[
  {
    "path": ".cspell.json",
    "content": "{\n  \"version\": \"0.2\",\n  \"language\": \"en\",\n  \"words\": [\n    \"claude\",\n    \"Claude\",\n    \"Anthropic\",\n    \"subagent\",\n    \"subagents\",\n    \"CLAUDE\",\n    \"MCP\",\n    \"Mermaid\",\n    \"frontmatter\",\n    \"pre-commit\",\n    \"Ruff\",\n    \"Bandit\",\n    \"EPUB\",\n    \"Sonnet\",\n    \"Opus\",\n    \"Haiku\",\n    \"luongnv89\",\n    \"claude-howto\",\n    \"ModelContextProtocol\",\n    \"YAML\",\n    \"JSON\",\n    \"API\",\n    \"DevOps\",\n    \"CRUD\",\n    \"CLI\",\n    \"SSH\",\n    \"HTTP\",\n    \"HTTPS\",\n    \"AWS\",\n    \"GitHub\",\n    \"GitLab\",\n    \"MongoDB\",\n    \"PostgreSQL\",\n    \"SQLite\",\n    \"Redis\",\n    \"JWT\",\n    \"OAuth\",\n    \"CORS\",\n    \"REST\",\n    \"GraphQL\",\n    \"TypeScript\",\n    \"JavaScript\",\n    \"Python\",\n    \"Bash\",\n    \"Unix\",\n    \"Linux\",\n    \"macOS\",\n    \"Windows\",\n    \"PowerShell\",\n    \"VSCode\",\n    \"IDE\",\n    \"MCP\",\n    \"Checks\",\n    \"checkpoints\",\n    \"THINKING\",\n    \"Headless\",\n    \"Headless mode\",\n    \"Kyrie\",\n    \"subprocesses\",\n    \"subprocess\",\n    \"checklist\",\n    \"checklists\",\n    \"customizable\",\n    \"customization\",\n    \"delegated\",\n    \"delegating\",\n    \"permissioning\",\n    \"GOPATH\",\n    \"goToDefinition\",\n    \"outgoingCalls\",\n    \"incomingCalls\",\n    \"docstring\",\n    \"docstrings\",\n    \"EOSMTP\",\n    \"OPENSPEC\",\n    \"Markdown\",\n    \"realtime\",\n    \"real-time\",\n    \"refactoring\",\n    \"runtime\",\n    \"namespace\",\n    \"namespacing\",\n    \"linting\",\n    \"pytest\",\n    \"Pytest\",\n    \"telemetry\",\n    \"caching\",\n    \"HTTPS\",\n    \"repo\",\n    \"repos\",\n    \"readme\",\n    \"README\",\n    \"mypy\",\n    \"wjhrdy\",\n    \"BigQuery\",\n    \"Sentry\",\n    \"bcherny\",\n    \"autoCheckpoint\",\n    \"autoEnter\",\n    \"backgroundTasks\",\n    \"extendedThinking\",\n    \"maxConcurrentTasks\",\n    \"PostCommit\",\n    \"PostToolUse\",\n    \"PreCommit\",\n    \"PrePush\",\n    \"PreToolUse\",\n    \"CODEOWNERS\",\n    \"PyPI\",\n    \"CVSS\",\n    \"CWE\",\n    \"OWASP\",\n    \"unrecognized\",\n    \"Dependabot\",\n    \"Codecov\",\n    \"codecov\",\n    \"pytest\",\n    \"anyio\",\n    \"asyncio\",\n    \"beautifulsoup\",\n    \"ebooklib\",\n    \"httpx\",\n    \"pillow\",\n    \"tenacity\",\n    \"cSpell\",\n    \"markdownlint\",\n    \"Kroki\",\n    \"setuptools\",\n    \"configurability\",\n    \"proactively\",\n    \"Kyrie\",\n    \"ChatGPT\",\n    \"GPT\",\n    \"Claude\",\n    \"Anthropic\",\n    \"OpenAI\",\n    \"subagent\",\n    \"emoji\",\n    \"emojis\",\n    \"reusable\",\n    \"scalability\",\n    \"latency\",\n    \"throughput\",\n    \"middleware\",\n    \"backend\",\n    \"frontend\",\n    \"middleware\",\n    \"templating\",\n    \"templated\",\n    \"serialization\",\n    \"deserialization\",\n    \"polymorphism\",\n    \"refactor\",\n    \"refactoring\",\n    \"refactored\",\n    \"reproducible\",\n    \"deterministic\",\n    \"probabilistic\",\n    \"hardcoded\",\n    \"tradeoff\",\n    \"tradeoffs\",\n    \"monorepo\",\n    \"monorepositories\",\n    \"idempotent\",\n    \"idempotence\",\n    \"mutable\",\n    \"immutable\",\n    \"invariant\",\n    \"invariants\",\n    \"docstring\",\n    \"docstrings\",\n    \"boilerplate\",\n    \"scaffolding\",\n    \"middleware\",\n    \"plugin\",\n    \"plugins\",\n    \"middleware\",\n    \"precommit\",\n    \"commitments\",\n    \"filesystem\",\n    \"subprocess\",\n    \"subprocesses\",\n    \"multiprocessing\",\n    \"Zod\",\n    \"zod\",\n    \"OpenAPI\",\n    \"RESTful\",\n    \"CRUD\",\n    \"SOLID\",\n    \"DRY\",\n    \"YAGNI\",\n    \"KISS\",\n    \"BATHWATER\",\n    \"scalable\",\n    \"configurable\",\n    \"maintainable\",\n    \"reliable\",\n    \"performant\",\n    \"resilient\",\n    \"idempotent\",\n    \"interoperable\",\n    \"composable\",\n    \"extensible\",\n    \"srcset\",\n    \"overcomplicate\",\n    \"Asana\",\n    \"oneline\",\n    \"anthropics\",\n    \"worktree\",\n    \"worktrees\",\n    \"dontAsk\",\n    \"VikalpP\",\n    \"sandboxed\",\n    \"Sandboxing\",\n    \"pycache\",\n    \"inlines\",\n    \"pyproject\",\n    \"Spawnable\",\n    \"spawnable\",\n    \"agentic\",\n    \"Ghostty\",\n    \"Backgrounding\",\n    \"AUTOCOMPACT\",\n    \"reconnections\",\n    \"CLAUDEAI\",\n    \"blocklist\",\n    \"Blocklist\",\n    \"mcporter\",\n    \"SESSIONEND\",\n    \"tiktoken\",\n    \"gopls\",\n    \"pyright\",\n    \"langserver\",\n    \"rustup\",\n    \"Lockdown\",\n    \"Checkpointing\",\n    \"opusplan\",\n    \"ultrathink\",\n    \"spacebar\",\n    \"MSIX\",\n    \"NONSTREAMING\",\n    \"startswith\",\n    \"unparse\"\n  ],\n  \"ignoreWords\": [\n    \"luongnv89\",\n    \"wjhrdy\",\n    \"Cherry\",\n    \"Boris\",\n    \"Cherny's\"\n  ],\n  \"ignoreRegExpList\": [\n    \"code\\\\{[^}]*\\\\}\",\n    \"```[\\\\s\\\\S]*?```\"\n  ],\n  \"overrides\": [\n    {\n      \"filename\": \"**/*.md\",\n      \"words\": [\n        \"commandline\",\n        \"cmd\"\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\ngithub: [luongnv89] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\nbuy_me_a_coffee: luongnv89 # Replace with a single Buy Me a Coffee username\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug Report\nabout: Report an issue with an example, guide, or documentation\ntitle: \"[BUG] \"\nlabels: bug\nassignees: ''\n\n---\n\n## Description\nBrief description of the issue.\n\n## Steps to Reproduce\n1. Step 1\n2. Step 2\n3. Step 3\n\n## Expected Behavior\nWhat should happen?\n\n## Actual Behavior\nWhat actually happened?\n\n## Environment\n- **Claude Code Version**: (e.g., 1.0.5)\n- **Operating System**: (e.g., macOS 14.1, Ubuntu 22.04, Windows 11)\n- **Python Version**: (if relevant, e.g., 3.11)\n- **Affected Component**: (e.g., 01-slash-commands, 03-skills, etc.)\n\n## Example Code\nIf applicable, provide the example code that's not working:\n```\n[Insert code here]\n```\n\n## Screenshots\nIf applicable, add screenshots showing the issue.\n\n## Additional Context\nAny other context that might help us understand the issue?\n\n## Possible Solution\nIf you have a suggestion for fixing this, share it here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Claude Code Documentation\n    url: https://code.claude.com/docs/en/overview\n    about: Official Claude Code documentation\n  - name: Discussions\n    url: https://github.com/luongnv89/claude-howto/discussions\n    about: Ask questions and share ideas with the community\n  - name: Anthropic Cookbook\n    url: https://github.com/anthropics/anthropic-cookbook\n    about: Official examples and guides from Anthropic\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/documentation.md",
    "content": "---\nname: Documentation Issue\nabout: Report unclear documentation, typos, or missing information\ntitle: \"[DOCS] \"\nlabels: documentation\nassignees: ''\n\n---\n\n## Type of Issue\n- [ ] Typo or grammar error\n- [ ] Unclear explanation\n- [ ] Missing information\n- [ ] Broken link or reference\n- [ ] Outdated content\n- [ ] Better example needed\n\n## Location\nWhich section has the issue?\n- **File**: (e.g., README.md, 03-skills/README.md)\n- **Section**: (e.g., \"Installation Quick Reference\")\n- **Line/Area**: (if specific)\n\n## Current Content\nWhat does it currently say?\n```\n[Paste the current text here]\n```\n\n## Issue Description\nWhat's wrong with it?\n\n## Suggested Improvement\nHow could this be improved or clarified?\n```\n[Provide improved text or suggestion here]\n```\n\n## Why This Matters\nHow does this issue impact users?\n\n## Related Documentation\nLinks to related sections:\n- Related Guide: <!-- Add link here -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature Request\nabout: Suggest a new example, guide, or improvement\ntitle: \"[FEATURE] \"\nlabels: enhancement\nassignees: ''\n\n---\n\n## Description\nDescribe the feature or improvement you'd like to see.\n\n## Problem It Solves\nWhat problem or gap does this address?\n\nExamples:\n- There's no example of X feature\n- The current documentation for Y is unclear\n- We need a guide for Z use case\n- The structure could be improved by...\n\n## Use Case\nWhen and how would this be used? Include real-world scenarios.\n\n## Proposed Solution\nHow should this be implemented or documented?\n\n## Example\nIf applicable, provide an example of what you envision:\n```\n[Insert example here]\n```\n\n## Related Examples\nLink any existing related examples or guides:\n- Existing Guide: <!-- Add link here -->\n- Feature: (e.g., Skills, Hooks, Subagents)\n\n## Additional Context\nAny other information that might be helpful?\n\n## Acceptance Criteria\nHow would you know this feature is complete?\n- [ ] Criterion 1\n- [ ] Criterion 2\n- [ ] Criterion 3\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question.md",
    "content": "---\nname: Question\nabout: Ask a question about Claude Code or this guide\ntitle: \"[QUESTION] \"\nlabels: question\nassignees: ''\n\n---\n\n## Question\nWhat would you like to know?\n\n## Context\nProvide some background or context for your question:\n- What are you trying to do?\n- What have you already tried?\n- What examples or guides have you looked at?\n\n## Relevant Topic\nWhich topic is this related to?\n- [ ] Slash Commands\n- [ ] Memory\n- [ ] Skills\n- [ ] Subagents\n- [ ] MCP Protocol\n- [ ] Hooks\n- [ ] Plugins\n- [ ] Checkpoints\n- [ ] Advanced Features\n- [ ] CLI Reference\n- [ ] Other\n\n## What You've Tried\nHave you already tried anything? What was the result?\n\n## Expected Outcome\nWhat would help you solve this?\n\n## Additional Resources\nAny links or resources that might be relevant?\n"
  },
  {
    "path": ".github/SECURITY_REPORTING.md",
    "content": "# Security Vulnerability Reporting\n\nThis file explains how to report security vulnerabilities to the Claude How To project.\n\n## Quick Links\n\n- **Private Reporting**: https://github.com/luongnv89/claude-howto/security/advisories\n- **Security Policy**: [SECURITY.md](../SECURITY.md)\n- **Report Template**: See below\n\n## Report a Vulnerability\n\n### Option 1: GitHub Private Vulnerability Report (RECOMMENDED)\n\nThis is the preferred method for reporting security vulnerabilities.\n\n**Steps:**\n1. Go to: https://github.com/luongnv89/claude-howto/security/advisories\n2. Click \"Report a vulnerability\"\n3. Fill in the details (use template below)\n4. Submit\n\n**Advantages:**\n- Keeps vulnerability private until fix is released\n- Automatic notifications to maintainers\n- Built-in collaboration features\n- Integrated with GitHub security tools\n\n### Option 2: GitHub Security Alert (For Dependencies)\n\nIf you discover a vulnerability in a dependency:\n\n1. Go to: https://github.com/luongnv89/claude-howto/security/dependabot/alerts\n2. Review the alert\n3. Create a pull request with the fix\n4. Tag with `security` label\n\n### Option 3: Private Email (If GitHub unavailable)\n\nIf you cannot use GitHub's reporting system:\n\n**Coming soon**: Security contact email will be added here\n\nFor now, use GitHub's private vulnerability reporting as described above.\n\n## Vulnerability Report Template\n\nUse this template when reporting a vulnerability:\n\n```\n**Title**: [Brief description of vulnerability]\n\n**Severity**: [Critical/High/Medium/Low]\nEstimated CVSS Score: [0-10]\n\n**Type**: [Code/Documentation/Dependency/Configuration]\n\n**Affected Component**:\n- File: [path/to/file.py]\n- Section: [Section name if documentation]\n- Version: [latest/specific version]\n\n**Description**:\n[Clear explanation of what the vulnerability is]\n\n**Potential Impact**:\n[What could an attacker do with this vulnerability?]\n[Who could be affected?]\n\n**Steps to Reproduce**:\n1. [First step]\n2. [Second step]\n3. [Third step]\n[Expected result vs actual result]\n\n**Proof of Concept** (if available):\n[Code or steps to demonstrate the vulnerability]\n\n**Suggested Fix**:\n[Your recommended solution, if you have one]\n\n**Additional Context**:\n[Any other relevant information]\n\n**Your Information**:\n- Name: [Your name or anonymous]\n- Email: [Your email]\n- Credit: [How you'd like to be credited, if at all]\n```\n\n## What Happens After You Report\n\n### Timeline\n\n1. **Immediate (< 1 hour)**\n   - Automatic notification sent to project maintainers\n\n2. **Within 24 hours**\n   - Initial assessment of the report\n   - Confirmation that we received it\n   - Preliminary severity assessment\n\n3. **Within 48 hours**\n   - Detailed response from security team\n   - Questions for clarification (if needed)\n   - Timeline for fix (if vulnerability confirmed)\n\n4. **Within 1-7 days** (depends on severity)\n   - Fix developed and tested\n   - Security advisory prepared\n   - Fix released and public advisory published\n\n### Communication\n\nWe will keep you informed through:\n- GitHub private vulnerability discussion\n- Email (if provided)\n- Updates in the discussion thread\n\nYou can:\n- Ask clarifying questions\n- Provide additional information\n- Suggest improvements to the fix\n- Request timeline adjustments\n\n### Disclosure Timeline\n\n**Critical Issues (CVSS 9.0-10.0)**\n- Fix: Released immediately (within 24 hours)\n- Disclosure: Public advisory issued same day\n- Notice: 24 hours advance notice to reporter\n\n**High Issues (CVSS 7.0-8.9)**\n- Fix: Released within 48-72 hours\n- Disclosure: Public advisory on release\n- Notice: 5 days advance notice to reporter\n\n**Medium Issues (CVSS 4.0-6.9)**\n- Fix: Included in next regular update\n- Disclosure: Public advisory on release\n- Notice: Coordinated timing\n\n**Low Issues (CVSS 0.1-3.9)**\n- Fix: Included in next regular update\n- Disclosure: Advisory on release\n- Notice: Same day as release\n\n## Security Vulnerability Criteria\n\n### In Scope\n\nWe accept reports on:\n\n- **Code Vulnerabilities**\n  - Injection attacks (command, SQL, etc.)\n  - Cross-site scripting (XSS) in examples\n  - Authentication/authorization flaws\n  - Path traversal vulnerabilities\n  - Cryptography issues\n\n- **Documentation Security**\n  - Exposed secrets or credentials\n  - Insecure code patterns\n  - Security anti-patterns\n  - Misleading security claims\n\n- **Dependency Vulnerabilities**\n  - Known CVEs in dependencies\n  - Supply chain attacks\n  - Malicious dependencies\n\n- **Configuration Issues**\n  - Insecure defaults\n  - Missing security headers\n  - Credential exposure in examples\n\n### Out of Scope\n\nWe do NOT accept reports on:\n\n- Vulnerabilities in Claude Code itself (contact Anthropic)\n- Vulnerabilities in external services\n- Theoretical vulnerabilities without proof\n- Issues already reported to upstream projects\n- Social engineering or phishing\n- User education/training issues\n\n## Responsible Disclosure Guidelines\n\n### Do's ✅\n\n- **Report privately** before public disclosure\n- **Be specific** with file paths and line numbers\n- **Provide proof** of the vulnerability\n- **Give us time** to fix (coordinated disclosure)\n- **Update** if you discover more details\n- **Be professional** in all communications\n- **Respect confidentiality** until we publish\n\n### Don'ts ❌\n\n- **Don't publicly disclose** before we fix\n- **Don't exploit** the vulnerability beyond testing\n- **Don't modify** other users' data\n- **Don't demand** payment or favors\n- **Don't share** the vulnerability with others\n- **Don't use** it in any harmful way\n- **Don't spam** with non-security related issues\n\n## Coordinated Disclosure\n\nWe practice responsible disclosure:\n\n1. **Private Report**: You report to us privately\n2. **Our Assessment**: We evaluate and assess severity\n3. **Fix Development**: We develop and test a fix\n4. **Advance Notice**: We give you advance notice before public disclosure\n5. **Public Release**: We release fix and advisory together\n6. **Your Credit**: We acknowledge your contribution (if desired)\n\n**Timeline varies based on severity** (see section above)\n\n## After the Fix is Released\n\n### Public Advisory\n\nA public security advisory will include:\n- Description of the vulnerability\n- Affected versions\n- Severity (CVSS score)\n- Steps to remediate\n- Link to the fix\n- Credit to reporter (with permission)\n\n### Your Recognition\n\nIf you wish to be credited:\n- Your name/handle in the advisory\n- Link to your profile/website\n- Mention in release notes\n- Addition to hall of fame (if created)\n\n### No Compensation\n\nPlease note:\n- This is a volunteer-run open-source project\n- We cannot offer financial rewards\n- We do offer recognition and credit\n- Your contribution helps the community\n\n## Security Research\n\nIf you're conducting security research:\n\n1. **Get Permission**: Contact maintainers first\n2. **Define Scope**: Agree on what you'll test\n3. **Report Findings**: Use this process\n4. **Respect Timeline**: Allow time for fixes\n5. **Publish Responsibly**: Coordinate with us\n\n## Questions?\n\nFor questions about this process:\n\n1. Check [SECURITY.md](../SECURITY.md) for detailed policy\n2. Look at [FAQ](#faq) section below\n3. Open a discussion with `[SECURITY]` label\n4. Use private vulnerability reporting for sensitive questions\n\n## FAQ\n\n**Q: Will my report be kept confidential?**\nA: Yes, until the fix is released. We only share details with those working on the fix.\n\n**Q: How long do I need to wait before public disclosure?**\nA: We follow responsible disclosure timelines based on severity (24 hours to 7 days). You can agree to extend this if needed.\n\n**Q: Will I get credit?**\nA: Yes, in the security advisory and release notes (unless you prefer anonymity).\n\n**Q: What if the vulnerability is minor?**\nA: All legitimate security issues are taken seriously. Even minor fixes will be acknowledged.\n\n**Q: Can I report vulnerabilities in documentation only?**\nA: Yes! Documentation security is important too. Examples with insecure patterns are in scope.\n\n**Q: What if I'm not sure if something is a security issue?**\nA: Report it anyway! If it's not a security issue, we'll let you know. False positives are fine.\n\n**Q: Can I publicly discuss the vulnerability after reporting?**\nA: No, please keep it private until we publish the advisory. Premature disclosure could put users at risk.\n\n**Q: How do I know you received my report?**\nA: GitHub will send an automatic notification, and we'll follow up within 24 hours.\n\n**Q: What if I don't hear back?**\nA: Check GitHub security advisories page. If you still don't see a response, you can follow up with a comment on the private report.\n\n## Resources\n\n- [SECURITY.md](../SECURITY.md) - Full security policy\n- [CONTRIBUTING.md](../CONTRIBUTING.md) - Contributing guidelines\n- [CODE_OF_CONDUCT.md](../CODE_OF_CONDUCT.md) - Community standards\n- [OWASP Vulnerability Disclosure](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html) - Responsible disclosure best practices\n- [Coordinated Vulnerability Disclosure](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerable_Dependency_Management_Cheat_Sheet.html)\n\n---\n\nThank you for helping keep this project secure! 🔒\n"
  },
  {
    "path": ".github/TESTING.md",
    "content": "# Testing Guide\n\nThis document describes the testing infrastructure for Claude How To.\n\n## Overview\n\nThe project uses GitHub Actions to automatically run tests on every push and pull request. Tests cover:\n\n- **Unit Tests**: Python tests using pytest\n- **Code Quality**: Linting and formatting with Ruff\n- **Security**: Vulnerability scanning with Bandit\n- **Type Checking**: Static type analysis with mypy\n- **Build Verification**: EPUB generation test\n\n## Running Tests Locally\n\n### Prerequisites\n\n```bash\n# Install uv (fast Python package manager)\npip install uv\n\n# Or on macOS with Homebrew\nbrew install uv\n```\n\n### Setup Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/luongnv89/claude-howto.git\ncd claude-howto\n\n# Create virtual environment\nuv venv\n\n# Activate it\nsource .venv/bin/activate  # macOS/Linux\n# or\n.venv\\Scripts\\activate     # Windows\n\n# Install development dependencies\nuv pip install -r requirements-dev.txt\n```\n\n### Run Tests\n\n```bash\n# Run all unit tests\npytest scripts/tests/ -v\n\n# Run tests with coverage\npytest scripts/tests/ -v --cov=scripts --cov-report=html\n\n# Run specific test file\npytest scripts/tests/test_build_epub.py -v\n\n# Run specific test function\npytest scripts/tests/test_build_epub.py::test_function_name -v\n\n# Run tests in watch mode (requires pytest-watch)\nptw scripts/tests/\n```\n\n### Run Linting\n\n```bash\n# Check code formatting\nruff format --check scripts/\n\n# Auto-fix formatting issues\nruff format scripts/\n\n# Run linter\nruff check scripts/\n\n# Auto-fix linter issues\nruff check --fix scripts/\n```\n\n### Run Security Scan\n\n```bash\n# Run Bandit security scan\nbandit -c pyproject.toml -r scripts/ --exclude scripts/tests/\n\n# Generate JSON report\nbandit -c pyproject.toml -r scripts/ --exclude scripts/tests/ -f json -o bandit-report.json\n```\n\n### Run Type Checking\n\n```bash\n# Check types with mypy\nmypy scripts/ --ignore-missing-imports --no-implicit-optional\n```\n\n## GitHub Actions Workflow\n\n### Triggered On\n\n- **Push** to `main` or `develop` branches (when scripts change)\n- **Pull Request** to `main` (when scripts change)\n- Manual workflow dispatch\n\n### Jobs\n\n#### 1. Unit Tests (pytest)\n\n- **Runs on**: Ubuntu latest\n- **Python versions**: 3.10, 3.11, 3.12\n- **What it does**:\n  - Installs dependencies from `requirements-dev.txt`\n  - Runs pytest with coverage reporting\n  - Uploads coverage to Codecov\n  - Archives test results and coverage HTML\n\n**Outcome**: If any test fails, the workflow fails (critical)\n\n#### 2. Code Quality (Ruff)\n\n- **Runs on**: Ubuntu latest\n- **Python version**: 3.11\n- **What it does**:\n  - Checks code formatting with `ruff format`\n  - Runs linter with `ruff check`\n  - Reports issues but doesn't fail the workflow\n\n**Outcome**: Non-blocking (warning only)\n\n#### 3. Security Scan (Bandit)\n\n- **Runs on**: Ubuntu latest\n- **Python version**: 3.11\n- **What it does**:\n  - Scans for security vulnerabilities\n  - Generates JSON report\n  - Uploads report as artifact\n\n**Outcome**: Non-blocking (warning only)\n\n#### 4. Type Checking (mypy)\n\n- **Runs on**: Ubuntu latest\n- **Python version**: 3.11\n- **What it does**:\n  - Performs static type analysis\n  - Reports type mismatches\n  - Helps catch bugs early\n\n**Outcome**: Non-blocking (warning only)\n\n#### 5. Build EPUB\n\n- **Runs on**: Ubuntu latest\n- **Depends on**: pytest, lint, security (all must pass)\n- **What it does**:\n  - Builds the EPUB file using `scripts/build_epub.py`\n  - Verifies the EPUB was created successfully\n  - Uploads EPUB as artifact\n\n**Outcome**: If build fails, the workflow fails (critical)\n\n#### 6. Summary\n\n- **Runs on**: Ubuntu latest\n- **Depends on**: All other jobs\n- **What it does**:\n  - Generates workflow summary\n  - Lists all artifacts\n  - Reports overall status\n\n## Writing Tests\n\n### Test Structure\n\nTests should be placed in `scripts/tests/` with names like `test_*.py`:\n\n```python\n# scripts/tests/test_example.py\nimport pytest\nfrom scripts.example_module import some_function\n\ndef test_basic_functionality():\n    \"\"\"Test that some_function works correctly.\"\"\"\n    result = some_function(\"input\")\n    assert result == \"expected_output\"\n\ndef test_error_handling():\n    \"\"\"Test that some_function handles errors gracefully.\"\"\"\n    with pytest.raises(ValueError):\n        some_function(\"invalid_input\")\n\n@pytest.mark.asyncio\nasync def test_async_function():\n    \"\"\"Test async functions.\"\"\"\n    result = await async_function()\n    assert result is not None\n```\n\n### Test Best Practices\n\n- **Use descriptive names**: `test_function_returns_correct_value()`\n- **One assertion per test** (when possible): Easier to debug failures\n- **Use fixtures** for reusable setup: See `scripts/tests/conftest.py`\n- **Mock external services**: Use `unittest.mock` or `pytest-mock`\n- **Test edge cases**: Empty inputs, None values, errors\n- **Keep tests fast**: Avoid sleep() and external I/O\n- **Use pytest markers**: `@pytest.mark.slow` for slow tests\n\n### Fixtures\n\nCommon fixtures are defined in `scripts/tests/conftest.py`:\n\n```python\n# Use fixtures in your tests\ndef test_something(tmp_path):\n    \"\"\"tmp_path fixture provides temporary directory.\"\"\"\n    test_file = tmp_path / \"test.txt\"\n    test_file.write_text(\"content\")\n    assert test_file.read_text() == \"content\"\n```\n\n## Coverage Reports\n\n### Local Coverage\n\n```bash\n# Generate coverage report\npytest scripts/tests/ --cov=scripts --cov-report=html\n\n# Open the coverage report in your browser\nopen htmlcov/index.html\n```\n\n### Coverage Goals\n\n- **Minimum coverage**: 80%\n- **Branch coverage**: Enabled\n- **Focus areas**: Core functionality and error paths\n\n## Pre-commit Hooks\n\nThe project uses pre-commit hooks to run checks automatically before commits:\n\n```bash\n# Install pre-commit hooks\npre-commit install\n\n# Run hooks manually\npre-commit run --all-files\n\n# Skip hooks for a commit (not recommended)\ngit commit --no-verify\n```\n\nConfigured hooks in `.pre-commit-config.yaml`:\n- Ruff formatter\n- Ruff linter\n- Bandit security scanner\n- YAML validation\n- File size checks\n- Merge conflict detection\n\n## Troubleshooting\n\n### Tests Pass Locally but Fail in CI\n\nCommon causes:\n1. **Python version difference**: CI uses 3.10, 3.11, 3.12\n2. **Missing dependencies**: Update `requirements-dev.txt`\n3. **Platform differences**: Path separators, environment variables\n4. **Flaky tests**: Tests that depend on timing or order\n\nSolution:\n```bash\n# Test with the same Python versions\nuv python install 3.10 3.11 3.12\n\n# Test with clean environment\nrm -rf .venv\nuv venv\nuv pip install -r requirements-dev.txt\npytest scripts/tests/\n```\n\n### Bandit Reports False Positives\n\nSome security warnings may be false positives. Configure in `pyproject.toml`:\n\n```toml\n[tool.bandit]\nexclude_dirs = [\"scripts/tests\"]\nskips = [\"B101\"]  # Skip assert_used warning\n```\n\n### Type Checking Too Strict\n\nRelax type checking for specific files:\n\n```python\n# Add at the top of file\n# type: ignore\n\n# Or for specific lines\nsome_dynamic_code()  # type: ignore\n```\n\n## Continuous Integration Best Practices\n\n1. **Keep tests fast**: Each test should complete in <1 second\n2. **Don't test external APIs**: Mock external services\n3. **Test in isolation**: Each test should be independent\n4. **Use clear assertions**: `assert x == 5` not `assert x`\n5. **Handle async tests**: Use `@pytest.mark.asyncio`\n6. **Generate reports**: Coverage, security, type checking\n\n## Resources\n\n- [pytest Documentation](https://docs.pytest.org/)\n- [Ruff Documentation](https://docs.astral.sh/ruff/)\n- [Bandit Documentation](https://bandit.readthedocs.io/)\n- [mypy Documentation](https://mypy.readthedocs.io/)\n- [GitHub Actions Documentation](https://docs.github.com/en/actions)\n\n## Contributing Tests\n\nWhen submitting a PR:\n\n1. **Write tests** for new functionality\n2. **Run tests locally**: `pytest scripts/tests/ -v`\n3. **Check coverage**: `pytest scripts/tests/ --cov=scripts`\n4. **Run linting**: `ruff check scripts/`\n5. **Security scan**: `bandit -r scripts/ --exclude scripts/tests/`\n6. **Update documentation** if tests change\n\nTests are required for all PRs! 🧪\n\n---\n\nFor questions or issues with testing, open a GitHub issue or discussion.\n"
  },
  {
    "path": ".github/markdown-link-check-config.json",
    "content": "{\n  \"ignorePatterns\": [\n    {\n      \"pattern\": \"^https://docs\\\\.example\\\\.com\",\n      \"comment\": \"Example placeholder URLs in documentation templates\"\n    },\n    {\n      \"pattern\": \"^\\\\./docs/\",\n      \"comment\": \"Example relative paths in documentation templates\"\n    },\n    {\n      \"pattern\": \"^FORMS\\\\.md$|^REFERENCE\\\\.md$\",\n      \"comment\": \"Example file references in skill templates\"\n    },\n    {\n      \"pattern\": \"^https://en\\\\.wikipedia\\\\.org/wiki/N%2B1\",\n      \"comment\": \"Wikipedia N+1 article - URL encoding issues\"\n    },\n    {\n      \"pattern\": \"^https://twitter.com\",\n      \"comment\": \"Twitter/X links require authentication\"\n    },\n    {\n      \"pattern\": \"^https://x.com\",\n      \"comment\": \"X (Twitter) links require authentication\"\n    },\n    {\n      \"pattern\": \"^https://github.com/[^/]+/claude-howto\",\n      \"comment\": \"Self-referencing links\"\n    },\n    {\n      \"pattern\": \"^https://docs\\\\.claude\\\\.com\",\n      \"comment\": \"Claude docs - URL structure may vary\"\n    },\n    {\n      \"pattern\": \"^https://docs\\\\.anthropic\\\\.com\",\n      \"comment\": \"Anthropic docs - May have authentication or access restrictions\"\n    },\n    {\n      \"pattern\": \"^https://code\\\\.claude\\\\.com\",\n      \"comment\": \"Claude Code docs - May have dynamic content or routing issues\"\n    },\n    {\n      \"pattern\": \"^https://plugins\\\\.claude\\\\.com\",\n      \"comment\": \"Plugin marketplace - May have access restrictions\"\n    },\n    {\n      \"pattern\": \"^https://medium\\\\.com\",\n      \"comment\": \"Medium posts - May have paywall or tracking restrictions\"\n    },\n    {\n      \"pattern\": \"^https://modelcontextprotocol\\\\.io\",\n      \"comment\": \"MCP docs - May have infrastructure limitations\"\n    },\n    {\n      \"pattern\": \"^https://discord\\\\.gg\",\n      \"comment\": \"Discord invite links - May expire or have access issues\"\n    },\n    {\n      \"pattern\": \"^https://bsky\\\\.app\",\n      \"comment\": \"BlueSky links - May require authentication\"\n    },\n    {\n      \"pattern\": \"^https://api\\\\.star-history\\\\.com\",\n      \"comment\": \"External badge service - May have rate limiting\"\n    },\n    {\n      \"pattern\": \"^https://jazz\\\\.tools\",\n      \"comment\": \"External tool links - May have dynamic routing\"\n    },\n    {\n      \"pattern\": \"^https://mcp\\\\.notion\\\\.com\",\n      \"comment\": \"Notion-hosted docs - May require authentication\"\n    }\n  ],\n  \"replacementPatterns\": [\n    {\n      \"pattern\": \"^/\",\n      \"replacement\": \"https://github.com/luongnv89/claude-howto/blob/main/\"\n    }\n  ],\n  \"timeout\": 10000,\n  \"retryOn\": [429, 503],\n  \"retryCount\": 3,\n  \"fallbackRetryDelay\": 5000,\n  \"aliveStatusCodes\": [200, 206]\n}\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "## Description\nBrief summary of what this PR does.\n\n## Type of Change\n- [ ] New example or template\n- [ ] Documentation improvement\n- [ ] Bug fix\n- [ ] Feature guide\n- [ ] Other (please describe)\n\n## Related Issues\nCloses #(issue number)\n\n## Changes Made\n- Change 1\n- Change 2\n- Change 3\n\n## What to Review\nWhat should reviewers focus on?\n\n## Files Changed\n- `path/to/file1.md`\n- `path/to/file2.md`\n\n## Testing\nHow have you tested this?\n- [ ] Tested locally with Claude Code\n- [ ] Verified examples work\n- [ ] Checked links and references\n- [ ] Reviewed for typos and clarity\n\n## Checklist\n- [ ] Follows project structure and conventions\n- [ ] Includes clear documentation/examples\n- [ ] Code/examples are copy-paste ready\n- [ ] All links are verified and working\n- [ ] No sensitive information included (keys, tokens, credentials)\n- [ ] Updated relevant README files\n- [ ] Commit message follows conventional commit format\n- [ ] No large files (>1MB) added\n\n## Screenshots or Examples\nIf applicable, show what this adds:\n```\n[Example code or before/after comparison]\n```\n\n## Breaking Changes\nDoes this change any existing content or behavior?\n- [ ] No breaking changes\n- [ ] Yes, and it's documented below\n\nIf yes, please describe:\n\n## Additional Notes\nAny other information for reviewers?\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\n# Cancel in-progress runs for the same branch\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\njobs:\n  lint:\n    name: Lint & Format\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install Ruff\n        run: |\n          uv venv\n          uv pip install ruff\n\n      - name: Ruff Format Check\n        run: uv run ruff format --check scripts/\n\n      - name: Ruff Lint Check\n        run: uv run ruff check scripts/\n\n  security:\n    name: Security Scan\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install Bandit\n        run: |\n          uv venv\n          uv pip install \"bandit[toml]\"\n\n      - name: Run Bandit Security Scan\n        run: uv run bandit -c scripts/pyproject.toml -r scripts/ --exclude scripts/tests/\n\n  test:\n    name: Unit Tests (Python ${{ matrix.python-version }})\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        python-version: ['3.10', '3.11', '3.12']\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python ${{ matrix.python-version }}\n        run: uv python install ${{ matrix.python-version }}\n\n      - name: Create venv and install dependencies\n        run: |\n          uv venv\n          uv pip install -r scripts/requirements-dev.txt\n\n      - name: Run pytest with coverage\n        run: uv run pytest scripts/tests/ -v --tb=short --cov=scripts --cov-report=xml --cov-report=term-missing\n\n      - name: Upload coverage to Codecov\n        uses: codecov/codecov-action@v3\n        with:\n          files: ./coverage.xml\n          flags: unittests\n          name: codecov-python-${{ matrix.python-version }}\n          fail_ci_if_error: false\n\n  build:\n    name: Build EPUB\n    runs-on: ubuntu-latest\n    needs: [lint, security, test]\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install dependencies\n        run: |\n          uv venv\n          uv pip install -r scripts/requirements-dev.txt\n\n      - name: Build EPUB\n        run: uv run scripts/build_epub.py\n\n      - name: Verify EPUB Created\n        run: |\n          if [ -f claude-howto-guide.epub ]; then\n            echo \"EPUB built successfully\"\n            ls -lh claude-howto-guide.epub\n          else\n            echo \"EPUB file not found!\"\n            exit 1\n          fi\n\n      - name: Upload EPUB Artifact\n        uses: actions/upload-artifact@v4\n        with:\n          name: claude-howto-guide-epub\n          path: claude-howto-guide.epub\n          retention-days: 7\n"
  },
  {
    "path": ".github/workflows/docs-check.yml",
    "content": "name: Documentation Checks\n\non:\n  push:\n    branches: [main]\n    paths:\n      - '**.md'\n      - '.github/workflows/docs-check.yml'\n      - '.cspell.json'\n      - '.github/markdown-link-check-config.json'\n  pull_request:\n    branches: [main]\n    paths:\n      - '**.md'\n      - 'CONTRIBUTING.md'\n      - 'LICENSE'\n      - '.cspell.json'\n      - '.github/markdown-link-check-config.json'\n\n# Cancel in-progress runs for the same branch\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\njobs:\n  markdown-lint:\n    name: Markdown Linting\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v4\n        with:\n          node-version: '18'\n\n      - name: Install markdownlint-cli\n        run: npm install -g markdownlint-cli\n\n      - name: Run Markdown Linter\n        run: markdownlint '**/*.md' --ignore node_modules --ignore .venv\n        continue-on-error: true\n\n  link-check:\n    name: Check Links\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Check markdown links\n        uses: gaurav-nelson/github-action-markdown-link-check@v1\n        with:\n          use-quiet-mode: 'yes'\n          use-verbose-mode: 'no'\n          config-file: '.github/markdown-link-check-config.json'\n\n  spelling:\n    name: Spell Check\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Run cSpell\n        uses: streetsidesoftware/cspell-action@v6\n        with:\n          files: |\n            **/*.md\n            **/*.json\n            **/*.yml\n            **/*.yaml\n          incremental: 'no'\n          config: '.cspell.json'\n\n  frontmatter:\n    name: YAML Frontmatter Validation\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Setup Python\n        uses: actions/setup-python@v4\n        with:\n          python-version: '3.11'\n\n      - name: Install PyYAML\n        run: pip install pyyaml\n\n      - name: Validate YAML Frontmatter\n        run: |\n          python3 << 'EOF'\n          import os\n          import yaml\n          import re\n          from pathlib import Path\n\n          errors = []\n\n          # Check all markdown files in Claude sections\n          md_files = list(Path('.').glob('**/README.md')) + list(Path('.').glob('01-*/**/*.md'))\n\n          for file_path in md_files:\n              if '.venv' in str(file_path) or 'node_modules' in str(file_path):\n                  continue\n\n              with open(file_path, 'r') as f:\n                  content = f.read()\n\n              # Check for YAML frontmatter in skill/agent templates\n              if 'SKILL.md' in str(file_path) or any(x in str(file_path) for x in ['agent', 'template']):\n                  if content.startswith('---'):\n                      try:\n                          # Extract frontmatter\n                          parts = content.split('---', 2)\n                          if len(parts) >= 3:\n                              yaml.safe_load(parts[1])\n                      except yaml.YAMLError as e:\n                          errors.append(f\"{file_path}: Invalid YAML frontmatter - {e}\")\n                  else:\n                      if 'skill' in str(file_path).lower():\n                          print(f\"⚠ {file_path}: Consider adding YAML frontmatter\")\n\n          if errors:\n              for error in errors:\n                  print(f\"❌ {error}\")\n              exit(1)\n          else:\n              print(\"✅ All YAML frontmatter is valid\")\n          EOF\n\n  structure:\n    name: Documentation Structure\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Setup Python\n        uses: actions/setup-python@v4\n        with:\n          python-version: '3.11'\n\n      - name: Validate Documentation Structure\n        run: |\n          python3 << 'EOF'\n          import os\n          from pathlib import Path\n          import re\n\n          errors = []\n          warnings = []\n\n          # Check that all numbered directories have README.md\n          for i in range(1, 11):\n              dir_path = Path(f\"{i:02d}-*\")\n              matches = list(dir_path.parent.glob(str(dir_path)))\n              if matches:\n                  for match in matches:\n                      if (match / \"README.md\").exists():\n                          print(f\"✅ {match}/README.md found\")\n                      else:\n                          errors.append(f\"{match}: Missing README.md\")\n\n          # Check README.md has required sections\n          readme_path = Path(\"README.md\")\n          if readme_path.exists():\n              with open(readme_path) as f:\n                  content = f.read()\n\n              required_sections = [\n                  \"## Table of Contents\",\n                  \"## Contributing\",\n                  \"## License\",\n              ]\n\n              for section in required_sections:\n                  if section not in content:\n                      errors.append(f\"README.md: Missing '{section}' section\")\n                  else:\n                      print(f\"✅ README.md has '{section}' section\")\n\n          # Check for broken relative links\n          md_files = list(Path(\".\").rglob(\"*.md\"))\n          for file_path in md_files:\n              if \".venv\" in str(file_path) or \"node_modules\" in str(file_path):\n                  continue\n\n              with open(file_path) as f:\n                  content = f.read()\n\n              # Find markdown links to local files\n              local_links = re.findall(r'\\[([^\\]]+)\\]\\(([^)]+\\.md)\\)', content)\n              for link_text, link_path in local_links:\n                  # Skip anchor-only links\n                  if link_path.startswith(\"#\"):\n                      continue\n\n                  resolved_path = (file_path.parent / link_path).resolve()\n                  if not resolved_path.exists():\n                      warnings.append(f\"{file_path}: Broken link to '{link_path}'\")\n\n          if errors:\n              print(\"\\n❌ Validation Errors:\")\n              for error in errors:\n                  print(f\"  - {error}\")\n              exit(1)\n\n          if warnings:\n              print(\"\\n⚠ Warnings:\")\n              for warning in warnings:\n                  print(f\"  - {warning}\")\n\n          print(\"\\n✅ Documentation structure is valid\")\n          EOF\n\n  metadata:\n    name: File Metadata Checks\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Check for common issues\n        run: |\n          set +e  # Don't exit on first error\n\n          echo \"📋 Checking for documentation issues...\"\n\n          # Check for files over 100KB\n          echo \"Checking file sizes...\"\n          large_files=$(find . -name \"*.md\" -size +100k | grep -v \".venv\" | grep -v \"node_modules\")\n          if [ ! -z \"$large_files\" ]; then\n            echo \"⚠ Large markdown files found (>100KB):\"\n            echo \"$large_files\"\n          fi\n\n          # Check for TODO markers (might indicate incomplete content)\n          echo \"Checking for TODO markers in main docs...\"\n          todos=$(grep -r \"TODO\\|FIXME\" --include=\"*.md\" . --exclude-dir=.venv --exclude-dir=node_modules --exclude-dir=.git | grep -v \".github\" | head -10)\n          if [ ! -z \"$todos\" ]; then\n            echo \"⚠ Found TODO/FIXME markers:\"\n            echo \"$todos\"\n          fi\n\n          # Check for consistent heading structure\n          echo \"Checking heading consistency in key files...\"\n          for file in README.md CONTRIBUTING.md; do\n            if [ -f \"$file\" ]; then\n              heading_count=$(grep -c \"^##\" \"$file\")\n              echo \"✅ $file has $heading_count main sections\"\n            fi\n          done\n\n          # Check that LICENSE file exists\n          if [ -f \"LICENSE\" ]; then\n            echo \"✅ LICENSE file exists\"\n          else\n            echo \"❌ LICENSE file not found\"\n            exit 1\n          fi\n\n  consistency:\n    name: Content Consistency\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Setup Python\n        uses: actions/setup-python@v4\n        with:\n          python-version: '3.11'\n\n      - name: Check Content Consistency\n        run: |\n          python3 << 'EOF'\n          import re\n          from pathlib import Path\n\n          errors = []\n\n          # Check that all numbered sections are referenced in README\n          readme_path = Path(\"README.md\")\n          with open(readme_path) as f:\n              readme_content = f.read()\n\n          # Look for numbered directories\n          for i in range(1, 11):\n              dir_pattern = f\"{i:02d}-\"\n              dirs = list(Path(\".\").glob(f\"{dir_pattern}*\"))\n\n              if dirs:\n                  for dir_path in dirs:\n                      if dir_path.is_dir():\n                          # Check if referenced in README\n                          dir_name = dir_path.name\n                          if dir_name not in readme_content:\n                              errors.append(f\"README.md: Directory '{dir_name}' not mentioned\")\n                          else:\n                              print(f\"✅ '{dir_name}' is referenced in README\")\n\n          # Check for consistent code fence formatting\n          md_files = [f for f in Path(\".\").rglob(\"*.md\") if \".venv\" not in str(f)]\n          for file_path in md_files:\n              with open(file_path) as f:\n                  content = f.read()\n\n              # Count code fence types\n              backtick_fences = len(re.findall(r'```', content))\n              if backtick_fences % 2 != 0:\n                  errors.append(f\"{file_path}: Unmatched code fences (backticks)\")\n\n          if errors:\n              print(\"\\n❌ Consistency Errors:\")\n              for error in errors:\n                  print(f\"  - {error}\")\n              exit(1)\n\n          print(\"\\n✅ Content is consistent\")\n          EOF\n\n  summary:\n    name: Summary\n    needs: [markdown-lint, link-check, spelling, frontmatter, structure, metadata, consistency]\n    runs-on: ubuntu-latest\n    if: always()\n    steps:\n      - name: Check Job Results\n        run: |\n          if [ \"${{ needs.markdown-lint.result }}\" = \"failure\" ] || \\\n             [ \"${{ needs.link-check.result }}\" = \"failure\" ] || \\\n             [ \"${{ needs.spelling.result }}\" = \"failure\" ] || \\\n             [ \"${{ needs.frontmatter.result }}\" = \"failure\" ] || \\\n             [ \"${{ needs.structure.result }}\" = \"failure\" ] || \\\n             [ \"${{ needs.metadata.result }}\" = \"failure\" ] || \\\n             [ \"${{ needs.consistency.result }}\" = \"failure\" ]; then\n            echo \"❌ Some documentation checks failed\"\n            exit 1\n          else\n            echo \"✅ All documentation checks passed!\"\n          fi\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Build and Release EPUB\n\non:\n  push:\n    tags:\n      - 'v*'\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n\n    steps:\n      - uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Build EPUB\n        run: uv run scripts/build_epub.py\n\n      - name: Create Release\n        uses: softprops/action-gh-release@v2\n        with:\n          files: claude-howto-guide.epub\n          generate_release_notes: true\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Automated Testing\n\non:\n  push:\n    branches: [main, develop]\n    paths:\n      - 'scripts/**'\n      - '.github/workflows/test.yml'\n      - 'pyproject.toml'\n      - 'requirements*.txt'\n  pull_request:\n    branches: [main]\n    paths:\n      - 'scripts/**'\n      - '.github/workflows/test.yml'\n      - 'pyproject.toml'\n      - 'requirements*.txt'\n\n# Cancel in-progress runs for the same branch\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\njobs:\n  pytest:\n    name: Unit Tests (Python ${{ matrix.python-version }})\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        python-version: ['3.10', '3.11', '3.12']\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python ${{ matrix.python-version }}\n        run: uv python install ${{ matrix.python-version }}\n\n      - name: Create venv and install dependencies\n        run: |\n          uv venv\n          uv pip install -r scripts/requirements-dev.txt\n\n      - name: Run pytest\n        run: uv run pytest scripts/tests/ -v --tb=short --cov=scripts --cov-report=xml --cov-report=html\n        continue-on-error: false\n\n      - name: Upload coverage to Codecov\n        uses: codecov/codecov-action@v3\n        with:\n          files: ./coverage.xml\n          flags: unittests\n          name: codecov-python-${{ matrix.python-version }}\n          fail_ci_if_error: false\n          verbose: true\n\n      - name: Archive test results\n        if: always()\n        uses: actions/upload-artifact@v4\n        with:\n          name: pytest-results-${{ matrix.python-version }}\n          path: |\n            coverage.xml\n            htmlcov/\n          retention-days: 7\n\n  lint:\n    name: Code Quality (Lint & Format)\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install Ruff\n        run: |\n          uv venv\n          uv pip install ruff\n\n      - name: Ruff Format Check\n        run: uv run ruff format --check scripts/\n        continue-on-error: true\n\n      - name: Ruff Lint Check\n        run: uv run ruff check scripts/\n        continue-on-error: true\n\n  security:\n    name: Security Scan\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install Bandit\n        run: |\n          uv venv\n          uv pip install \"bandit[toml]\"\n\n      - name: Run Bandit Security Scan\n        run: uv run bandit -c pyproject.toml -r scripts/ --exclude scripts/tests/ -f json -o bandit-report.json\n        continue-on-error: true\n\n      - name: Upload security report\n        uses: actions/upload-artifact@v4\n        if: always()\n        with:\n          name: bandit-security-report\n          path: bandit-report.json\n          retention-days: 7\n\n  type-check:\n    name: Type Checking\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install mypy\n        run: |\n          uv venv\n          uv pip install -r scripts/requirements-dev.txt mypy\n\n      - name: Run mypy\n        run: uv run mypy scripts/ --ignore-missing-imports --no-implicit-optional\n        continue-on-error: true\n\n  build-epub:\n    name: Build EPUB Artifact\n    runs-on: ubuntu-latest\n    needs: [pytest, lint, security]\n    if: success()\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v4\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v4\n\n      - name: Set up Python\n        run: uv python install 3.11\n\n      - name: Create venv and install dependencies\n        run: |\n          uv venv\n          uv pip install -r scripts/requirements-dev.txt\n\n      - name: Build EPUB\n        run: uv run scripts/build_epub.py\n\n      - name: Verify EPUB Created\n        run: |\n          if [ -f claude-howto-guide.epub ]; then\n            echo \"✅ EPUB built successfully\"\n            ls -lh claude-howto-guide.epub\n          else\n            echo \"❌ EPUB file not found!\"\n            exit 1\n          fi\n\n      - name: Upload EPUB Artifact\n        uses: actions/upload-artifact@v4\n        with:\n          name: claude-howto-guide-epub\n          path: claude-howto-guide.epub\n          retention-days: 7\n          compression-level: 0\n\n  summary:\n    name: Test Summary\n    needs: [pytest, lint, security, type-check, build-epub]\n    runs-on: ubuntu-latest\n    if: always()\n\n    steps:\n      - name: Download all artifacts\n        uses: actions/download-artifact@v4\n\n      - name: Generate Summary\n        run: |\n          echo \"# Test Summary\" >> $GITHUB_STEP_SUMMARY\n          echo \"\" >> $GITHUB_STEP_SUMMARY\n          echo \"## Results\" >> $GITHUB_STEP_SUMMARY\n          echo \"- **Unit Tests**: ${{ needs.pytest.result }}\" >> $GITHUB_STEP_SUMMARY\n          echo \"- **Code Quality**: ${{ needs.lint.result }}\" >> $GITHUB_STEP_SUMMARY\n          echo \"- **Security Scan**: ${{ needs.security.result }}\" >> $GITHUB_STEP_SUMMARY\n          echo \"- **Type Checking**: ${{ needs.type-check.result }}\" >> $GITHUB_STEP_SUMMARY\n          echo \"- **EPUB Build**: ${{ needs.build-epub.result }}\" >> $GITHUB_STEP_SUMMARY\n          echo \"\" >> $GITHUB_STEP_SUMMARY\n          echo \"## Artifacts\" >> $GITHUB_STEP_SUMMARY\n          echo \"- pytest-results-* (coverage and test results)\" >> $GITHUB_STEP_SUMMARY\n          echo \"- bandit-security-report (security scan JSON)\" >> $GITHUB_STEP_SUMMARY\n          echo \"- claude-howto-guide-epub (built EPUB file)\" >> $GITHUB_STEP_SUMMARY\n\n      - name: Check if all tests passed\n        if: |\n          needs.pytest.result != 'success' ||\n          needs.build-epub.result != 'success'\n        run: |\n          echo \"❌ Critical tests failed\"\n          exit 1\n\n      - name: All tests passed\n        if: success()\n        run: echo \"✅ All tests passed successfully!\"\n"
  },
  {
    "path": ".gitignore",
    "content": "# macOS\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n# IDEs\n.vscode/\n.idea/\n*.swp\n*.swo\n*~\n\n# Logs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Environment variables\n.env\n.env.local\n.env.*.local\n\n# Temporary files\n*.tmp\n*.temp\n# Keep .claude/ clean for hand-on section — except project skills\n.claude/*\n!.claude/skills/\n.claude/skills/*\n!.claude/skills/self-assessment/\n!.claude/skills/lesson-quiz/\nblog-posts/\n\n# EPUB files in root directory\n/*.epub\n\n# Python virtual environment\n.venv/\n\n# Python cache\n__pycache__/\n*.py[cod]\n*$py.class\n*.so\n.pytest_cache/\n.mypy_cache/\n*.egg-info/\ndist/\nbuild/\n\n# Coverage reports\n.coverage\nhtmlcov/\n\n# uv lockfile\nuv.lock\nblog-post/\nopenspec/\n.opencode/\n\n# Promo video project\npromo-video/\n.agents/\n.codex/\n\n# Video files (too large for git)\n*.mp4\n\nupdate-plan*.md\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "# Pre-commit hooks for claude-howto project\n# Run `pre-commit install` to set up hooks\n# Run `pre-commit run --all-files` to check all files\n\ndefault_language_version:\n  python: python3.11\n\nrepos:\n  # Ruff - Fast Python linter and formatter\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.8.2\n    hooks:\n      # Ruff linter\n      - id: ruff\n        name: ruff-lint\n        args: [--fix, --exit-non-zero-on-fix]\n        types_or: [python, pyi]\n        files: ^scripts/\n      # Ruff formatter (replaces black)\n      - id: ruff-format\n        name: ruff-format\n        types_or: [python, pyi]\n        files: ^scripts/\n\n  # Bandit - Security linter\n  - repo: https://github.com/PyCQA/bandit\n    rev: 1.7.10\n    hooks:\n      - id: bandit\n        name: bandit-security\n        args: [-c, pyproject.toml]\n        additional_dependencies: [\"bandit[toml]\"]\n        types: [python]\n        files: ^scripts/\n        exclude: ^scripts/tests/\n\n  # Standard pre-commit hooks\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v5.0.0\n    hooks:\n      - id: check-yaml\n        name: check-yaml\n        args: [--allow-multiple-documents]\n      - id: check-toml\n        name: check-toml\n      - id: end-of-file-fixer\n        name: fix-end-of-file\n      - id: trailing-whitespace\n        name: fix-trailing-whitespace\n      - id: check-added-large-files\n        name: check-large-files\n        args: [--maxkb=1000]\n      - id: check-merge-conflict\n        name: check-merge-conflict\n"
  },
  {
    "path": "01-slash-commands/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Slash Commands\n\n## Overview\n\nSlash commands are shortcuts that control Claude's behavior during an interactive session. They come in several types:\n\n- **Built-in commands**: Provided by Claude Code (`/help`, `/clear`, `/model`)\n- **Skills**: User-defined commands created as `SKILL.md` files (`/optimize`, `/pr`)\n- **Plugin commands**: Commands from installed plugins (`/frontend-design:frontend-design`)\n- **MCP prompts**: Commands from MCP servers (`/mcp__github__list_prs`)\n\n> **Note**: Custom slash commands have been merged into skills. Files in `.claude/commands/` still work, but skills (`.claude/skills/`) are now the recommended approach. Both create `/command-name` shortcuts. See the [Skills Guide](../03-skills/) for the full reference.\n\n## Built-in Commands Reference\n\nBuilt-in commands are shortcuts for common actions. There are **55+ built-in commands** and **5 bundled skills** available. Type `/` in Claude Code to see the full list, or type `/` followed by any letters to filter.\n\n| Command | Purpose |\n|---------|---------|\n| `/add-dir <path>` | Add working directory |\n| `/agents` | Manage agent configurations |\n| `/branch [name]` | Branch conversation into a new session (alias: `/fork`). Note: `/fork` renamed to `/branch` in v2.1.77 |\n| `/btw <question>` | Side question without adding to history |\n| `/chrome` | Configure Chrome browser integration |\n| `/clear` | Clear conversation (aliases: `/reset`, `/new`) |\n| `/color [color\\|default]` | Set prompt bar color |\n| `/compact [instructions]` | Compact conversation with optional focus instructions |\n| `/config` | Open Settings (alias: `/settings`) |\n| `/context` | Visualize context usage as colored grid |\n| `/copy [N]` | Copy assistant response to clipboard; `w` writes to file |\n| `/cost` | Show token usage statistics |\n| `/desktop` | Continue in Desktop app (alias: `/app`) |\n| `/diff` | Interactive diff viewer for uncommitted changes |\n| `/doctor` | Diagnose installation health |\n| `/effort [low\\|medium\\|high\\|max\\|auto]` | Set effort level. `max` requires Opus 4.6 |\n| `/exit` | Exit the REPL (alias: `/quit`) |\n| `/export [filename]` | Export the current conversation to a file or clipboard |\n| `/extra-usage` | Configure extra usage for rate limits |\n| `/fast [on\\|off]` | Toggle fast mode |\n| `/feedback` | Submit feedback (alias: `/bug`) |\n| `/help` | Show help |\n| `/hooks` | View hook configurations |\n| `/ide` | Manage IDE integrations |\n| `/init` | Initialize `CLAUDE.md`. Set `CLAUDE_CODE_NEW_INIT=true` for interactive flow |\n| `/insights` | Generate session analysis report |\n| `/install-github-app` | Set up GitHub Actions app |\n| `/install-slack-app` | Install Slack app |\n| `/keybindings` | Open keybindings configuration |\n| `/login` | Switch Anthropic accounts |\n| `/logout` | Sign out from your Anthropic account |\n| `/mcp` | Manage MCP servers and OAuth |\n| `/memory` | Edit `CLAUDE.md`, toggle auto-memory |\n| `/mobile` | QR code for mobile app (aliases: `/ios`, `/android`) |\n| `/model [model]` | Select model with left/right arrows for effort |\n| `/passes` | Share free week of Claude Code |\n| `/permissions` | View/update permissions (alias: `/allowed-tools`) |\n| `/plan [description]` | Enter plan mode |\n| `/plugin` | Manage plugins |\n| `/pr-comments [PR]` | Fetch GitHub PR comments |\n| `/privacy-settings` | Privacy settings (Pro/Max only) |\n| `/release-notes` | View changelog |\n| `/reload-plugins` | Reload active plugins |\n| `/remote-control` | Remote control from claude.ai (alias: `/rc`) |\n| `/remote-env` | Configure default remote environment |\n| `/rename [name]` | Rename session |\n| `/resume [session]` | Resume conversation (alias: `/continue`) |\n| `/review` | **Deprecated** — install the `code-review` plugin instead |\n| `/rewind` | Rewind conversation and/or code (alias: `/checkpoint`) |\n| `/sandbox` | Toggle sandbox mode |\n| `/schedule [description]` | Create/manage scheduled tasks |\n| `/security-review` | Analyze branch for security vulnerabilities |\n| `/skills` | List available skills |\n| `/stats` | Visualize daily usage, sessions, streaks |\n| `/status` | Show version, model, account |\n| `/statusline` | Configure status line |\n| `/tasks` | List/manage background tasks |\n| `/terminal-setup` | Configure terminal keybindings |\n| `/theme` | Change color theme |\n| `/vim` | Toggle Vim/Normal modes |\n| `/voice` | Toggle push-to-talk voice dictation |\n\n### Bundled Skills\n\nThese skills ship with Claude Code and are invoked like slash commands:\n\n| Skill | Purpose |\n|-------|---------|\n| `/batch <instruction>` | Orchestrate large-scale parallel changes using worktrees |\n| `/claude-api` | Load Claude API reference for project language |\n| `/debug [description]` | Enable debug logging |\n| `/loop [interval] <prompt>` | Run prompt repeatedly on interval |\n| `/simplify [focus]` | Review changed files for code quality |\n\n### Deprecated Commands\n\n| Command | Status |\n|---------|--------|\n| `/review` | Deprecated — replaced by `code-review` plugin |\n| `/output-style` | Deprecated since v2.1.73 |\n| `/fork` | Renamed to `/branch` (alias still works, v2.1.77) |\n\n### Recent Changes\n\n- `/fork` renamed to `/branch` with `/fork` kept as alias (v2.1.77)\n- `/output-style` deprecated (v2.1.73)\n- `/review` deprecated in favor of the `code-review` plugin\n- `/effort` command added with `max` level requiring Opus 4.6\n- `/voice` command added for push-to-talk voice dictation\n- `/schedule` command added for creating/managing scheduled tasks\n- `/color` command added for prompt bar customization\n- `/model` picker now shows human-readable labels (e.g., \"Sonnet 4.6\") instead of raw model IDs\n- `/resume` supports `/continue` alias\n- MCP prompts are available as `/mcp__<server>__<prompt>` commands (see [MCP Prompts as Commands](#mcp-prompts-as-commands))\n\n## Custom Commands (Now Skills)\n\nCustom slash commands have been **merged into skills**. Both approaches create commands you can invoke with `/command-name`:\n\n| Approach | Location | Status |\n|----------|----------|--------|\n| **Skills (Recommended)** | `.claude/skills/<name>/SKILL.md` | Current standard |\n| **Legacy Commands** | `.claude/commands/<name>.md` | Still works |\n\nIf a skill and a command share the same name, the **skill takes precedence**. For example, when both `.claude/commands/review.md` and `.claude/skills/review/SKILL.md` exist, the skill version is used.\n\n### Migration Path\n\nYour existing `.claude/commands/` files continue to work without changes. To migrate to skills:\n\n**Before (Command):**\n```\n.claude/commands/optimize.md\n```\n\n**After (Skill):**\n```\n.claude/skills/optimize/SKILL.md\n```\n\n### Why Skills?\n\nSkills offer additional features over legacy commands:\n\n- **Directory structure**: Bundle scripts, templates, and reference files\n- **Auto-invocation**: Claude can trigger skills automatically when relevant\n- **Invocation control**: Choose whether users, Claude, or both can invoke\n- **Subagent execution**: Run skills in isolated contexts with `context: fork`\n- **Progressive disclosure**: Load additional files only when needed\n\n### Creating a Custom Command as a Skill\n\nCreate a directory with a `SKILL.md` file:\n\n```bash\nmkdir -p .claude/skills/my-command\n```\n\n**File:** `.claude/skills/my-command/SKILL.md`\n\n```yaml\n---\nname: my-command\ndescription: What this command does and when to use it\n---\n\n# My Command\n\nInstructions for Claude to follow when this command is invoked.\n\n1. First step\n2. Second step\n3. Third step\n```\n\n### Frontmatter Reference\n\n| Field | Purpose | Default |\n|-------|---------|---------|\n| `name` | Command name (becomes `/name`) | Directory name |\n| `description` | Brief description (helps Claude know when to use it) | First paragraph |\n| `argument-hint` | Expected arguments for auto-completion | None |\n| `allowed-tools` | Tools the command can use without permission | Inherits |\n| `model` | Specific model to use | Inherits |\n| `disable-model-invocation` | If `true`, only user can invoke (not Claude) | `false` |\n| `user-invocable` | If `false`, hide from `/` menu | `true` |\n| `context` | Set to `fork` to run in isolated subagent | None |\n| `agent` | Agent type when using `context: fork` | `general-purpose` |\n| `hooks` | Skill-scoped hooks (PreToolUse, PostToolUse, Stop) | None |\n\n### Arguments\n\nCommands can receive arguments:\n\n**All arguments with `$ARGUMENTS`:**\n\n```yaml\n---\nname: fix-issue\ndescription: Fix a GitHub issue by number\n---\n\nFix issue #$ARGUMENTS following our coding standards\n```\n\nUsage: `/fix-issue 123` → `$ARGUMENTS` becomes \"123\"\n\n**Individual arguments with `$0`, `$1`, etc.:**\n\n```yaml\n---\nname: review-pr\ndescription: Review a PR with priority\n---\n\nReview PR #$0 with priority $1\n```\n\nUsage: `/review-pr 456 high` → `$0`=\"456\", `$1`=\"high\"\n\n### Dynamic Context with Shell Commands\n\nExecute bash commands before the prompt using `!`command``:\n\n```yaml\n---\nname: commit\ndescription: Create a git commit with context\nallowed-tools: Bash(git *)\n---\n\n## Context\n\n- Current git status: !`git status`\n- Current git diff: !`git diff HEAD`\n- Current branch: !`git branch --show-current`\n- Recent commits: !`git log --oneline -5`\n\n## Your task\n\nBased on the above changes, create a single git commit.\n```\n\n### File References\n\nInclude file contents using `@`:\n\n```markdown\nReview the implementation in @src/utils/helpers.js\nCompare @src/old-version.js with @src/new-version.js\n```\n\n## Plugin Commands\n\nPlugins can provide custom commands:\n\n```\n/plugin-name:command-name\n```\n\nOr simply `/command-name` when there are no naming conflicts.\n\n**Examples:**\n```bash\n/frontend-design:frontend-design\n/commit-commands:commit\n```\n\n## MCP Prompts as Commands\n\nMCP servers can expose prompts as slash commands:\n\n```\n/mcp__<server-name>__<prompt-name> [arguments]\n```\n\n**Examples:**\n```bash\n/mcp__github__list_prs\n/mcp__github__pr_review 456\n/mcp__jira__create_issue \"Bug title\" high\n```\n\n### MCP Permission Syntax\n\nControl MCP server access in permissions:\n\n- `mcp__github` - Access entire GitHub MCP server\n- `mcp__github__*` - Wildcard access to all tools\n- `mcp__github__get_issue` - Specific tool access\n\n## Command Architecture\n\n```mermaid\ngraph TD\n    A[\"User Input: /command-name\"] --> B{\"Command Type?\"}\n    B -->|Built-in| C[\"Execute Built-in\"]\n    B -->|Skill| D[\"Load SKILL.md\"]\n    B -->|Plugin| E[\"Load Plugin Command\"]\n    B -->|MCP| F[\"Execute MCP Prompt\"]\n\n    D --> G[\"Parse Frontmatter\"]\n    G --> H[\"Substitute Variables\"]\n    H --> I[\"Execute Shell Commands\"]\n    I --> J[\"Send to Claude\"]\n    J --> K[\"Return Results\"]\n```\n\n## Command Lifecycle\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant FS as File System\n    participant CLI as Shell/Bash\n\n    User->>Claude: Types /optimize\n    Claude->>FS: Searches .claude/skills/ and .claude/commands/\n    FS-->>Claude: Returns optimize/SKILL.md\n    Claude->>Claude: Parses frontmatter\n    Claude->>CLI: Executes !`command` substitutions\n    CLI-->>Claude: Command outputs\n    Claude->>Claude: Substitutes $ARGUMENTS\n    Claude->>User: Processes prompt\n    Claude->>User: Returns results\n```\n\n## Available Commands in This Folder\n\nThese example commands can be installed as skills or legacy commands.\n\n### 1. `/optimize` - Code Optimization\n\nAnalyzes code for performance issues, memory leaks, and optimization opportunities.\n\n**Usage:**\n```\n/optimize\n[Paste your code]\n```\n\n### 2. `/pr` - Pull Request Preparation\n\nGuides through PR preparation checklist including linting, testing, and commit formatting.\n\n**Usage:**\n```\n/pr\n```\n\n**Screenshot:**\n![/pr](pr-slash-command.png)\n\n### 3. `/generate-api-docs` - API Documentation Generator\n\nGenerates comprehensive API documentation from source code.\n\n**Usage:**\n```\n/generate-api-docs\n```\n\n### 4. `/commit` - Git Commit with Context\n\nCreates a git commit with dynamic context from your repository.\n\n**Usage:**\n```\n/commit [optional message]\n```\n\n### 5. `/push-all` - Stage, Commit, and Push\n\nStages all changes, creates a commit, and pushes to remote with safety checks.\n\n**Usage:**\n```\n/push-all\n```\n\n**Safety Checks:**\n- Secrets: `.env*`, `*.key`, `*.pem`, `credentials.json`\n- API Keys: Detects real keys vs. placeholders\n- Large files: `>10MB` without Git LFS\n- Build artifacts: `node_modules/`, `dist/`, `__pycache__/`\n\n### 6. `/doc-refactor` - Documentation Restructuring\n\nRestructures project documentation for clarity and accessibility.\n\n**Usage:**\n```\n/doc-refactor\n```\n\n### 7. `/setup-ci-cd` - CI/CD Pipeline Setup\n\nImplements pre-commit hooks and GitHub Actions for quality assurance.\n\n**Usage:**\n```\n/setup-ci-cd\n```\n\n### 8. `/unit-test-expand` - Test Coverage Expansion\n\nIncreases test coverage by targeting untested branches and edge cases.\n\n**Usage:**\n```\n/unit-test-expand\n```\n\n## Installation\n\n### As Skills (Recommended)\n\nCopy to your skills directory:\n\n```bash\n# Create skills directory\nmkdir -p .claude/skills\n\n# For each command file, create a skill directory\nfor cmd in optimize pr commit; do\n  mkdir -p .claude/skills/$cmd\n  cp 01-slash-commands/$cmd.md .claude/skills/$cmd/SKILL.md\ndone\n```\n\n### As Legacy Commands\n\nCopy to your commands directory:\n\n```bash\n# Project-wide (team)\nmkdir -p .claude/commands\ncp 01-slash-commands/*.md .claude/commands/\n\n# Personal use\nmkdir -p ~/.claude/commands\ncp 01-slash-commands/*.md ~/.claude/commands/\n```\n\n## Creating Your Own Commands\n\n### Skill Template (Recommended)\n\nCreate `.claude/skills/my-command/SKILL.md`:\n\n```yaml\n---\nname: my-command\ndescription: What this command does. Use when [trigger conditions].\nargument-hint: [optional-args]\nallowed-tools: Bash(npm *), Read, Grep\n---\n\n# Command Title\n\n## Context\n\n- Current branch: !`git branch --show-current`\n- Related files: @package.json\n\n## Instructions\n\n1. First step\n2. Second step with argument: $ARGUMENTS\n3. Third step\n\n## Output Format\n\n- How to format the response\n- What to include\n```\n\n### User-Only Command (No Auto-Invocation)\n\nFor commands with side effects that Claude shouldn't trigger automatically:\n\n```yaml\n---\nname: deploy\ndescription: Deploy to production\ndisable-model-invocation: true\nallowed-tools: Bash(npm *), Bash(git *)\n---\n\nDeploy the application to production:\n\n1. Run tests\n2. Build application\n3. Push to deployment target\n4. Verify deployment\n```\n\n## Best Practices\n\n| Do | Don't |\n|------|---------|\n| Use clear, action-oriented names | Create commands for one-time tasks |\n| Include `description` with trigger conditions | Build complex logic in commands |\n| Keep commands focused on single task | Hardcode sensitive information |\n| Use `disable-model-invocation` for side effects | Skip the description field |\n| Use `!` prefix for dynamic context | Assume Claude knows current state |\n| Organize related files in skill directories | Put everything in one file |\n\n## Troubleshooting\n\n### Command Not Found\n\n**Solutions:**\n- Check file is in `.claude/skills/<name>/SKILL.md` or `.claude/commands/<name>.md`\n- Verify the `name` field in frontmatter matches expected command name\n- Restart Claude Code session\n- Run `/help` to see available commands\n\n### Command Not Executing as Expected\n\n**Solutions:**\n- Add more specific instructions\n- Include examples in the skill file\n- Check `allowed-tools` if using bash commands\n- Test with simple inputs first\n\n### Skill vs Command Conflict\n\nIf both exist with the same name, the **skill takes precedence**. Remove one or rename it.\n\n## Related Guides\n\n- **[Skills](../03-skills/)** - Full reference for skills (auto-invoked capabilities)\n- **[Memory](../02-memory/)** - Persistent context with CLAUDE.md\n- **[Subagents](../04-subagents/)** - Delegated AI agents\n- **[Plugins](../07-plugins/)** - Bundled command collections\n- **[Hooks](../06-hooks/)** - Event-driven automation\n\n## Additional Resources\n\n- [Official Interactive Mode Documentation](https://code.claude.com/docs/en/interactive-mode) - Built-in commands reference\n- [Official Skills Documentation](https://code.claude.com/docs/en/skills) - Complete skills reference\n- [CLI Reference](https://code.claude.com/docs/en/cli-reference) - Command-line options\n\n---\n\n*Part of the [Claude How To](../) guide series*\n"
  },
  {
    "path": "01-slash-commands/commit.md",
    "content": "---\nallowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git diff:*)\nargument-hint: [message]\ndescription: Create a git commit with context\n---\n\n## Context\n\n- Current git status: !`git status`\n- Current git diff: !`git diff HEAD`\n- Current branch: !`git branch --show-current`\n- Recent commits: !`git log --oneline -10`\n\n## Your task\n\nBased on the above changes, create a single git commit.\n\nIf a message was provided via arguments, use it: $ARGUMENTS\n\nOtherwise, analyze the changes and create an appropriate commit message following conventional commits format:\n- `feat:` for new features\n- `fix:` for bug fixes\n- `docs:` for documentation changes\n- `refactor:` for code refactoring\n- `test:` for adding tests\n- `chore:` for maintenance tasks\n"
  },
  {
    "path": "01-slash-commands/doc-refactor.md",
    "content": "---\nname: Documentation Refactor\ndescription: Restructure project documentation for clarity and accessibility\ntags: documentation, refactoring, organization\n---\n\n# Documentation Refactor\n\nRefactor project documentation structure adapted to project type:\n\n1. **Analyze project**: Identify type (library/API/web app/CLI/microservices), architecture, and user personas\n2. **Centralize docs**: Move technical documentation to `docs/` with proper cross-references\n3. **Root README.md**: Streamline as entry point with overview, quickstart, modules/components summary, license, contacts\n4. **Component docs**: Add module/package/service-level README files with setup and testing instructions\n5. **Organize `docs/`** by relevant categories:\n   - Architecture, API Reference, Database, Design, Troubleshooting, Deployment, Contributing (adapt to project needs)\n6. **Create guides** (select applicable):\n   - User Guide: End-user documentation for applications\n   - API Documentation: Endpoints, authentication, examples for APIs\n   - Development Guide: Setup, testing, contribution workflow\n   - Deployment Guide: Production deployment for services/apps\n7. **Use Mermaid** for all diagrams (architecture, flows, schemas)\n\nKeep docs concise, scannable, and contextual to project type.\n"
  },
  {
    "path": "01-slash-commands/generate-api-docs.md",
    "content": "---\ndescription: Create comprehensive API documentation from source code\n---\n\n# API Documentation Generator\n\nGenerate API documentation by:\n\n1. Scanning all files in `/src/api/`\n2. Extracting function signatures and JSDoc comments\n3. Organizing by endpoint/module\n4. Creating markdown with examples\n5. Including request/response schemas\n6. Adding error documentation\n\nOutput format:\n- Markdown file in `/docs/api.md`\n- Include curl examples for all endpoints\n- Add TypeScript types\n"
  },
  {
    "path": "01-slash-commands/optimize.md",
    "content": "---\ndescription: Analyze code for performance issues and suggest optimizations\n---\n\n# Code Optimization\n\nReview the provided code for the following issues in order of priority:\n\n1. **Performance bottlenecks** - identify O(n²) operations, inefficient loops\n2. **Memory leaks** - find unreleased resources, circular references\n3. **Algorithm improvements** - suggest better algorithms or data structures\n4. **Caching opportunities** - identify repeated computations\n5. **Concurrency issues** - find race conditions or threading problems\n\nFormat your response with:\n- Issue severity (Critical/High/Medium/Low)\n- Location in code\n- Explanation\n- Recommended fix with code example\n"
  },
  {
    "path": "01-slash-commands/pr.md",
    "content": "---\ndescription: Clean up code, stage changes, and prepare a pull request\nallowed-tools: Bash(git add:*), Bash(git status:*), Bash(git diff:*), Bash(npm test:*), Bash(npm run lint:*)\n---\n\n# Pull Request Preparation Checklist\n\nBefore creating a PR, execute these steps:\n\n1. Run linting: `prettier --write .`\n2. Run tests: `npm test`\n3. Review git diff: `git diff HEAD`\n4. Stage changes: `git add .`\n5. Create commit message following conventional commits:\n   - `fix:` for bug fixes\n   - `feat:` for new features\n   - `docs:` for documentation\n   - `refactor:` for code restructuring\n   - `test:` for test additions\n   - `chore:` for maintenance\n\n6. Generate PR summary including:\n   - What changed\n   - Why it changed\n   - Testing performed\n   - Potential impacts\n"
  },
  {
    "path": "01-slash-commands/push-all.md",
    "content": "---\ndescription: Stage all changes, create commit, and push to remote (use with caution)\nallowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git push:*), Bash(git diff:*), Bash(git log:*), Bash(git pull:*)\n---\n\n# Commit and Push Everything\n\n⚠️ **CAUTION**: Stage ALL changes, commit, and push to remote. Use only when confident all changes belong together.\n\n## Workflow\n\n### 1. Analyze Changes\nRun in parallel:\n- `git status` - Show modified/added/deleted/untracked files\n- `git diff --stat` - Show change statistics\n- `git log -1 --oneline` - Show recent commit for message style\n\n### 2. Safety Checks\n\n**❌ STOP and WARN if detected:**\n- Secrets: `.env*`, `*.key`, `*.pem`, `credentials.json`, `secrets.yaml`, `id_rsa`, `*.p12`, `*.pfx`, `*.cer`\n- API Keys: Any `*_API_KEY`, `*_SECRET`, `*_TOKEN` variables with real values (not placeholders like `your-api-key`, `xxx`, `placeholder`)\n- Large files: `>10MB` without Git LFS\n- Build artifacts: `node_modules/`, `dist/`, `build/`, `__pycache__/`, `*.pyc`, `.venv/`\n- Temp files: `.DS_Store`, `thumbs.db`, `*.swp`, `*.tmp`\n\n**API Key Validation:**\nCheck modified files for patterns like:\n```bash\nOPENAI_API_KEY=sk-proj-xxxxx  # ❌ Real key detected!\nAWS_SECRET_KEY=AKIA...         # ❌ Real key detected!\nSTRIPE_API_KEY=sk_live_...    # ❌ Real key detected!\n\n# ✅ Acceptable placeholders:\nAPI_KEY=your-api-key-here\nSECRET_KEY=placeholder\nTOKEN=xxx\nAPI_KEY=<your-key>\nSECRET=${YOUR_SECRET}\n```\n\n**✅ Verify:**\n- `.gitignore` properly configured\n- No merge conflicts\n- Correct branch (warn if main/master)\n- API keys are placeholders only\n\n### 3. Request Confirmation\n\nPresent summary:\n```\n📊 Changes Summary:\n- X files modified, Y added, Z deleted\n- Total: +AAA insertions, -BBB deletions\n\n🔒 Safety: ✅ No secrets | ✅ No large files | ⚠️ [warnings]\n🌿 Branch: [name] → origin/[name]\n\nI will: git add . → commit → push\n\nType 'yes' to proceed or 'no' to cancel.\n```\n\n**WAIT for explicit \"yes\" before proceeding.**\n\n### 4. Execute (After Confirmation)\n\nRun sequentially:\n```bash\ngit add .\ngit status  # Verify staging\n```\n\n### 5. Generate Commit Message\n\nAnalyze changes and create conventional commit:\n\n**Format:**\n```\n[type]: Brief summary (max 72 characters)\n\n- Key change 1\n- Key change 2\n- Key change 3\n```\n\n**Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `perf`, `build`, `ci`\n\n**Example:**\n```\ndocs: Update concept README files with comprehensive documentation\n\n- Add architecture diagrams and tables\n- Include practical examples\n- Expand best practices sections\n```\n\n### 6. Commit and Push\n\n```bash\ngit commit -m \"$(cat <<'EOF'\n[Generated commit message]\nEOF\n)\"\ngit push  # If fails: git pull --rebase && git push\ngit log -1 --oneline --decorate  # Verify\n```\n\n### 7. Confirm Success\n\n```\n✅ Successfully pushed to remote!\n\nCommit: [hash] [message]\nBranch: [branch] → origin/[branch]\nFiles changed: X (+insertions, -deletions)\n```\n\n## Error Handling\n\n- **git add fails**: Check permissions, locked files, verify repo initialized\n- **git commit fails**: Fix pre-commit hooks, check git config (user.name/email)\n- **git push fails**:\n  - Non-fast-forward: `git pull --rebase && git push`\n  - No remote branch: `git push -u origin [branch]`\n  - Protected branch: Use PR workflow instead\n\n## When to Use\n\n✅ **Good:**\n- Multi-file documentation updates\n- Feature with tests and docs\n- Bug fixes across files\n- Project-wide formatting/refactoring\n- Configuration changes\n\n❌ **Avoid:**\n- Uncertain what's being committed\n- Contains secrets/sensitive data\n- Protected branches without review\n- Merge conflicts present\n- Want granular commit history\n- Pre-commit hooks failing\n\n## Alternatives\n\nIf user wants control, suggest:\n1. **Selective staging**: Review/stage specific files\n2. **Interactive staging**: `git add -p` for patch selection\n3. **PR workflow**: Create branch → push → PR (use `/pr` command)\n\n**⚠️ Remember**: Always review changes before pushing. When in doubt, use individual git commands for more control.\n"
  },
  {
    "path": "01-slash-commands/setup-ci-cd.md",
    "content": "---\nname: Setup CI/CD Pipeline\ndescription: Implement pre-commit hooks and GitHub Actions for quality assurance\ntags: ci-cd, devops, automation\n---\n\n# Setup CI/CD Pipeline\n\nImplement comprehensive DevOps quality gates adapted to project type:\n\n1. **Analyze project**: Detect language(s), framework, build system, and existing tooling\n2. **Configure pre-commit hooks** with language-specific tools:\n   - Formatting: Prettier/Black/gofmt/rustfmt/etc.\n   - Linting: ESLint/Ruff/golangci-lint/Clippy/etc.\n   - Security: Bandit/gosec/cargo-audit/npm audit/etc.\n   - Type checking: TypeScript/mypy/flow (if applicable)\n   - Tests: Run relevant test suites\n3. **Create GitHub Actions workflows** (.github/workflows/):\n   - Mirror pre-commit checks on push/PR\n   - Multi-version/platform matrix (if applicable)\n   - Build and test verification\n   - Deployment steps (if needed)\n4. **Verify pipeline**: Test locally, create test PR, confirm all checks pass\n\nUse free/open-source tools. Respect existing configs. Keep execution fast.\n"
  },
  {
    "path": "01-slash-commands/unit-test-expand.md",
    "content": "---\nname: Expand Unit Tests\ndescription: Increase test coverage by targeting untested branches and edge cases\ntags: testing, coverage, unit-tests\n---\n\n# Expand Unit Tests\n\nExpand existing unit tests adapted to project's testing framework:\n\n1. **Analyze coverage**: Run coverage report to identify untested branches, edge cases, and low-coverage areas\n2. **Identify gaps**: Review code for logical branches, error paths, boundary conditions, null/empty inputs\n3. **Write tests** using project's framework:\n   - Jest/Vitest/Mocha (JavaScript/TypeScript)\n   - pytest/unittest (Python)\n   - Go testing/testify (Go)\n   - Rust test framework (Rust)\n4. **Target specific scenarios**:\n   - Error handling and exceptions\n   - Boundary values (min/max, empty, null)\n   - Edge cases and corner cases\n   - State transitions and side effects\n5. **Verify improvement**: Run coverage again, confirm measurable increase\n\nPresent new test code blocks only. Follow existing test patterns and naming conventions.\n"
  },
  {
    "path": "02-memory/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Memory Guide\n\nMemory 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.\n\n## Overview\n\nMemory in Claude Code provides persistent context that carries across multiple sessions and conversations. Unlike temporary context windows, memory files allow you to:\n\n- Share project standards across your team\n- Store personal development preferences\n- Maintain directory-specific rules and configurations\n- Import external documentation\n- Version control memory as part of your project\n\nThe 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.\n\n## Memory Commands Quick Reference\n\n| Command | Purpose | Usage | When to Use |\n|---------|---------|-------|-------------|\n| `/init` | Initialize project memory | `/init` | Starting new project, first-time CLAUDE.md setup |\n| `/memory` | Edit memory files in editor | `/memory` | Extensive updates, reorganization, reviewing content |\n| `#` prefix | Quick single-line memory add | `# Your rule here` | Adding quick rules during conversation |\n| `# new rule into memory` | Explicit memory addition | `# new rule into memory<br/>Your detailed rule` | Adding complex multi-line rules |\n| `# remember this` | Natural language memory | `# remember this<br/>Your instruction` | Conversational memory updates |\n| `@path/to/file` | Import external content | `@README.md` or `@docs/api.md` | Referencing existing documentation in CLAUDE.md |\n\n## Quick Start: Initializing Memory\n\n### The `/init` Command\n\nThe `/init` command is the fastest way to set up project memory in Claude Code. It initializes a CLAUDE.md file with foundational project documentation.\n\n**Usage:**\n\n```bash\n/init\n```\n\n**What it does:**\n\n- Creates a new CLAUDE.md file in your project (typically at `./CLAUDE.md` or `./.claude/CLAUDE.md`)\n- Establishes project conventions and guidelines\n- Sets up the foundation for context persistence across sessions\n- Provides a template structure for documenting your project standards\n\n**Enhanced interactive mode:** Set `CLAUDE_CODE_NEW_INIT=true` to enable a multi-phase interactive flow that walks you through project setup step by step:\n\n```bash\nCLAUDE_CODE_NEW_INIT=true claude\n/init\n```\n\n**When to use `/init`:**\n\n- Starting a new project with Claude Code\n- Establishing team coding standards and conventions\n- Creating documentation about your codebase structure\n- Setting up memory hierarchy for collaborative development\n\n**Example workflow:**\n\n```markdown\n# In your project directory\n/init\n\n# Claude creates CLAUDE.md with structure like:\n# Project Configuration\n## Project Overview\n- Name: Your Project\n- Tech Stack: [Your technologies]\n- Team Size: [Number of developers]\n\n## Development Standards\n- Code style preferences\n- Testing requirements\n- Git workflow conventions\n```\n\n### Quick Memory Updates with `#`\n\nYou can quickly add information to memory during any conversation by starting your message with `#`:\n\n**Syntax:**\n\n```markdown\n# Your memory rule or instruction here\n```\n\n**Examples:**\n\n```markdown\n# Always use TypeScript strict mode in this project\n\n# Prefer async/await over promise chains\n\n# Run npm test before every commit\n\n# Use kebab-case for file names\n```\n\n**How it works:**\n\n1. Start your message with `#` followed by your rule\n2. Claude recognizes this as a memory update request\n3. Claude asks which memory file to update (project or personal)\n4. The rule is added to the appropriate CLAUDE.md file\n5. Future sessions automatically load this context\n\n**Alternative patterns:**\n\n```markdown\n# new rule into memory\nAlways validate user input with Zod schemas\n\n# remember this\nUse semantic versioning for all releases\n\n# add to memory\nDatabase migrations must be reversible\n```\n\n### The `/memory` Command\n\nThe `/memory` command provides direct access to edit your CLAUDE.md memory files within Claude Code sessions. It opens your memory files in your system editor for comprehensive editing.\n\n**Usage:**\n\n```bash\n/memory\n```\n\n**What it does:**\n\n- Opens your memory files in your system's default editor\n- Allows you to make extensive additions, modifications, and reorganizations\n- Provides direct access to all memory files in the hierarchy\n- Enables you to manage persistent context across sessions\n\n**When to use `/memory`:**\n\n- Reviewing existing memory content\n- Making extensive updates to project standards\n- Reorganizing memory structure\n- Adding detailed documentation or guidelines\n- Maintaining and updating memory as your project evolves\n\n**Comparison: `/memory` vs `/init`**\n\n| Aspect | `/memory` | `/init` |\n|--------|-----------|---------|\n| **Purpose** | Edit existing memory files | Initialize new CLAUDE.md |\n| **When to use** | Update/modify project context | Begin new projects |\n| **Action** | Opens editor for changes | Generates starter template |\n| **Workflow** | Ongoing maintenance | One-time setup |\n\n**Example workflow:**\n\n```markdown\n# Open memory for editing\n/memory\n\n# Claude presents options:\n# 1. Managed Policy Memory\n# 2. Project Memory (./CLAUDE.md)\n# 3. User Memory (~/.claude/CLAUDE.md)\n# 4. Local Project Memory\n\n# Choose option 2 (Project Memory)\n# Your default editor opens with ./CLAUDE.md content\n\n# Make changes, save, and close editor\n# Claude automatically reloads the updated memory\n```\n\n**Using Memory Imports:**\n\nCLAUDE.md files support the `@path/to/file` syntax to include external content:\n\n```markdown\n# Project Documentation\nSee @README.md for project overview\nSee @package.json for available npm commands\nSee @docs/architecture.md for system design\n\n# Import from home directory using absolute path\n@~/.claude/my-project-instructions.md\n```\n\n**Import features:**\n\n- Both relative and absolute paths are supported (e.g., `@docs/api.md` or `@~/.claude/my-project-instructions.md`)\n- Recursive imports are supported with a maximum depth of 5\n- First-time imports from external locations trigger an approval dialog for security\n- Import directives are not evaluated inside markdown code spans or code blocks (so documenting them in examples is safe)\n- Helps avoid duplication by referencing existing documentation\n- Automatically includes referenced content in Claude's context\n\n## Memory Architecture\n\nMemory in Claude Code follows a hierarchical system where different scopes serve different purposes:\n\n```mermaid\ngraph TB\n    A[\"Claude Session\"]\n    B[\"User Input\"]\n    C[\"Memory System\"]\n    D[\"Memory Storage\"]\n\n    B -->|User provides info| C\n    C -->|Synthesizes every 24h| D\n    D -->|Loads automatically| A\n    A -->|Uses context| C\n```\n\n## Memory Hierarchy in Claude Code\n\nClaude Code uses a multi-tier hierarchical memory system. Memory files are automatically loaded when Claude Code launches, with higher-level files taking precedence.\n\n**Complete Memory Hierarchy (in order of precedence):**\n\n1. **Managed Policy** - Organization-wide instructions\n   - macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`\n   - Linux/WSL: `/etc/claude-code/CLAUDE.md`\n   - Windows: `C:\\Program Files\\ClaudeCode\\CLAUDE.md`\n\n2. **Managed Drop-ins** - Alphabetically merged policy files (v2.1.83+)\n   - `managed-settings.d/` directory alongside the managed policy CLAUDE.md\n   - Files are merged in alphabetical order for modular policy management\n\n3. **Project Memory** - Team-shared context (version controlled)\n   - `./.claude/CLAUDE.md` or `./CLAUDE.md` (in repository root)\n\n4. **Project Rules** - Modular, topic-specific project instructions\n   - `./.claude/rules/*.md`\n\n5. **User Memory** - Personal preferences (all projects)\n   - `~/.claude/CLAUDE.md`\n\n6. **User-Level Rules** - Personal rules (all projects)\n   - `~/.claude/rules/*.md`\n\n7. **Local Project Memory** - Personal project-specific preferences\n   - `./CLAUDE.local.md`\n\n> **Note**: `CLAUDE.local.md` is not mentioned in the [official documentation](https://code.claude.com/docs/en/memory) as of March 2026. It may still work as a legacy feature. For new projects, consider using `~/.claude/CLAUDE.md` (user-level) or `.claude/rules/` (project-level, path-scoped) instead.\n\n8. **Auto Memory** - Claude's automatic notes and learnings\n   - `~/.claude/projects/<project>/memory/`\n\n**Memory Discovery Behavior:**\n\nClaude searches for memory files in this order, with earlier locations taking precedence:\n\n```mermaid\ngraph TD\n    A[\"Managed Policy<br/>/Library/.../ClaudeCode/CLAUDE.md\"] -->|highest priority| A2[\"Managed Drop-ins<br/>managed-settings.d/\"]\n    A2 --> B[\"Project Memory<br/>./CLAUDE.md\"]\n    B --> C[\"Project Rules<br/>./.claude/rules/*.md\"]\n    C --> D[\"User Memory<br/>~/.claude/CLAUDE.md\"]\n    D --> E[\"User Rules<br/>~/.claude/rules/*.md\"]\n    E --> F[\"Local Project Memory<br/>./CLAUDE.local.md\"]\n    F --> G[\"Auto Memory<br/>~/.claude/projects/.../memory/\"]\n\n    B -->|imports| H[\"@docs/architecture.md\"]\n    H -->|imports| I[\"@docs/api-standards.md\"]\n\n    style A fill:#fce4ec,stroke:#333,color:#333\n    style A2 fill:#fce4ec,stroke:#333,color:#333\n    style B fill:#e1f5fe,stroke:#333,color:#333\n    style C fill:#e1f5fe,stroke:#333,color:#333\n    style D fill:#f3e5f5,stroke:#333,color:#333\n    style E fill:#f3e5f5,stroke:#333,color:#333\n    style F fill:#e8f5e9,stroke:#333,color:#333\n    style G fill:#fff3e0,stroke:#333,color:#333\n    style H fill:#e1f5fe,stroke:#333,color:#333\n    style I fill:#e1f5fe,stroke:#333,color:#333\n```\n\n## Excluding CLAUDE.md Files with `claudeMdExcludes`\n\nIn large monorepos, some CLAUDE.md files may be irrelevant to your current work. The `claudeMdExcludes` setting lets you skip specific CLAUDE.md files so they are not loaded into context:\n\n```jsonc\n// In ~/.claude/settings.json or .claude/settings.json\n{\n  \"claudeMdExcludes\": [\n    \"packages/legacy-app/CLAUDE.md\",\n    \"vendors/**/CLAUDE.md\"\n  ]\n}\n```\n\nPatterns are matched against paths relative to the project root. This is particularly useful for:\n\n- Monorepos with many sub-projects, where only some are relevant\n- Repositories that contain vendored or third-party CLAUDE.md files\n- Reducing noise in Claude's context window by excluding stale or unrelated instructions\n\n## Settings File Hierarchy\n\nClaude Code settings (including `autoMemoryDirectory`, `claudeMdExcludes`, and other configuration) are resolved from a five-level hierarchy, with higher levels taking precedence:\n\n| Level | Location | Scope |\n|-------|----------|-------|\n| 1 (Highest) | Managed policy (system-level) | Organization-wide enforcement |\n| 2 | `managed-settings.d/` (v2.1.83+) | Modular policy drop-ins, merged alphabetically |\n| 3 | `~/.claude/settings.json` | User preferences |\n| 4 | `.claude/settings.json` | Project-level (committed to git) |\n| 5 (Lowest) | `.claude/settings.local.json` | Local overrides (git-ignored) |\n\n**Platform-specific configuration (v2.1.51+):**\n\nSettings can also be configured via:\n- **macOS**: Property list (plist) files\n- **Windows**: Windows Registry\n\nThese platform-native mechanisms are read alongside JSON settings files and follow the same precedence rules.\n\n## Modular Rules System\n\nCreate organized, path-specific rules using the `.claude/rules/` directory structure. Rules can be defined at both the project level and user level:\n\n```\nyour-project/\n├── .claude/\n│   ├── CLAUDE.md\n│   └── rules/\n│       ├── code-style.md\n│       ├── testing.md\n│       ├── security.md\n│       └── api/                  # Subdirectories supported\n│           ├── conventions.md\n│           └── validation.md\n\n~/.claude/\n├── CLAUDE.md\n└── rules/                        # User-level rules (all projects)\n    ├── personal-style.md\n    └── preferred-patterns.md\n```\n\nRules are discovered recursively within the `rules/` directory, including any subdirectories. User-level rules at `~/.claude/rules/` are loaded before project-level rules, allowing personal defaults that projects can override.\n\n### Path-Specific Rules with YAML Frontmatter\n\nDefine rules that apply only to specific file paths:\n\n```markdown\n---\npaths: src/api/**/*.ts\n---\n\n# API Development Rules\n\n- All API endpoints must include input validation\n- Use Zod for schema validation\n- Document all parameters and response types\n- Include error handling for all operations\n```\n\n**Glob Pattern Examples:**\n\n- `**/*.ts` - All TypeScript files\n- `src/**/*` - All files under src/\n- `src/**/*.{ts,tsx}` - Multiple extensions\n- `{src,lib}/**/*.ts, tests/**/*.test.ts` - Multiple patterns\n\n### Subdirectories and Symlinks\n\nRules in `.claude/rules/` support two organizational features:\n\n- **Subdirectories**: Rules are discovered recursively, so you can organize them into topic-based folders (e.g., `rules/api/`, `rules/testing/`, `rules/security/`)\n- **Symlinks**: Symlinks are supported for sharing rules across multiple projects. For example, you can symlink a shared rule file from a central location into each project's `.claude/rules/` directory\n\n## Memory Locations Table\n\n| Location | Scope | Priority | Shared | Access | Best For |\n|----------|-------|----------|--------|--------|----------|\n| `/Library/Application Support/ClaudeCode/CLAUDE.md` (macOS) | Managed Policy | 1 (Highest) | Organization | System | Company-wide policies |\n| `/etc/claude-code/CLAUDE.md` (Linux/WSL) | Managed Policy | 1 (Highest) | Organization | System | Organization standards |\n| `C:\\Program Files\\ClaudeCode\\CLAUDE.md` (Windows) | Managed Policy | 1 (Highest) | Organization | System | Corporate guidelines |\n| `managed-settings.d/*.md` (alongside policy) | Managed Drop-ins | 1.5 | Organization | System | Modular policy files (v2.1.83+) |\n| `./CLAUDE.md` or `./.claude/CLAUDE.md` | Project Memory | 2 | Team | Git | Team standards, shared architecture |\n| `./.claude/rules/*.md` | Project Rules | 3 | Team | Git | Path-specific, modular rules |\n| `~/.claude/CLAUDE.md` | User Memory | 4 | Individual | Filesystem | Personal preferences (all projects) |\n| `~/.claude/rules/*.md` | User Rules | 5 | Individual | Filesystem | Personal rules (all projects) |\n| `./CLAUDE.local.md` | Project Local | 6 | Individual | Git (ignored) | Personal project-specific preferences |\n| `~/.claude/projects/<project>/memory/` | Auto Memory | 7 (Lowest) | Individual | Filesystem | Claude's automatic notes and learnings |\n\n## Memory Update Lifecycle\n\nHere's how memory updates flow through your Claude Code sessions:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Editor as File System\n    participant Memory as CLAUDE.md\n\n    User->>Claude: \"Remember: use async/await\"\n    Claude->>User: \"Which memory file?\"\n    User->>Claude: \"Project memory\"\n    Claude->>Editor: Open ~/.claude/settings.json\n    Claude->>Memory: Write to ./CLAUDE.md\n    Memory-->>Claude: File saved\n    Claude->>Claude: Load updated memory\n    Claude-->>User: \"Memory saved!\"\n```\n\n## Auto Memory\n\nAuto memory is a persistent directory where Claude automatically records learnings, patterns, and insights as it works with your project. Unlike CLAUDE.md files which you write and maintain manually, auto memory is written by Claude itself during sessions.\n\n### How Auto Memory Works\n\n- **Location**: `~/.claude/projects/<project>/memory/`\n- **Entrypoint**: `MEMORY.md` serves as the main file in the auto memory directory\n- **Topic files**: Optional additional files for specific subjects (e.g., `debugging.md`, `api-conventions.md`)\n- **Loading behavior**: The first 200 lines of `MEMORY.md` are loaded into the system prompt at session start. Topic files are loaded on demand, not at startup.\n- **Read/write**: Claude reads and writes memory files during sessions as it discovers patterns and project-specific knowledge\n\n### Auto Memory Architecture\n\n```mermaid\ngraph TD\n    A[\"Claude Session Starts\"] --> B[\"Load MEMORY.md<br/>(first 200 lines)\"]\n    B --> C[\"Session Active\"]\n    C --> D[\"Claude discovers<br/>patterns & insights\"]\n    D --> E{\"Write to<br/>auto memory\"}\n    E -->|General notes| F[\"MEMORY.md\"]\n    E -->|Topic-specific| G[\"debugging.md\"]\n    E -->|Topic-specific| H[\"api-conventions.md\"]\n    C --> I[\"On-demand load<br/>topic files\"]\n    I --> C\n\n    style A fill:#e1f5fe,stroke:#333,color:#333\n    style B fill:#e1f5fe,stroke:#333,color:#333\n    style C fill:#e8f5e9,stroke:#333,color:#333\n    style D fill:#f3e5f5,stroke:#333,color:#333\n    style E fill:#fff3e0,stroke:#333,color:#333\n    style F fill:#fce4ec,stroke:#333,color:#333\n    style G fill:#fce4ec,stroke:#333,color:#333\n    style H fill:#fce4ec,stroke:#333,color:#333\n    style I fill:#f3e5f5,stroke:#333,color:#333\n```\n\n### Auto Memory Directory Structure\n\n```\n~/.claude/projects/<project>/memory/\n├── MEMORY.md              # Entrypoint (first 200 lines loaded at startup)\n├── debugging.md           # Topic file (loaded on demand)\n├── api-conventions.md     # Topic file (loaded on demand)\n└── testing-patterns.md    # Topic file (loaded on demand)\n```\n\n### Version Requirement\n\nAuto memory requires **Claude Code v2.1.59 or later**. If you are on an older version, upgrade first:\n\n```bash\nnpm install -g @anthropic-ai/claude-code@latest\n```\n\n### Custom Auto Memory Directory\n\nBy default, auto memory is stored in `~/.claude/projects/<project>/memory/`. You can change this location using the `autoMemoryDirectory` setting (available since **v2.1.74**):\n\n```jsonc\n// In ~/.claude/settings.json or .claude/settings.local.json (user/local settings only)\n{\n  \"autoMemoryDirectory\": \"/path/to/custom/memory/directory\"\n}\n```\n\n> **Note**: `autoMemoryDirectory` can only be set in user-level (`~/.claude/settings.json`) or local settings (`.claude/settings.local.json`), not in project or managed policy settings.\n\nThis is useful when you want to:\n\n- Store auto memory in a shared or synced location\n- Separate auto memory from the default Claude configuration directory\n- Use a project-specific path outside the default hierarchy\n\n### Worktree and Repository Sharing\n\nAll worktrees and subdirectories within the same git repository share a single auto memory directory. This means switching between worktrees or working in different subdirectories of the same repo will read and write to the same memory files.\n\n### Subagent Memory\n\nSubagents (spawned via tools like Task or parallel execution) can have their own memory context. Use the `memory` frontmatter field in the subagent definition to specify which memory scopes to load:\n\n```yaml\nmemory: user      # Load user-level memory only\nmemory: project   # Load project-level memory only\nmemory: local     # Load local memory only\n```\n\nThis allows subagents to operate with focused context rather than inheriting the full memory hierarchy.\n\n### Controlling Auto Memory\n\nAuto memory can be controlled via the `CLAUDE_CODE_DISABLE_AUTO_MEMORY` environment variable:\n\n| Value | Behavior |\n|-------|----------|\n| `0` | Force auto memory **on** |\n| `1` | Force auto memory **off** |\n| *(unset)* | Default behavior (auto memory enabled) |\n\n```bash\n# Disable auto memory for a session\nCLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude\n\n# Force auto memory on explicitly\nCLAUDE_CODE_DISABLE_AUTO_MEMORY=0 claude\n```\n\n## Additional Directories with `--add-dir`\n\nThe `--add-dir` flag allows Claude Code to load CLAUDE.md files from additional directories beyond the current working directory. This is useful for monorepos or multi-project setups where context from other directories is relevant.\n\nTo enable this feature, set the environment variable:\n\n```bash\nCLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1\n```\n\nThen launch Claude Code with the flag:\n\n```bash\nclaude --add-dir /path/to/other/project\n```\n\nClaude will load CLAUDE.md from the specified additional directory alongside the memory files from your current working directory.\n\n## Practical Examples\n\n### Example 1: Project Memory Structure\n\n**File:** `./CLAUDE.md`\n\n```markdown\n# Project Configuration\n\n## Project Overview\n- **Name**: E-commerce Platform\n- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker\n- **Team Size**: 5 developers\n- **Deadline**: Q4 2025\n\n## Architecture\n@docs/architecture.md\n@docs/api-standards.md\n@docs/database-schema.md\n\n## Development Standards\n\n### Code Style\n- Use Prettier for formatting\n- Use ESLint with airbnb config\n- Maximum line length: 100 characters\n- Use 2-space indentation\n\n### Naming Conventions\n- **Files**: kebab-case (user-controller.js)\n- **Classes**: PascalCase (UserService)\n- **Functions/Variables**: camelCase (getUserById)\n- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)\n- **Database Tables**: snake_case (user_accounts)\n\n### Git Workflow\n- Branch names: `feature/description` or `fix/description`\n- Commit messages: Follow conventional commits\n- PR required before merge\n- All CI/CD checks must pass\n- Minimum 1 approval required\n\n### Testing Requirements\n- Minimum 80% code coverage\n- All critical paths must have tests\n- Use Jest for unit tests\n- Use Cypress for E2E tests\n- Test filenames: `*.test.ts` or `*.spec.ts`\n\n### API Standards\n- RESTful endpoints only\n- JSON request/response\n- Use HTTP status codes correctly\n- Version API endpoints: `/api/v1/`\n- Document all endpoints with examples\n\n### Database\n- Use migrations for schema changes\n- Never hardcode credentials\n- Use connection pooling\n- Enable query logging in development\n- Regular backups required\n\n### Deployment\n- Docker-based deployment\n- Kubernetes orchestration\n- Blue-green deployment strategy\n- Automatic rollback on failure\n- Database migrations run before deploy\n\n## Common Commands\n\n| Command | Purpose |\n|---------|---------|\n| `npm run dev` | Start development server |\n| `npm test` | Run test suite |\n| `npm run lint` | Check code style |\n| `npm run build` | Build for production |\n| `npm run migrate` | Run database migrations |\n\n## Team Contacts\n- Tech Lead: Sarah Chen (@sarah.chen)\n- Product Manager: Mike Johnson (@mike.j)\n- DevOps: Alex Kim (@alex.k)\n\n## Known Issues & Workarounds\n- PostgreSQL connection pooling limited to 20 during peak hours\n- Workaround: Implement query queuing\n- Safari 14 compatibility issues with async generators\n- Workaround: Use Babel transpiler\n\n## Related Projects\n- Analytics Dashboard: `/projects/analytics`\n- Mobile App: `/projects/mobile`\n- Admin Panel: `/projects/admin`\n```\n\n### Example 2: Directory-Specific Memory\n\n**File:** `./src/api/CLAUDE.md`\n\n```markdown\n# API Module Standards\n\nThis file overrides root CLAUDE.md for everything in /src/api/\n\n## API-Specific Standards\n\n### Request Validation\n- Use Zod for schema validation\n- Always validate input\n- Return 400 with validation errors\n- Include field-level error details\n\n### Authentication\n- All endpoints require JWT token\n- Token in Authorization header\n- Token expires after 24 hours\n- Implement refresh token mechanism\n\n### Response Format\n\nAll responses must follow this structure:\n\n```json\n{\n  \"success\": true,\n  \"data\": { /* actual data */ },\n  \"timestamp\": \"2025-11-06T10:30:00Z\",\n  \"version\": \"1.0\"\n}\n```\n\nError responses:\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"User message\",\n    \"details\": { /* field errors */ }\n  },\n  \"timestamp\": \"2025-11-06T10:30:00Z\"\n}\n```\n\n### Pagination\n- Use cursor-based pagination (not offset)\n- Include `hasMore` boolean\n- Limit max page size to 100\n- Default page size: 20\n\n### Rate Limiting\n- 1000 requests per hour for authenticated users\n- 100 requests per hour for public endpoints\n- Return 429 when exceeded\n- Include retry-after header\n\n### Caching\n- Use Redis for session caching\n- Cache duration: 5 minutes default\n- Invalidate on write operations\n- Tag cache keys with resource type\n```\n\n### Example 3: Personal Memory\n\n**File:** `~/.claude/CLAUDE.md`\n\n```markdown\n# My Development Preferences\n\n## About Me\n- **Experience Level**: 8 years full-stack development\n- **Preferred Languages**: TypeScript, Python\n- **Communication Style**: Direct, with examples\n- **Learning Style**: Visual diagrams with code\n\n## Code Preferences\n\n### Error Handling\nI prefer explicit error handling with try-catch blocks and meaningful error messages.\nAvoid generic errors. Always log errors for debugging.\n\n### Comments\nUse comments for WHY, not WHAT. Code should be self-documenting.\nComments should explain business logic or non-obvious decisions.\n\n### Testing\nI prefer TDD (test-driven development).\nWrite tests first, then implementation.\nFocus on behavior, not implementation details.\n\n### Architecture\nI prefer modular, loosely-coupled design.\nUse dependency injection for testability.\nSeparate concerns (Controllers, Services, Repositories).\n\n## Debugging Preferences\n- Use console.log with prefix: `[DEBUG]`\n- Include context: function name, relevant variables\n- Use stack traces when available\n- Always include timestamps in logs\n\n## Communication\n- Explain complex concepts with diagrams\n- Show concrete examples before explaining theory\n- Include before/after code snippets\n- Summarize key points at the end\n\n## Project Organization\nI organize my projects as:\n\n   project/\n   ├── src/\n   │   ├── api/\n   │   ├── services/\n   │   ├── models/\n   │   └── utils/\n   ├── tests/\n   ├── docs/\n   └── docker/\n\n## Tooling\n- **IDE**: VS Code with vim keybindings\n- **Terminal**: Zsh with Oh-My-Zsh\n- **Format**: Prettier (100 char line length)\n- **Linter**: ESLint with airbnb config\n- **Test Framework**: Jest with React Testing Library\n```\n\n_My Test_\nAsk Claude to save a new rule\n\n![Ask Claude to save a new rule](memory-ask-claude.png)\nClaude has not save the rule because I did not have any `Claude.md` file anywhere. Then asked Claude to confirm the location.\n\n![Ask Claude to save a new rule](memory-saved.png)\n\n### Example 4: Memory Update During Session\n\nYou can add new rules to memory during an active Claude Code session. There are two ways to do this:\n\n#### Method 1: Direct Request\n\n```markdown\nUser: Remember that I prefer using React hooks instead of class components\n     for all new components.\n\nClaude: I'm adding that to your memory. Which memory file should this go in?\n        1. Project memory (./CLAUDE.md)\n        2. Personal memory (~/.claude/CLAUDE.md)\n\nUser: Project memory\n\nClaude: ✅ Memory saved!\n\nAdded to ./CLAUDE.md:\n---\n\n### Component Development\n- Use functional components with React Hooks\n- Prefer hooks over class components\n- Custom hooks for reusable logic\n- Use useCallback for event handlers\n- Use useMemo for expensive computations\n```\n\n#### Method 2: Using \"# new rule into memory\" Pattern\n\nYou can also use the explicit pattern \"# new rule into memory\" to trigger memory updates:\n\n```markdown\nUser: # new rule into memory\n      Always validate user input with Zod schemas before processing.\n\nClaude: I'm saving this rule to memory. Which memory file should I use?\n        1. Project memory (./CLAUDE.md)\n        2. Personal memory (~/.claude/CLAUDE.md)\n\nUser: Project memory\n\nClaude: ✅ Memory saved!\n\nAdded to ./CLAUDE.md:\n---\n\n### Input Validation\n- Always validate user input with Zod schemas before processing\n- Define schemas at the top of each API handler file\n- Return 400 status with validation errors\n```\n\n#### Tips for Adding Memory\n\n- Be specific and actionable in your rules\n- Group related rules together under a section header\n- Update existing sections instead of duplicating content\n- Choose the appropriate memory scope (project vs. personal)\n\n## Memory Features Comparison\n\n| Feature | Claude Web/Desktop | Claude Code (CLAUDE.md) |\n|---------|-------------------|------------------------|\n| Auto-synthesis | ✅ Every 24h | ❌ Manual |\n| Cross-project | ✅ Shared | ❌ Project-specific |\n| Team access | ✅ Shared projects | ✅ Git-tracked |\n| Searchable | ✅ Built-in | ✅ Through `/memory` |\n| Editable | ✅ In-chat | ✅ Direct file edit |\n| Import/Export | ✅ Yes | ✅ Copy/paste |\n| Persistent | ✅ 24h+ | ✅ Indefinite |\n\n### Memory in Claude Web/Desktop\n\n#### Memory Synthesis Timeline\n\n```mermaid\ngraph LR\n    A[\"Day 1: User<br/>Conversations\"] -->|24 hours| B[\"Day 2: Memory<br/>Synthesis\"]\n    B -->|Automatic| C[\"Memory Updated<br/>Summarized\"]\n    C -->|Loaded in| D[\"Day 2-N:<br/>New Conversations\"]\n    D -->|Add to| E[\"Memory\"]\n    E -->|24 hours later| F[\"Memory Refreshed\"]\n```\n\n**Example Memory Summary:**\n\n```markdown\n## Claude's Memory of User\n\n### Professional Background\n- Senior full-stack developer with 8 years experience\n- Focus on TypeScript/Node.js backends and React frontends\n- Active open source contributor\n- Interested in AI and machine learning\n\n### Project Context\n- Currently building e-commerce platform\n- Tech stack: Node.js, PostgreSQL, React 18, Docker\n- Working with team of 5 developers\n- Using CI/CD and blue-green deployments\n\n### Communication Preferences\n- Prefers direct, concise explanations\n- Likes visual diagrams and examples\n- Appreciates code snippets\n- Explains business logic in comments\n\n### Current Goals\n- Improve API performance\n- Increase test coverage to 90%\n- Implement caching strategy\n- Document architecture\n```\n\n## Best Practices\n\n### Do's - What To Include\n\n- **Be specific and detailed**: Use clear, detailed instructions rather than vague guidance\n  - ✅ Good: \"Use 2-space indentation for all JavaScript files\"\n  - ❌ Avoid: \"Follow best practices\"\n\n- **Keep organized**: Structure memory files with clear markdown sections and headings\n\n- **Use appropriate hierarchy levels**:\n  - **Managed policy**: Company-wide policies, security standards, compliance requirements\n  - **Project memory**: Team standards, architecture, coding conventions (commit to git)\n  - **User memory**: Personal preferences, communication style, tooling choices\n  - **Directory memory**: Module-specific rules and overrides\n\n- **Leverage imports**: Use `@path/to/file` syntax to reference existing documentation\n  - Supports up to 5 levels of recursive nesting\n  - Avoids duplication across memory files\n  - Example: `See @README.md for project overview`\n\n- **Document frequent commands**: Include commands you use repeatedly to save time\n\n- **Version control project memory**: Commit project-level CLAUDE.md files to git for team benefit\n\n- **Review periodically**: Update memory regularly as projects evolve and requirements change\n\n- **Provide concrete examples**: Include code snippets and specific scenarios\n\n### Don'ts - What To Avoid\n\n- **Don't store secrets**: Never include API keys, passwords, tokens, or credentials\n\n- **Don't include sensitive data**: No PII, private information, or proprietary secrets\n\n- **Don't duplicate content**: Use imports (`@path`) to reference existing documentation instead\n\n- **Don't be vague**: Avoid generic statements like \"follow best practices\" or \"write good code\"\n\n- **Don't make it too long**: Keep individual memory files focused and under 500 lines\n\n- **Don't over-organize**: Use hierarchy strategically; don't create excessive subdirectory overrides\n\n- **Don't forget to update**: Stale memory can cause confusion and outdated practices\n\n- **Don't exceed nesting limits**: Memory imports support up to 5 levels of nesting\n\n### Memory Management Tips\n\n**Choose the right memory level:**\n\n| Use Case | Memory Level | Rationale |\n|----------|-------------|-----------|\n| Company security policy | Managed Policy | Applies to all projects organization-wide |\n| Team code style guide | Project | Shared with team via git |\n| Your preferred editor shortcuts | User | Personal preference, not shared |\n| API module standards | Directory | Specific to that module only |\n\n**Quick update workflow:**\n\n1. For single rules: Use `#` prefix in conversation\n2. For multiple changes: Use `/memory` to open editor\n3. For initial setup: Use `/init` to create template\n\n**Import best practices:**\n\n```markdown\n# Good: Reference existing docs\n@README.md\n@docs/architecture.md\n@package.json\n\n# Avoid: Copying content that exists elsewhere\n# Instead of copying README content into CLAUDE.md, just import it\n```\n\n## Installation Instructions\n\n### Setup Project Memory\n\n#### Method 1: Using `/init` Command (Recommended)\n\nThe fastest way to set up project memory:\n\n1. **Navigate to your project directory:**\n   ```bash\n   cd /path/to/your/project\n   ```\n\n2. **Run the init command in Claude Code:**\n   ```bash\n   /init\n   ```\n\n3. **Claude will create and populate CLAUDE.md** with a template structure\n\n4. **Customize the generated file** to match your project needs\n\n5. **Commit to git:**\n   ```bash\n   git add CLAUDE.md\n   git commit -m \"Initialize project memory with /init\"\n   ```\n\n#### Method 2: Manual Creation\n\nIf you prefer manual setup:\n\n1. **Create a CLAUDE.md in your project root:**\n   ```bash\n   cd /path/to/your/project\n   touch CLAUDE.md\n   ```\n\n2. **Add project standards:**\n   ```bash\n   cat > CLAUDE.md << 'EOF'\n   # Project Configuration\n\n   ## Project Overview\n   - **Name**: Your Project Name\n   - **Tech Stack**: List your technologies\n   - **Team Size**: Number of developers\n\n   ## Development Standards\n   - Your coding standards\n   - Naming conventions\n   - Testing requirements\n   EOF\n   ```\n\n3. **Commit to git:**\n   ```bash\n   git add CLAUDE.md\n   git commit -m \"Add project memory configuration\"\n   ```\n\n#### Method 3: Quick Updates with `#`\n\nOnce CLAUDE.md exists, add rules quickly during conversations:\n\n```markdown\n# Use semantic versioning for all releases\n\n# Always run tests before committing\n\n# Prefer composition over inheritance\n```\n\nClaude will prompt you to choose which memory file to update.\n\n### Setup Personal Memory\n\n1. **Create ~/.claude directory:**\n   ```bash\n   mkdir -p ~/.claude\n   ```\n\n2. **Create personal CLAUDE.md:**\n   ```bash\n   touch ~/.claude/CLAUDE.md\n   ```\n\n3. **Add your preferences:**\n   ```bash\n   cat > ~/.claude/CLAUDE.md << 'EOF'\n   # My Development Preferences\n\n   ## About Me\n   - Experience Level: [Your level]\n   - Preferred Languages: [Your languages]\n   - Communication Style: [Your style]\n\n   ## Code Preferences\n   - [Your preferences]\n   EOF\n   ```\n\n### Setup Directory-Specific Memory\n\n1. **Create memory for specific directories:**\n   ```bash\n   mkdir -p /path/to/directory/.claude\n   touch /path/to/directory/CLAUDE.md\n   ```\n\n2. **Add directory-specific rules:**\n   ```bash\n   cat > /path/to/directory/CLAUDE.md << 'EOF'\n   # [Directory Name] Standards\n\n   This file overrides root CLAUDE.md for this directory.\n\n   ## [Specific Standards]\n   EOF\n   ```\n\n3. **Commit to version control:**\n   ```bash\n   git add /path/to/directory/CLAUDE.md\n   git commit -m \"Add [directory] memory configuration\"\n   ```\n\n### Verify Setup\n\n1. **Check memory locations:**\n   ```bash\n   # Project root memory\n   ls -la ./CLAUDE.md\n\n   # Personal memory\n   ls -la ~/.claude/CLAUDE.md\n   ```\n\n2. **Claude Code will automatically load** these files when starting a session\n\n3. **Test with Claude Code** by starting a new session in your project\n\n## Official Documentation\n\nFor the most up-to-date information, refer to the official Claude Code documentation:\n\n- **[Memory Documentation](https://code.claude.com/docs/en/memory)** - Complete memory system reference\n- **[Slash Commands Reference](https://code.claude.com/docs/en/interactive-mode)** - All built-in commands including `/init` and `/memory`\n- **[CLI Reference](https://code.claude.com/docs/en/cli-reference)** - Command-line interface documentation\n\n### Key Technical Details from Official Docs\n\n**Memory Loading:**\n\n- All memory files are automatically loaded when Claude Code launches\n- Claude traverses upward from the current working directory to discover CLAUDE.md files\n- Subtree files are discovered and loaded contextually when accessing those directories\n\n**Import Syntax:**\n\n- Use `@path/to/file` to include external content (e.g., `@~/.claude/my-project-instructions.md`)\n- Supports both relative and absolute paths\n- Recursive imports supported with a maximum depth of 5\n- First-time external imports trigger an approval dialog\n- Not evaluated inside markdown code spans or code blocks\n- Automatically includes referenced content in Claude's context\n\n**Memory Hierarchy Precedence:**\n\n1. Managed Policy (highest precedence)\n2. Managed Drop-ins (`managed-settings.d/`, v2.1.83+)\n3. Project Memory\n4. Project Rules (`.claude/rules/`)\n5. User Memory\n6. User-Level Rules (`~/.claude/rules/`)\n7. Local Project Memory\n8. Auto Memory (lowest precedence)\n\n## Related Concepts Links\n\n### Integration Points\n- [MCP Protocol](../05-mcp/) - Live data access alongside memory\n- [Slash Commands](../01-slash-commands/) - Session-specific shortcuts\n- [Skills](../03-skills/) - Automated workflows with memory context\n\n### Related Claude Features\n- [Claude Web Memory](https://claude.ai) - Automatic synthesis\n- [Official Memory Docs](https://code.claude.com/docs/en/memory) - Anthropic documentation\n"
  },
  {
    "path": "02-memory/directory-api-CLAUDE.md",
    "content": "# API Module Standards\n\nThis file overrides root CLAUDE.md for everything in /src/api/\n\n## API-Specific Standards\n\n### Request Validation\n- Use Zod for schema validation\n- Always validate input\n- Return 400 with validation errors\n- Include field-level error details\n\n### Authentication\n- All endpoints require JWT token\n- Token in Authorization header\n- Token expires after 24 hours\n- Implement refresh token mechanism\n\n### Response Format\n\nAll responses must follow this structure:\n\n```json\n{\n  \"success\": true,\n  \"data\": { /* actual data */ },\n  \"timestamp\": \"2025-11-06T10:30:00Z\",\n  \"version\": \"1.0\"\n}\n```\n\nError responses:\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"User message\",\n    \"details\": { /* field errors */ }\n  },\n  \"timestamp\": \"2025-11-06T10:30:00Z\"\n}\n```\n\n### Pagination\n- Use cursor-based pagination (not offset)\n- Include `hasMore` boolean\n- Limit max page size to 100\n- Default page size: 20\n\n### Rate Limiting\n- 1000 requests per hour for authenticated users\n- 100 requests per hour for public endpoints\n- Return 429 when exceeded\n- Include retry-after header\n\n### Caching\n- Use Redis for session caching\n- Cache duration: 5 minutes default\n- Invalidate on write operations\n- Tag cache keys with resource type\n"
  },
  {
    "path": "02-memory/personal-CLAUDE.md",
    "content": "# My Development Preferences\n\n## About Me\n- **Experience Level**: 8 years full-stack development\n- **Preferred Languages**: TypeScript, Python\n- **Communication Style**: Direct, with examples\n- **Learning Style**: Visual diagrams with code\n\n## Code Preferences\n\n### Error Handling\nI prefer explicit error handling with try-catch blocks and meaningful error messages.\nAvoid generic errors. Always log errors for debugging.\n\n### Comments\nUse comments for WHY, not WHAT. Code should be self-documenting.\nComments should explain business logic or non-obvious decisions.\n\n### Testing\nI prefer TDD (test-driven development).\nWrite tests first, then implementation.\nFocus on behavior, not implementation details.\n\n### Architecture\nI prefer modular, loosely-coupled design.\nUse dependency injection for testability.\nSeparate concerns (Controllers, Services, Repositories).\n\n## Debugging Preferences\n- Use console.log with prefix: `[DEBUG]`\n- Include context: function name, relevant variables\n- Use stack traces when available\n- Always include timestamps in logs\n\n## Communication\n- Explain complex concepts with diagrams\n- Show concrete examples before explaining theory\n- Include before/after code snippets\n- Summarize key points at the end\n\n## Project Organization\nI organize my projects as:\n```\nproject/\n  ├── src/\n  │   ├── api/\n  │   ├── services/\n  │   ├── models/\n  │   └── utils/\n  ├── tests/\n  ├── docs/\n  └── docker/\n```\n\n## Tooling\n- **IDE**: VS Code with vim keybindings\n- **Terminal**: Zsh with Oh-My-Zsh\n- **Format**: Prettier (100 char line length)\n- **Linter**: ESLint with airbnb config\n- **Test Framework**: Jest with React Testing Library\n"
  },
  {
    "path": "02-memory/project-CLAUDE.md",
    "content": "# Project Configuration\n\n## Project Overview\n- **Name**: E-commerce Platform\n- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker\n- **Team Size**: 5 developers\n- **Deadline**: Q4 2025\n\n## Architecture\n@docs/architecture.md\n@docs/api-standards.md\n@docs/database-schema.md\n\n## Development Standards\n\n### Code Style\n- Use Prettier for formatting\n- Use ESLint with airbnb config\n- Maximum line length: 100 characters\n- Use 2-space indentation\n\n### Naming Conventions\n- **Files**: kebab-case (user-controller.js)\n- **Classes**: PascalCase (UserService)\n- **Functions/Variables**: camelCase (getUserById)\n- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)\n- **Database Tables**: snake_case (user_accounts)\n\n### Git Workflow\n- Branch names: `feature/description` or `fix/description`\n- Commit messages: Follow conventional commits\n- PR required before merge\n- All CI/CD checks must pass\n- Minimum 1 approval required\n\n### Testing Requirements\n- Minimum 80% code coverage\n- All critical paths must have tests\n- Use Jest for unit tests\n- Use Cypress for E2E tests\n- Test filenames: `*.test.ts` or `*.spec.ts`\n\n### API Standards\n- RESTful endpoints only\n- JSON request/response\n- Use HTTP status codes correctly\n- Version API endpoints: `/api/v1/`\n- Document all endpoints with examples\n\n### Database\n- Use migrations for schema changes\n- Never hardcode credentials\n- Use connection pooling\n- Enable query logging in development\n- Regular backups required\n\n### Deployment\n- Docker-based deployment\n- Kubernetes orchestration\n- Blue-green deployment strategy\n- Automatic rollback on failure\n- Database migrations run before deploy\n\n## Common Commands\n\n| Command | Purpose |\n|---------|---------|\n| `npm run dev` | Start development server |\n| `npm test` | Run test suite |\n| `npm run lint` | Check code style |\n| `npm run build` | Build for production |\n| `npm run migrate` | Run database migrations |\n\n## Team Contacts\n- Tech Lead: Sarah Chen (@sarah.chen)\n- Product Manager: Mike Johnson (@mike.j)\n- DevOps: Alex Kim (@alex.k)\n\n## Known Issues & Workarounds\n- PostgreSQL connection pooling limited to 20 during peak hours\n- Workaround: Implement query queuing\n- Safari 14 compatibility issues with async generators\n- Workaround: Use Babel transpiler\n\n## Related Projects\n- Analytics Dashboard: `/projects/analytics`\n- Mobile App: `/projects/mobile`\n- Admin Panel: `/projects/admin`\n"
  },
  {
    "path": "03-skills/.gitignore",
    "content": "# Local skill testing\n.claude/\n\n# Blog post outputs\nblog-posts/\n"
  },
  {
    "path": "03-skills/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Agent Skills Guide\n\nAgent Skills are reusable, filesystem-based capabilities that extend Claude's functionality. They package domain-specific expertise, workflows, and best practices into discoverable components that Claude automatically uses when relevant.\n\n## Overview\n\n**Agent Skills** are modular capabilities that transform general-purpose agents into specialists. Unlike prompts (conversation-level instructions for one-off tasks), Skills load on-demand and eliminate the need to repeatedly provide the same guidance across multiple conversations.\n\n### Key Benefits\n\n- **Specialize Claude**: Tailor capabilities for domain-specific tasks\n- **Reduce repetition**: Create once, use automatically across conversations\n- **Compose capabilities**: Combine Skills to build complex workflows\n- **Scale workflows**: Reuse skills across multiple projects and teams\n- **Maintain quality**: Embed best practices directly into your workflow\n\nSkills follow the [Agent Skills](https://agentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like invocation control, subagent execution, and dynamic context injection.\n\n> **Note**: Custom slash commands have been merged into skills. `.claude/commands/` files still work and support the same frontmatter fields. Skills are recommended for new development. When both exist at the same path (e.g., `.claude/commands/review.md` and `.claude/skills/review/SKILL.md`), the skill takes precedence.\n\n## How Skills Work: Progressive Disclosure\n\nSkills leverage a **progressive disclosure** architecture—Claude loads information in stages as needed, rather than consuming context upfront. This enables efficient context management while maintaining unlimited scalability.\n\n### Three Levels of Loading\n\n```mermaid\ngraph TB\n    subgraph \"Level 1: Metadata (Always Loaded)\"\n        A[\"YAML Frontmatter\"]\n        A1[\"~100 tokens per skill\"]\n        A2[\"name + description\"]\n    end\n\n    subgraph \"Level 2: Instructions (When Triggered)\"\n        B[\"SKILL.md Body\"]\n        B1[\"Under 5k tokens\"]\n        B2[\"Workflows & guidance\"]\n    end\n\n    subgraph \"Level 3: Resources (As Needed)\"\n        C[\"Bundled Files\"]\n        C1[\"Effectively unlimited\"]\n        C2[\"Scripts, templates, docs\"]\n    end\n\n    A --> B\n    B --> C\n```\n\n| Level | When Loaded | Token Cost | Content |\n|-------|------------|------------|---------|\n| **Level 1: Metadata** | Always (at startup) | ~100 tokens per Skill | `name` and `description` from YAML frontmatter |\n| **Level 2: Instructions** | When Skill is triggered | Under 5k tokens | SKILL.md body with instructions and guidance |\n| **Level 3+: Resources** | As needed | Effectively unlimited | Bundled files executed via bash without loading contents into context |\n\nThis means you can install many Skills without context penalty—Claude only knows each Skill exists and when to use it until actually triggered.\n\n## Skill Loading Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude\n    participant System as System\n    participant Skill as Skill\n\n    User->>Claude: \"Review this code for security issues\"\n    Claude->>System: Check available skills (metadata)\n    System-->>Claude: Skill descriptions loaded at startup\n    Claude->>Claude: Match request to skill description\n    Claude->>Skill: bash: read code-review/SKILL.md\n    Skill-->>Claude: Instructions loaded into context\n    Claude->>Claude: Determine: Need templates?\n    Claude->>Skill: bash: read templates/checklist.md\n    Skill-->>Claude: Template loaded\n    Claude->>Claude: Execute skill instructions\n    Claude->>User: Comprehensive code review\n```\n\n## Skill Types & Locations\n\n| Type | Location | Scope | Shared | Best For |\n|------|----------|-------|--------|----------|\n| **Enterprise** | Managed settings | All org users | Yes | Organization-wide standards |\n| **Personal** | `~/.claude/skills/<skill-name>/SKILL.md` | Individual | No | Personal workflows |\n| **Project** | `.claude/skills/<skill-name>/SKILL.md` | Team | Yes (via git) | Team standards |\n| **Plugin** | `<plugin>/skills/<skill-name>/SKILL.md` | Where enabled | Depends | Bundled with plugins |\n\nWhen skills share the same name across levels, higher-priority locations win: **enterprise > personal > project**. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict.\n\n### Automatic Discovery\n\n**Nested directories**: When you work with files in subdirectories, Claude Code automatically discovers skills from nested `.claude/skills/` directories. For example, if you're editing a file in `packages/frontend/`, Claude Code also looks for skills in `packages/frontend/.claude/skills/`. This supports monorepo setups where packages have their own skills.\n\n**`--add-dir` directories**: Skills from directories added via `--add-dir` are loaded automatically with live change detection. Any edits to skill files in those directories take effect immediately without restarting Claude Code.\n\n**Description budget**: Skill descriptions (Level 1 metadata) are capped at **2% of the context window** (fallback: **16,000 characters**). If you have many skills installed, some may be excluded. Run `/context` to check for warnings. Override the budget with the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.\n\n## Creating Custom Skills\n\n### Basic Directory Structure\n\n```\nmy-skill/\n├── SKILL.md           # Main instructions (required)\n├── template.md        # Template for Claude to fill in\n├── examples/\n│   └── sample.md      # Example output showing expected format\n└── scripts/\n    └── validate.sh    # Script Claude can execute\n```\n\n### SKILL.md Format\n\n```yaml\n---\nname: your-skill-name\ndescription: Brief description of what this Skill does and when to use it\n---\n\n# Your Skill Name\n\n## Instructions\nProvide clear, step-by-step guidance for Claude.\n\n## Examples\nShow concrete examples of using this Skill.\n```\n\n### Required Fields\n\n- **name**: lowercase letters, numbers, hyphens only (max 64 characters). Cannot contain \"anthropic\" or \"claude\".\n- **description**: what the Skill does AND when to use it (max 1024 characters). This is critical for Claude to know when to activate the skill.\n\n### Optional Frontmatter Fields\n\n```yaml\n---\nname: my-skill\ndescription: What this skill does and when to use it\nargument-hint: \"[filename] [format]\"        # Hint for autocomplete\ndisable-model-invocation: true              # Only user can invoke\nuser-invocable: false                       # Hide from slash menu\nallowed-tools: Read, Grep, Glob             # Restrict tool access\nmodel: opus                                 # Specific model to use\neffort: high                                # Effort level override (low, medium, high, max)\ncontext: fork                               # Run in isolated subagent\nagent: Explore                              # Which agent type (with context: fork)\nshell: bash                                 # Shell for commands: bash (default) or powershell\nhooks:                                      # Skill-scoped hooks\n  PreToolUse:\n    - matcher: \"Bash\"\n      hooks:\n        - type: command\n          command: \"./scripts/validate.sh\"\n---\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Lowercase letters, numbers, hyphens only (max 64 chars). Cannot contain \"anthropic\" or \"claude\". |\n| `description` | What the Skill does AND when to use it (max 1024 chars). Critical for auto-invocation matching. |\n| `argument-hint` | Hint shown in the `/` autocomplete menu (e.g., `\"[filename] [format]\"`). |\n| `disable-model-invocation` | `true` = only the user can invoke via `/name`. Claude will never auto-invoke. |\n| `user-invocable` | `false` = hidden from the `/` menu. Only Claude can invoke it automatically. |\n| `allowed-tools` | Comma-separated list of tools the skill may use without permission prompts. |\n| `model` | Model override while the skill is active (e.g., `opus`, `sonnet`). |\n| `effort` | Effort level override while the skill is active: `low`, `medium`, `high`, or `max`. |\n| `context` | `fork` to run the skill in a forked subagent context with its own context window. |\n| `agent` | Subagent type when `context: fork` (e.g., `Explore`, `Plan`, `general-purpose`). |\n| `shell` | Shell used for `!`command`` substitutions and scripts: `bash` (default) or `powershell`. |\n| `hooks` | Hooks scoped to this skill's lifecycle (same format as global hooks). |\n\n## Skill Content Types\n\nSkills can contain two types of content, each suited for different purposes:\n\n### Reference Content\n\nAdds knowledge Claude applies to your current work—conventions, patterns, style guides, domain knowledge. Runs inline with your conversation context.\n\n```yaml\n---\nname: api-conventions\ndescription: API design patterns for this codebase\n---\n\nWhen writing API endpoints:\n- Use RESTful naming conventions\n- Return consistent error formats\n- Include request validation\n```\n\n### Task Content\n\nStep-by-step instructions for specific actions. Often invoked directly with `/skill-name`.\n\n```yaml\n---\nname: deploy\ndescription: Deploy the application to production\ncontext: fork\ndisable-model-invocation: true\n---\n\nDeploy the application:\n1. Run the test suite\n2. Build the application\n3. Push to the deployment target\n```\n\n## Controlling Skill Invocation\n\nBy default, both you and Claude can invoke any skill. Two frontmatter fields control the three invocation modes:\n\n| Frontmatter | You can invoke | Claude can invoke |\n|---|---|---|\n| (default) | Yes | Yes |\n| `disable-model-invocation: true` | Yes | No |\n| `user-invocable: false` | No | Yes |\n\n**Use `disable-model-invocation: true`** for workflows with side effects: `/commit`, `/deploy`, `/send-slack-message`. You don't want Claude deciding to deploy because your code looks ready.\n\n**Use `user-invocable: false`** for background knowledge that isn't actionable as a command. A `legacy-system-context` skill explains how an old system works—useful for Claude, but not a meaningful action for users.\n\n## String Substitutions\n\nSkills support dynamic values that are resolved before the skill content reaches Claude:\n\n| Variable | Description |\n|----------|-------------|\n| `$ARGUMENTS` | All arguments passed when invoking the skill |\n| `$ARGUMENTS[N]` or `$N` | Access specific argument by index (0-based) |\n| `${CLAUDE_SESSION_ID}` | Current session ID |\n| `${CLAUDE_SKILL_DIR}` | Directory containing the skill's SKILL.md file |\n| `` !`command` `` | Dynamic context injection — runs a shell command and inlines the output |\n\n**Example:**\n\n```yaml\n---\nname: fix-issue\ndescription: Fix a GitHub issue\n---\n\nFix GitHub issue $ARGUMENTS following our coding standards.\n1. Read the issue description\n2. Implement the fix\n3. Write tests\n4. Create a commit\n```\n\nRunning `/fix-issue 123` replaces `$ARGUMENTS` with `123`.\n\n## Injecting Dynamic Context\n\nThe `!`command`` syntax runs shell commands before the skill content is sent to Claude:\n\n```yaml\n---\nname: pr-summary\ndescription: Summarize changes in a pull request\ncontext: fork\nagent: Explore\n---\n\n## Pull request context\n- PR diff: !`gh pr diff`\n- PR comments: !`gh pr view --comments`\n- Changed files: !`gh pr diff --name-only`\n\n## Your task\nSummarize this pull request...\n```\n\nCommands execute immediately; Claude only sees the final output. By default, commands run in `bash`. Set `shell: powershell` in frontmatter to use PowerShell instead.\n\n## Running Skills in Subagents\n\nAdd `context: fork` to run a skill in an isolated subagent context. The skill content becomes the task for a dedicated subagent with its own context window, keeping the main conversation uncluttered.\n\nThe `agent` field specifies which agent type to use:\n\n| Agent Type | Best For |\n|---|---|\n| `Explore` | Read-only research, codebase analysis |\n| `Plan` | Creating implementation plans |\n| `general-purpose` | Broad tasks requiring all tools |\n| Custom agents | Specialized agents defined in your configuration |\n\n**Example frontmatter:**\n\n```yaml\n---\ncontext: fork\nagent: Explore\n---\n```\n\n**Full skill example:**\n\n```yaml\n---\nname: deep-research\ndescription: Research a topic thoroughly\ncontext: fork\nagent: Explore\n---\n\nResearch $ARGUMENTS thoroughly:\n1. Find relevant files using Glob and Grep\n2. Read and analyze the code\n3. Summarize findings with specific file references\n```\n\n## Practical Examples\n\n### Example 1: Code Review Skill\n\n**Directory Structure:**\n\n```\n~/.claude/skills/code-review/\n├── SKILL.md\n├── templates/\n│   ├── review-checklist.md\n│   └── finding-template.md\n└── scripts/\n    ├── analyze-metrics.py\n    └── compare-complexity.py\n```\n\n**File:** `~/.claude/skills/code-review/SKILL.md`\n\n```yaml\n---\nname: code-review-specialist\ndescription: Comprehensive code review with security, performance, and quality analysis. Use when users ask to review code, analyze code quality, evaluate pull requests, or mention code review, security analysis, or performance optimization.\n---\n\n# Code Review Skill\n\nThis skill provides comprehensive code review capabilities focusing on:\n\n1. **Security Analysis**\n   - Authentication/authorization issues\n   - Data exposure risks\n   - Injection vulnerabilities\n   - Cryptographic weaknesses\n\n2. **Performance Review**\n   - Algorithm efficiency (Big O analysis)\n   - Memory optimization\n   - Database query optimization\n   - Caching opportunities\n\n3. **Code Quality**\n   - SOLID principles\n   - Design patterns\n   - Naming conventions\n   - Test coverage\n\n4. **Maintainability**\n   - Code readability\n   - Function size (should be < 50 lines)\n   - Cyclomatic complexity\n   - Type safety\n\n## Review Template\n\nFor each piece of code reviewed, provide:\n\n### Summary\n- Overall quality assessment (1-5)\n- Key findings count\n- Recommended priority areas\n\n### Critical Issues (if any)\n- **Issue**: Clear description\n- **Location**: File and line number\n- **Impact**: Why this matters\n- **Severity**: Critical/High/Medium\n- **Fix**: Code example\n\nFor detailed checklists, see [templates/review-checklist.md](templates/review-checklist.md).\n```\n\n### Example 2: Codebase Visualizer Skill\n\nA skill that generates interactive HTML visualizations:\n\n**Directory Structure:**\n\n```\n~/.claude/skills/codebase-visualizer/\n├── SKILL.md\n└── scripts/\n    └── visualize.py\n```\n\n**File:** `~/.claude/skills/codebase-visualizer/SKILL.md`\n\n```yaml\n---\nname: codebase-visualizer\ndescription: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.\nallowed-tools: Bash(python *)\n---\n\n# Codebase Visualizer\n\nGenerate an interactive HTML tree view showing your project's file structure.\n\n## Usage\n\nRun the visualization script from your project root:\n\n```bash\npython ~/.claude/skills/codebase-visualizer/scripts/visualize.py .\n```\n\nThis creates `codebase-map.html` and opens it in your default browser.\n\n## What the visualization shows\n\n- **Collapsible directories**: Click folders to expand/collapse\n- **File sizes**: Displayed next to each file\n- **Colors**: Different colors for different file types\n- **Directory totals**: Shows aggregate size of each folder\n```\n\nThe bundled Python script does the heavy lifting while Claude handles orchestration.\n\n### Example 3: Deploy Skill (User-Invoked Only)\n\n```yaml\n---\nname: deploy\ndescription: Deploy the application to production\ndisable-model-invocation: true\nallowed-tools: Bash(npm *), Bash(git *)\n---\n\nDeploy $ARGUMENTS to production:\n\n1. Run the test suite: `npm test`\n2. Build the application: `npm run build`\n3. Push to the deployment target\n4. Verify the deployment succeeded\n5. Report deployment status\n```\n\n### Example 4: Brand Voice Skill (Background Knowledge)\n\n```yaml\n---\nname: brand-voice\ndescription: Ensure all communication matches brand voice and tone guidelines. Use when creating marketing copy, customer communications, or public-facing content.\nuser-invocable: false\n---\n\n## Tone of Voice\n- **Friendly but professional** - approachable without being casual\n- **Clear and concise** - avoid jargon\n- **Confident** - we know what we're doing\n- **Empathetic** - understand user needs\n\n## Writing Guidelines\n- Use \"you\" when addressing readers\n- Use active voice\n- Keep sentences under 20 words\n- Start with value proposition\n\nFor templates, see [templates/](templates/).\n```\n\n### Example 5: CLAUDE.md Generator Skill\n\n```yaml\n---\nname: claude-md\ndescription: Create or update CLAUDE.md files following best practices for optimal AI agent onboarding. Use when users mention CLAUDE.md, project documentation, or AI onboarding.\n---\n\n## Core Principles\n\n**LLMs are stateless**: CLAUDE.md is the only file automatically included in every conversation.\n\n### The Golden Rules\n\n1. **Less is More**: Keep under 300 lines (ideally under 100)\n2. **Universal Applicability**: Only include information relevant to EVERY session\n3. **Don't Use Claude as a Linter**: Use deterministic tools instead\n4. **Never Auto-Generate**: Craft it manually with careful consideration\n\n## Essential Sections\n\n- **Project Name**: Brief one-line description\n- **Tech Stack**: Primary language, frameworks, database\n- **Development Commands**: Install, test, build commands\n- **Critical Conventions**: Only non-obvious, high-impact conventions\n- **Known Issues / Gotchas**: Things that trip up developers\n```\n\n### Example 6: Refactoring Skill with Scripts\n\n**Directory Structure:**\n\n```\nrefactor/\n├── SKILL.md\n├── references/\n│   ├── code-smells.md\n│   └── refactoring-catalog.md\n├── templates/\n│   └── refactoring-plan.md\n└── scripts/\n    ├── analyze-complexity.py\n    └── detect-smells.py\n```\n\n**File:** `refactor/SKILL.md`\n\n```yaml\n---\nname: code-refactor\ndescription: Systematic code refactoring based on Martin Fowler's methodology. Use when users ask to refactor code, improve code structure, reduce technical debt, or eliminate code smells.\n---\n\n# Code Refactoring Skill\n\nA phased approach emphasizing safe, incremental changes backed by tests.\n\n## Workflow\n\nPhase 1: Research & Analysis → Phase 2: Test Coverage Assessment →\nPhase 3: Code Smell Identification → Phase 4: Refactoring Plan Creation →\nPhase 5: Incremental Implementation → Phase 6: Review & Iteration\n\n## Core Principles\n\n1. **Behavior Preservation**: External behavior must remain unchanged\n2. **Small Steps**: Make tiny, testable changes\n3. **Test-Driven**: Tests are the safety net\n4. **Continuous**: Refactoring is ongoing, not a one-time event\n\nFor code smell catalog, see [references/code-smells.md](references/code-smells.md).\nFor refactoring techniques, see [references/refactoring-catalog.md](references/refactoring-catalog.md).\n```\n\n## Supporting Files\n\nSkills can include multiple files in their directory beyond `SKILL.md`. These supporting files (templates, examples, scripts, reference documents) let you keep the main skill file focused while providing Claude with additional resources it can load as needed.\n\n```\nmy-skill/\n├── SKILL.md              # Main instructions (required, keep under 500 lines)\n├── templates/            # Templates for Claude to fill in\n│   └── output-format.md\n├── examples/             # Example outputs showing expected format\n│   └── sample-output.md\n├── references/           # Domain knowledge and specifications\n│   └── api-spec.md\n└── scripts/              # Scripts Claude can execute\n    └── validate.sh\n```\n\nGuidelines for supporting files:\n\n- Keep `SKILL.md` under **500 lines**. Move detailed reference material, large examples, and specifications to separate files.\n- Reference additional files from `SKILL.md` using **relative paths** (e.g., `[API reference](references/api-spec.md)`).\n- Supporting files are loaded at Level 3 (as needed), so they do not consume context until Claude actually reads them.\n\n## Managing Skills\n\n### Viewing Available Skills\n\nAsk Claude directly:\n```\nWhat Skills are available?\n```\n\nOr check the filesystem:\n```bash\n# List personal Skills\nls ~/.claude/skills/\n\n# List project Skills\nls .claude/skills/\n```\n\n### Testing a Skill\n\nTwo ways to test:\n\n**Let Claude invoke it automatically** by asking something that matches the description:\n```\nCan you help me review this code for security issues?\n```\n\n**Or invoke it directly** with the skill name:\n```\n/code-review src/auth/login.ts\n```\n\n### Updating a Skill\n\nEdit the `SKILL.md` file directly. Changes take effect on next Claude Code startup.\n\n```bash\n# Personal Skill\ncode ~/.claude/skills/my-skill/SKILL.md\n\n# Project Skill\ncode .claude/skills/my-skill/SKILL.md\n```\n\n### Restricting Claude's Skill Access\n\nThree ways to control which skills Claude can invoke:\n\n**Disable all skills** in `/permissions`:\n```\n# Add to deny rules:\nSkill\n```\n\n**Allow or deny specific skills**:\n```\n# Allow only specific skills\nSkill(commit)\nSkill(review-pr *)\n\n# Deny specific skills\nSkill(deploy *)\n```\n\n**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter.\n\n## Best Practices\n\n### 1. Make Descriptions Specific\n\n- **Bad (Vague)**: \"Helps with documents\"\n- **Good (Specific)**: \"Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.\"\n\n### 2. Keep Skills Focused\n\n- One Skill = one capability\n- ✅ \"PDF form filling\"\n- ❌ \"Document processing\" (too broad)\n\n### 3. Include Trigger Terms\n\nAdd keywords in descriptions that match user requests:\n```yaml\ndescription: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files.\n```\n\n### 4. Keep SKILL.md Under 500 Lines\n\nMove detailed reference material to separate files that Claude loads as needed.\n\n### 5. Reference Supporting Files\n\n```markdown\n## Additional resources\n\n- For complete API details, see [reference.md](reference.md)\n- For usage examples, see [examples.md](examples.md)\n```\n\n### Do's\n\n- Use clear, descriptive names\n- Include comprehensive instructions\n- Add concrete examples\n- Package related scripts and templates\n- Test with real scenarios\n- Document dependencies\n\n### Don'ts\n\n- Don't create skills for one-time tasks\n- Don't duplicate existing functionality\n- Don't make skills too broad\n- Don't skip the description field\n- Don't install skills from untrusted sources without auditing\n\n## Troubleshooting\n\n### Quick Reference\n\n| Issue | Solution |\n|-------|----------|\n| Claude doesn't use Skill | Make description more specific with trigger terms |\n| Skill file not found | Verify path: `~/.claude/skills/name/SKILL.md` |\n| YAML errors | Check `---` markers, indentation, no tabs |\n| Skills conflict | Use distinct trigger terms in descriptions |\n| Scripts not running | Check permissions: `chmod +x scripts/*.py` |\n| Claude doesn't see all skills | Too many skills; check `/context` for warnings |\n\n### Skill Not Triggering\n\nIf Claude doesn't use your skill when expected:\n\n1. Check the description includes keywords users would naturally say\n2. Verify the skill appears when asking \"What skills are available?\"\n3. Try rephrasing your request to match the description\n4. Invoke directly with `/skill-name` to test\n\n### Skill Triggers Too Often\n\nIf Claude uses your skill when you don't want it:\n\n1. Make the description more specific\n2. Add `disable-model-invocation: true` for manual-only invocation\n\n### Claude Doesn't See All Skills\n\nSkill descriptions are loaded at **2% of the context window** (fallback: **16,000 characters**). Run `/context` to check for warnings about excluded skills. Override the budget with the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.\n\n## Security Considerations\n\n**Only use Skills from trusted sources.** Skills provide Claude with capabilities through instructions and code—a malicious Skill can direct Claude to invoke tools or execute code in harmful ways.\n\n**Key security considerations:**\n\n- **Audit thoroughly**: Review all files in the Skill directory\n- **External sources are risky**: Skills that fetch from external URLs can be compromised\n- **Tool misuse**: Malicious Skills can invoke tools in harmful ways\n- **Treat like installing software**: Only use Skills from trusted sources\n\n## Skills vs Other Features\n\n| Feature | Invocation | Best For |\n|---------|------------|----------|\n| **Skills** | Auto or `/name` | Reusable expertise, workflows |\n| **Slash Commands** | User-initiated `/name` | Quick shortcuts (merged into skills) |\n| **Subagents** | Auto-delegated | Isolated task execution |\n| **Memory (CLAUDE.md)** | Always loaded | Persistent project context |\n| **MCP** | Real-time | External data/service access |\n| **Hooks** | Event-driven | Automated side effects |\n\n## Bundled Skills\n\nClaude Code ships with several built-in skills that are always available without installation:\n\n| Skill | Description |\n|-------|-------------|\n| `/simplify` | Review changed files for reuse, quality, and efficiency; spawns 3 parallel review agents |\n| `/batch <instruction>` | Orchestrate large-scale parallel changes across codebase using git worktrees |\n| `/debug [description]` | Troubleshoot current session by reading debug log |\n| `/loop [interval] <prompt>` | Run prompt repeatedly on interval (e.g., `/loop 5m check the deploy`) |\n| `/claude-api` | Load Claude API/SDK reference; auto-activates on `anthropic`/`@anthropic-ai/sdk` imports |\n\nThese skills are available out-of-the-box and do not need to be installed or configured. They follow the same SKILL.md format as custom skills.\n\n## Sharing Skills\n\n### Project Skills (Team Sharing)\n\n1. Create Skill in `.claude/skills/`\n2. Commit to git\n3. Team members pull changes — Skills available immediately\n\n### Personal Skills\n\n```bash\n# Copy to personal directory\ncp -r my-skill ~/.claude/skills/\n\n# Make scripts executable\nchmod +x ~/.claude/skills/my-skill/scripts/*.py\n```\n\n### Plugin Distribution\n\nPackage skills in a plugin's `skills/` directory for broader distribution.\n\n## Going Further: A Skill Collection and a Skill Manager\n\nOnce you start building skills seriously, two things become essential: a library of proven skills and a tool to manage them.\n\n**[luongnv89/skills](https://github.com/luongnv89/skills)** — A collection of skills I use daily across almost all my projects. Highlights include `logo-designer` (generates project logos on the fly) and `ollama-optimizer` (tunes local LLM performance for your hardware). Great starting point if you want ready-to-use skills.\n\n**[luongnv89/asm](https://github.com/luongnv89/asm)** — Agent Skill Manager. Handles skill development, duplicate detection, and testing. The `asm link` command lets you test a skill in any project without copying files around — essential once you have more than a handful of skills.\n\n## Additional Resources\n\n- [Official Skills Documentation](https://code.claude.com/docs/en/skills)\n- [Agent Skills Architecture Blog](https://claude.com/blog/equipping-agents-for-the-real-world-with-agent-skills)\n- [Skills Repository](https://github.com/luongnv89/skills) - Collection of ready-to-use skills\n- [Slash Commands Guide](../01-slash-commands/) - User-initiated shortcuts\n- [Subagents Guide](../04-subagents/) - Delegated AI agents\n- [Memory Guide](../02-memory/) - Persistent context\n- [MCP (Model Context Protocol)](../05-mcp/) - Real-time external data\n- [Hooks Guide](../06-hooks/) - Event-driven automation\n"
  },
  {
    "path": "03-skills/blog-draft/SKILL.md",
    "content": "---\nname: blog-draft\ndescription: Draft a blog post from ideas and resources. Use when users want to write a blog post, create content from research, or draft articles. Guides through research, brainstorming, outlining, and iterative drafting with version control.\n---\n\n## User Input\n\n```text\n$ARGUMENTS\n```\n\nYou **MUST** consider the user input before proceeding. User should provide:\n- **Idea/Topic**: The main concept or theme for the blog post\n- **Resources**: URLs, files, or references to research (optional but recommended)\n- **Target audience**: Who the blog post is for (optional)\n- **Tone/Style**: Formal, casual, technical, etc. (optional)\n\n**IMPORTANT**: If the user is requesting updates to an **existing blog post**, skip steps 0-8 and start directly at **Step 9**. Read the existing draft file(s) first, then proceed with the iteration process.\n\n## Execution Flow\n\nFollow these steps sequentially. **Do not skip steps or proceed without user approval where indicated.**\n\n### Step 0: Create Project Folder\n\n1. Generate a folder name using format: `YYYY-MM-DD-short-topic-name`\n   - Use today's date\n   - Create a short, URL-friendly slug from the topic (lowercase, hyphens, max 5 words)\n\n2. Create the folder structure:\n   ```\n   blog-posts/\n   └── YYYY-MM-DD-short-topic-name/\n       └── resources/\n   ```\n\n3. Confirm folder creation with user before proceeding.\n\n### Step 1: Research & Resource Collection\n\n1. Create `resources/` subfolder in the blog post directory\n\n2. For each provided resource:\n   - **URLs**: Fetch and save key information to `resources/` as markdown files\n   - **Files**: Read and summarize in `resources/`\n   - **Topics**: Use web search to gather up-to-date information\n\n3. For each resource, create a summary file in `resources/`:\n   - `resources/source-1-[short-name].md`\n   - `resources/source-2-[short-name].md`\n   - etc.\n\n4. Each summary should include:\n   ```markdown\n   # Source: [Title/URL]\n\n   ## Key Points\n   - Point 1\n   - Point 2\n\n   ## Relevant Quotes/Data\n   - Quote or statistic 1\n   - Quote or statistic 2\n\n   ## How This Relates to Topic\n   Brief explanation of relevance\n   ```\n\n5. Present research summary to user.\n\n### Step 2: Brainstorm & Clarify\n\n1. Based on the idea and researched resources, present:\n   - **Main themes** identified from research\n   - **Potential angles** for the blog post\n   - **Key points** that should be covered\n   - **Gaps** in information that need clarification\n\n2. Ask clarifying questions:\n   - What is the main takeaway you want readers to have?\n   - Are there specific points from the research you want to emphasize?\n   - What's the target length? (short: 500-800 words, medium: 1000-1500, long: 2000+)\n   - Any points you want to exclude?\n\n3. **Wait for user responses before proceeding.**\n\n### Step 3: Propose Outline\n\n1. Create a structured outline including:\n\n   ```markdown\n   # Blog Post Outline: [Title]\n\n   ## Meta Information\n   - **Target Audience**: [who]\n   - **Tone**: [style]\n   - **Target Length**: [word count]\n   - **Main Takeaway**: [key message]\n\n   ## Proposed Structure\n\n   ### Hook/Introduction\n   - Opening hook idea\n   - Context setting\n   - Thesis statement\n\n   ### Section 1: [Title]\n   - Key point A\n   - Key point B\n   - Supporting evidence from [source]\n\n   ### Section 2: [Title]\n   - Key point A\n   - Key point B\n\n   [Continue for all sections...]\n\n   ### Conclusion\n   - Summary of key points\n   - Call to action or final thought\n\n   ## Sources to Cite\n   - Source 1\n   - Source 2\n   ```\n\n2. Present outline to user and **ask for approval or modifications**.\n\n### Step 4: Save Approved Outline\n\n1. Once user approves the outline, save it to `OUTLINE.md` in the blog post folder.\n\n2. Confirm the outline has been saved.\n\n### Step 5: Commit Outline (if in git repo)\n\n1. Check if current directory is a git repository.\n\n2. If yes:\n   - Stage the new files: blog post folder, resources, and OUTLINE.md\n   - Create commit with message: `docs: Add outline for blog post - [topic-name]`\n   - Push to remote\n\n3. If not a git repo, skip this step and inform user.\n\n### Step 6: Write Draft\n\n1. Based on the approved outline, write the full blog post draft.\n\n2. Follow the structure from OUTLINE.md exactly.\n\n3. Include:\n   - Engaging introduction with hook\n   - Clear section headers\n   - Supporting evidence and examples from research\n   - Smooth transitions between sections\n   - Strong conclusion with takeaway\n   - **Citations**: All comparisons, statistics, data points, and factual claims MUST cite the original source\n\n4. Save the draft as `draft-v0.1.md` in the blog post folder.\n\n5. Format:\n   ```markdown\n   # [Blog Post Title]\n\n   *[Optional: subtitle or tagline]*\n\n   [Full content with inline citations...]\n\n   ---\n\n   ## References\n   - [1] Source 1 Title - URL or Citation\n   - [2] Source 2 Title - URL or Citation\n   - [3] Source 3 Title - URL or Citation\n   ```\n\n6. **Citation Requirements**:\n   - Every data point, statistic, or comparison MUST have an inline citation\n   - Use numbered references [1], [2], etc., or named citations [Source Name]\n   - Link citations to the References section at the end\n   - Example: \"Studies show that 65% of developers prefer TypeScript [1]\"\n   - Example: \"React outperforms Vue in rendering speed by 20% [React Benchmarks 2024]\"\n\n### Step 7: Commit Draft (if in git repo)\n\n1. Check if in git repository.\n\n2. If yes:\n   - Stage the draft file\n   - Create commit with message: `docs: Add draft v0.1 for blog post - [topic-name]`\n   - Push to remote\n\n3. If not a git repo, skip and inform user.\n\n### Step 8: Present Draft for Review\n\n1. Present the draft content to user.\n\n2. Ask for feedback:\n   - Overall impression?\n   - Sections that need expansion or reduction?\n   - Tone adjustments needed?\n   - Missing information?\n   - Specific edits or rewrites?\n\n3. **Wait for user response.**\n\n### Step 9: Iterate or Finalize\n\n**If user requests changes:**\n1. Note all requested modifications\n2. Return to Step 6 with the following adjustments:\n   - Increment version number (v0.2, v0.3, etc.)\n   - Incorporate all feedback\n   - Save as `draft-v[X.Y].md`\n   - Repeat Steps 7-8\n\n**If user approves:**\n1. Confirm the final draft version\n2. Optionally rename to `final.md` if user requests\n3. Summarize the blog post creation process:\n   - Total versions created\n   - Key changes between versions\n   - Final word count\n   - Files created\n\n## Version Tracking\n\nAll drafts are preserved with incremental versioning:\n- `draft-v0.1.md` - Initial draft\n- `draft-v0.2.md` - After first round of feedback\n- `draft-v0.3.md` - After second round of feedback\n- etc.\n\nThis allows tracking the evolution of the blog post and reverting if needed.\n\n## Output Files Structure\n\n```\nblog-posts/\n└── YYYY-MM-DD-topic-name/\n    ├── resources/\n    │   ├── source-1-name.md\n    │   ├── source-2-name.md\n    │   └── ...\n    ├── OUTLINE.md\n    ├── draft-v0.1.md\n    ├── draft-v0.2.md (if iterations)\n    └── draft-v0.3.md (if more iterations)\n```\n\n## Tips for Quality\n\n- **Hook**: Start with a question, surprising fact, or relatable scenario\n- **Flow**: Each paragraph should connect to the next\n- **Evidence**: Support claims with data from research\n- **Citations**: ALWAYS cite sources for:\n  - All statistics and data points (e.g., \"According to [Source], 75% of...\")\n  - Comparisons between products, services, or approaches (e.g., \"X performs 2x faster than Y [Source]\")\n  - Factual claims about market trends, research findings, or benchmarks\n  - Use inline citations with format: [Source Name] or [Author, Year]\n- **Voice**: Maintain consistent tone throughout\n- **Length**: Respect the target word count\n- **Readability**: Use short paragraphs, bullet points where appropriate\n- **CTA**: End with a clear call-to-action or thought-provoking question\n\n## Notes\n\n- Always wait for user approval at outlined checkpoints\n- Preserve all draft versions for history\n- Use web search for up-to-date information when URLs are provided\n- If resources are insufficient, ask user for more or suggest additional research\n- Adapt tone based on target audience (technical, general, business, etc.)\n"
  },
  {
    "path": "03-skills/blog-draft/templates/draft-template.md",
    "content": "# [Blog Post Title]\n\n*[Subtitle or tagline - optional]*\n\n**[Author Name]** | [Date]\n\n---\n\n[Opening hook - grab attention immediately]\n\n[Context and background - why this matters]\n\n[Thesis statement - what this post will cover]\n\n---\n\n## [Section 1 Title]\n\n[Section content with clear, engaging prose]\n\n[Include evidence, examples, or data to support points]\n\n> \"Relevant quote from research\" - Source\n\n[Transition to next section]\n\n---\n\n## [Section 2 Title]\n\n[Continue with main content]\n\n**Key takeaway:** [Highlight important points in bold or callout boxes]\n\n[More supporting content]\n\n---\n\n## [Section 3 Title]\n\n[Additional sections as needed]\n\n### Subsection (if needed)\n\n[Subsection content]\n\n---\n\n## Conclusion\n\n[Summarize the key points covered]\n\n[Reinforce the main takeaway]\n\n[Call to action or thought-provoking final statement]\n\n---\n\n## References\n\n1. [Source Title](#)\n2. [Source Title](#)\n3. [Source Title](#)\n\n---\n\n*[Optional: Author bio or related posts suggestion]*\n"
  },
  {
    "path": "03-skills/blog-draft/templates/outline-template.md",
    "content": "# Blog Post Outline: [Title]\n\n## Meta Information\n\n| Attribute | Value |\n|-----------|-------|\n| **Target Audience** | [Who is this for?] |\n| **Tone** | [Formal/Casual/Technical/Conversational] |\n| **Target Length** | [Word count range] |\n| **Main Takeaway** | [One sentence: what should readers remember?] |\n| **Keywords** | [SEO keywords if relevant] |\n\n---\n\n## Proposed Structure\n\n### 1. Introduction / Hook\n\n**Opening Hook Options:**\n- [ ] Question that resonates with reader\n- [ ] Surprising statistic or fact\n- [ ] Brief story or scenario\n- [ ] Bold statement\n\n**Context Setting:**\n- Background information needed\n- Why this topic matters now\n\n**Thesis Statement:**\n- Clear statement of what the post will cover\n\n---\n\n### 2. [Section Title]\n\n**Key Points:**\n- Point A: [description]\n- Point B: [description]\n\n**Supporting Evidence:**\n- From [source]: [relevant data/quote]\n\n**Transition to next section:**\n- [How this connects to what's next]\n\n---\n\n### 3. [Section Title]\n\n**Key Points:**\n- Point A: [description]\n- Point B: [description]\n\n**Supporting Evidence:**\n- From [source]: [relevant data/quote]\n\n**Transition to next section:**\n- [How this connects to what's next]\n\n---\n\n### 4. [Section Title] (add more sections as needed)\n\n**Key Points:**\n- Point A: [description]\n- Point B: [description]\n\n**Supporting Evidence:**\n- From [source]: [relevant data/quote]\n\n---\n\n### 5. Conclusion\n\n**Summary of Key Points:**\n- Recap point 1\n- Recap point 2\n- Recap point 3\n\n**Final Thought / Call to Action:**\n- [What should readers do or think about next?]\n\n---\n\n## Sources to Cite\n\n1. [Source Name](#) - Used for: [what information]\n2. [Source Name](#) - Used for: [what information]\n3. [Source Name](#) - Used for: [what information]\n\n---\n\n## Notes for Drafting\n\n- [Any specific requirements or constraints]\n- [Things to emphasize]\n- [Things to avoid]\n"
  },
  {
    "path": "03-skills/brand-voice/SKILL.md",
    "content": "---\nname: brand-voice-consistency\ndescription: Ensure all communication matches brand voice and tone guidelines. Use when creating marketing copy, customer communications, public-facing content, or when users mention brand voice, tone, or writing style.\n---\n\n# Brand Voice Skill\n\n## Overview\nThis skill ensures all communications maintain consistent brand voice, tone, and messaging.\n\n## Brand Identity\n\n### Mission\nHelp teams automate their development workflows with AI\n\n### Values\n- **Simplicity**: Make complex things simple\n- **Reliability**: Rock-solid execution\n- **Empowerment**: Enable human creativity\n\n### Tone of Voice\n- **Friendly but professional** - approachable without being casual\n- **Clear and concise** - avoid jargon, explain technical concepts simply\n- **Confident** - we know what we're doing\n- **Empathetic** - understand user needs and pain points\n\n## Writing Guidelines\n\n### Do's ✅\n- Use \"you\" when addressing readers\n- Use active voice: \"Claude generates reports\" not \"Reports are generated by Claude\"\n- Start with value proposition\n- Use concrete examples\n- Keep sentences under 20 words\n- Use lists for clarity\n- Include calls-to-action\n\n### Don'ts ❌\n- Don't use corporate jargon\n- Don't patronize or oversimplify\n- Don't use \"we believe\" or \"we think\"\n- Don't use ALL CAPS except for emphasis\n- Don't create walls of text\n- Don't assume technical knowledge\n\n## Vocabulary\n\n### ✅ Preferred Terms\n- Claude (not \"the Claude AI\")\n- Code generation (not \"auto-coding\")\n- Agent (not \"bot\")\n- Streamline (not \"revolutionize\")\n- Integrate (not \"synergize\")\n\n### ❌ Avoid Terms\n- \"Cutting-edge\" (overused)\n- \"Game-changer\" (vague)\n- \"Leverage\" (corporate-speak)\n- \"Utilize\" (use \"use\")\n- \"Paradigm shift\" (unclear)\n\n## Examples\n\n### ✅ Good Example\n\"Claude automates your code review process. Instead of manually checking each PR, Claude reviews security, performance, and quality—saving your team hours every week.\"\n\nWhy it works: Clear value, specific benefits, action-oriented\n\n### ❌ Bad Example\n\"Claude leverages cutting-edge AI to provide comprehensive software development solutions.\"\n\nWhy it doesn't work: Vague, corporate jargon, no specific value\n"
  },
  {
    "path": "03-skills/brand-voice/templates/email-template.txt",
    "content": "Subject: [Clear, benefit-driven subject]\n\nHi [Name],\n\n[Opening: What's the value for them]\n\n[Body: How it works / What they'll get]\n\n[Specific example or benefit]\n\n[Call to action: Clear next step]\n\nBest regards,\n[Name]\n"
  },
  {
    "path": "03-skills/brand-voice/templates/social-post-template.txt",
    "content": "[Hook: Grab attention in first line]\n[2-3 lines: Value or interesting fact]\n[Call to action: Link, question, or engagement]\n[Emoji: 1-2 max for visual interest]\n"
  },
  {
    "path": "03-skills/brand-voice/tone-examples.md",
    "content": "# Brand Voice Tone Examples\n\n## Exciting Announcement\n\"Save 8 hours per week on code reviews. Claude reviews your PRs automatically.\"\n\n## Empathetic Support\n\"We know deployments can be stressful. Claude handles testing so you don't have to worry.\"\n\n## Confident Product Feature\n\"Claude doesn't just suggest code. It understands your architecture and maintains consistency.\"\n\n## Educational Blog Post\n\"Let's explore how agents improve code review workflows. Here's what we learned...\"\n"
  },
  {
    "path": "03-skills/claude-md/SKILL.md",
    "content": "---\nname: claude-md\ndescription: Create or update CLAUDE.md files following best practices for optimal AI agent onboarding\n---\n\n## User Input\n\n```text\n$ARGUMENTS\n```\n\nYou **MUST** consider the user input before proceeding (if not empty). User may specify:\n- `create` - Create new CLAUDE.md from scratch\n- `update` - Improve existing CLAUDE.md\n- `audit` - Analyze and report on current CLAUDE.md quality\n- A specific path to create/update (e.g., `src/api/CLAUDE.md` for directory-specific instructions)\n\n## Core Principles\n\n**LLMs are stateless**: CLAUDE.md is the only file automatically included in every conversation. It serves as the primary onboarding document for AI agents into your codebase.\n\n### The Golden Rules\n\n1. **Less is More**: Frontier LLMs can follow ~150-200 instructions. Claude Code's system prompt already uses ~50. Keep your CLAUDE.md focused and concise.\n\n2. **Universal Applicability**: Only include information relevant to EVERY session. Task-specific instructions belong in separate files.\n\n3. **Don't Use Claude as a Linter**: Style guidelines bloat context and degrade instruction-following. Use deterministic tools (prettier, eslint, etc.) instead.\n\n4. **Never Auto-Generate**: CLAUDE.md is the highest leverage point of the AI harness. Craft it manually with careful consideration.\n\n## Execution Flow\n\n### 1. Project Analysis\n\nFirst, analyze the current project state:\n\n1. Check for existing CLAUDE.md files:\n   - Root level: `./CLAUDE.md` or `.claude/CLAUDE.md`\n   - Directory-specific: `**/CLAUDE.md`\n   - Global user config: `~/.claude/CLAUDE.md`\n\n2. Identify the project structure:\n   - Technology stack (languages, frameworks)\n   - Project type (monorepo, single app, library)\n   - Development tools (package manager, build system, test runner)\n\n3. Review existing documentation:\n   - README.md\n   - CONTRIBUTING.md\n   - package.json, pyproject.toml, Cargo.toml, etc.\n\n### 2. Content Strategy (WHAT, WHY, HOW)\n\nStructure CLAUDE.md around three dimensions:\n\n#### WHAT - Technology & Structure\n- Technology stack overview\n- Project organization (especially important for monorepos)\n- Key directories and their purposes\n\n#### WHY - Purpose & Context\n- What the project does\n- Why certain architectural decisions were made\n- What each major component is responsible for\n\n#### HOW - Workflow & Conventions\n- Development workflow (bun vs node, pip vs uv, etc.)\n- Testing procedures and commands\n- Verification and build methods\n- Critical \"gotchas\" or non-obvious requirements\n\n### 3. Progressive Disclosure Strategy\n\nFor larger projects, recommend creating an `agent_docs/` folder:\n\n```\nagent_docs/\n  |- building_the_project.md\n  |- running_tests.md\n  |- code_conventions.md\n  |- architecture_decisions.md\n```\n\nIn CLAUDE.md, reference these files with instructions like:\n```markdown\nFor detailed build instructions, refer to `agent_docs/building_the_project.md`\n```\n\n**Important**: Use `file:line` references instead of code snippets to avoid outdated context.\n\n### 4. Quality Constraints\n\nWhen creating or updating CLAUDE.md:\n\n1. **Target Length**: Under 300 lines (ideally under 100)\n2. **No Style Rules**: Remove any linting/formatting instructions\n3. **No Task-Specific Instructions**: Move to separate files\n4. **No Code Snippets**: Use file references instead\n5. **No Redundant Information**: Don't repeat what's in package.json or README\n\n### 5. Essential Sections\n\nA well-structured CLAUDE.md should include:\n\n```markdown\n# Project Name\n\nBrief one-line description.\n\n## Tech Stack\n- Primary language and version\n- Key frameworks/libraries\n- Database/storage (if any)\n\n## Project Structure\n[Only for monorepos or complex structures]\n- `apps/` - Application entry points\n- `packages/` - Shared libraries\n\n## Development Commands\n- Install: `command`\n- Test: `command`\n- Build: `command`\n\n## Critical Conventions\n[Only non-obvious, high-impact conventions]\n- Convention 1 with brief explanation\n- Convention 2 with brief explanation\n\n## Known Issues / Gotchas\n[Things that consistently trip up developers]\n- Issue 1\n- Issue 2\n```\n\n### 6. Anti-Patterns to Avoid\n\n**DO NOT include:**\n- Code style guidelines (use linters)\n- Documentation on how to use Claude\n- Long explanations of obvious patterns\n- Copy-pasted code examples\n- Generic best practices (\"write clean code\")\n- Instructions for specific tasks\n- Auto-generated content\n- Extensive TODO lists\n\n### 7. Validation Checklist\n\nBefore finalizing, verify:\n\n- [ ] Under 300 lines (preferably under 100)\n- [ ] Every line applies to ALL sessions\n- [ ] No style/formatting rules\n- [ ] No code snippets (use file references)\n- [ ] Commands are verified to work\n- [ ] Progressive disclosure used for complex projects\n- [ ] Critical gotchas are documented\n- [ ] No redundancy with README.md\n\n## Output Format\n\n### For `create` or default:\n\n1. Analyze the project\n2. Draft a CLAUDE.md following the structure above\n3. Present the draft for review\n4. Write to the appropriate location after approval\n\n### For `update`:\n\n1. Read existing CLAUDE.md\n2. Audit against best practices\n3. Identify:\n   - Content to remove (style rules, code snippets, task-specific)\n   - Content to condense\n   - Missing essential information\n4. Present changes for review\n5. Apply changes after approval\n\n### For `audit`:\n\n1. Read existing CLAUDE.md\n2. Generate a report with:\n   - Current line count vs target\n   - Percentage of universally-applicable content\n   - List of anti-patterns found\n   - Recommendations for improvement\n3. Do NOT modify the file, only report\n\n## AGENTS.md Handling\n\nIf the user requests AGENTS.md creation/update:\n\nAGENTS.md is used for defining specialized agent behaviors. Unlike CLAUDE.md (which is for project context), AGENTS.md defines:\n- Custom agent roles and capabilities\n- Agent-specific instructions and constraints\n- Workflow definitions for multi-agent scenarios\n\nApply similar principles:\n- Keep focused and concise\n- Use progressive disclosure\n- Reference external docs instead of embedding content\n\n## Notes\n\n- Always verify commands work before including them\n- When in doubt, leave it out - less is more\n- The system reminder tells Claude that CLAUDE.md \"may or may not be relevant\" - the more noise, the more it gets ignored\n- Monorepos benefit most from clear WHAT/WHY/HOW structure\n- Directory-specific CLAUDE.md files should be even more focused\n"
  },
  {
    "path": "03-skills/code-review/SKILL.md",
    "content": "---\nname: code-review-specialist\ndescription: Comprehensive code review with security, performance, and quality analysis. Use when users ask to review code, analyze code quality, evaluate pull requests, or mention code review, security analysis, or performance optimization.\n---\n\n# Code Review Skill\n\nThis skill provides comprehensive code review capabilities focusing on:\n\n1. **Security Analysis**\n   - Authentication/authorization issues\n   - Data exposure risks\n   - Injection vulnerabilities\n   - Cryptographic weaknesses\n   - Sensitive data logging\n\n2. **Performance Review**\n   - Algorithm efficiency (Big O analysis)\n   - Memory optimization\n   - Database query optimization\n   - Caching opportunities\n   - Concurrency issues\n\n3. **Code Quality**\n   - SOLID principles\n   - Design patterns\n   - Naming conventions\n   - Documentation\n   - Test coverage\n\n4. **Maintainability**\n   - Code readability\n   - Function size (should be < 50 lines)\n   - Cyclomatic complexity\n   - Dependency management\n   - Type safety\n\n## Review Template\n\nFor each piece of code reviewed, provide:\n\n### Summary\n- Overall quality assessment (1-5)\n- Key findings count\n- Recommended priority areas\n\n### Critical Issues (if any)\n- **Issue**: Clear description\n- **Location**: File and line number\n- **Impact**: Why this matters\n- **Severity**: Critical/High/Medium\n- **Fix**: Code example\n\n### Findings by Category\n\n#### Security (if issues found)\nList security vulnerabilities with examples\n\n#### Performance (if issues found)\nList performance problems with complexity analysis\n\n#### Quality (if issues found)\nList code quality issues with refactoring suggestions\n\n#### Maintainability (if issues found)\nList maintainability problems with improvements\n\n## Version History\n\n- v1.0.0 (2024-12-10): Initial release with security, performance, quality, and maintainability analysis\n"
  },
  {
    "path": "03-skills/code-review/scripts/analyze-metrics.py",
    "content": "#!/usr/bin/env python3\nimport re\nimport sys\n\n\ndef analyze_code_metrics(code):\n    \"\"\"Analyze code for common metrics.\"\"\"\n\n    # Count functions\n    functions = len(re.findall(r\"^def\\s+\\w+\", code, re.MULTILINE))\n\n    # Count classes\n    classes = len(re.findall(r\"^class\\s+\\w+\", code, re.MULTILINE))\n\n    # Average line length\n    lines = code.split(\"\\n\")\n    avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0\n\n    # Estimate complexity\n    complexity = len(re.findall(r\"\\b(if|elif|else|for|while|and|or)\\b\", code))\n\n    return {\n        \"functions\": functions,\n        \"classes\": classes,\n        \"avg_line_length\": avg_length,\n        \"complexity_score\": complexity,\n    }\n\n\nif __name__ == \"__main__\":\n    with open(sys.argv[1]) as f:\n        code = f.read()\n    metrics = analyze_code_metrics(code)\n    for key, value in metrics.items():\n        print(f\"{key}: {value:.2f}\")\n"
  },
  {
    "path": "03-skills/code-review/scripts/compare-complexity.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nCompare cyclomatic complexity of code before and after changes.\nHelps identify if refactoring actually simplifies code structure.\n\"\"\"\n\nimport re\nimport sys\n\n\nclass ComplexityAnalyzer:\n    \"\"\"Analyze code complexity metrics.\"\"\"\n\n    def __init__(self, code: str):\n        self.code = code\n        self.lines = code.split(\"\\n\")\n\n    def calculate_cyclomatic_complexity(self) -> int:\n        \"\"\"\n        Calculate cyclomatic complexity using McCabe's method.\n        Count decision points: if, elif, else, for, while, except, and, or\n        \"\"\"\n        complexity = 1  # Base complexity\n\n        # Count decision points\n        decision_patterns = [\n            r\"\\bif\\b\",\n            r\"\\belif\\b\",\n            r\"\\bfor\\b\",\n            r\"\\bwhile\\b\",\n            r\"\\bexcept\\b\",\n            r\"\\band\\b(?!$)\",\n            r\"\\bor\\b(?!$)\",\n        ]\n\n        for pattern in decision_patterns:\n            matches = re.findall(pattern, self.code)\n            complexity += len(matches)\n\n        return complexity\n\n    def calculate_cognitive_complexity(self) -> int:\n        \"\"\"\n        Calculate cognitive complexity - how hard is it to understand?\n        Based on nesting depth and control flow.\n        \"\"\"\n        cognitive = 0\n        nesting_depth = 0\n\n        for line in self.lines:\n            # Track nesting depth\n            if re.search(r\"^\\s*(if|for|while|def|class|try)\\b\", line):\n                nesting_depth += 1\n                cognitive += nesting_depth\n            elif re.search(r\"^\\s*(elif|else|except|finally)\\b\", line):\n                cognitive += nesting_depth\n\n            # Reduce nesting when unindenting\n            if line and not line[0].isspace():\n                nesting_depth = 0\n\n        return cognitive\n\n    def calculate_maintainability_index(self) -> float:\n        \"\"\"\n        Maintainability Index ranges from 0-100.\n        > 85: Excellent\n        > 65: Good\n        > 50: Fair\n        < 50: Poor\n        \"\"\"\n        lines = len(self.lines)\n        cyclomatic = self.calculate_cyclomatic_complexity()\n        cognitive = self.calculate_cognitive_complexity()\n\n        # Simplified MI calculation\n        mi = (\n            171\n            - 5.2 * (cyclomatic / lines)\n            - 0.23 * (cognitive)\n            - 16.2 * (lines / 1000)\n        )\n\n        return max(0, min(100, mi))\n\n    def get_complexity_report(self) -> dict:\n        \"\"\"Generate comprehensive complexity report.\"\"\"\n        return {\n            \"cyclomatic_complexity\": self.calculate_cyclomatic_complexity(),\n            \"cognitive_complexity\": self.calculate_cognitive_complexity(),\n            \"maintainability_index\": round(self.calculate_maintainability_index(), 2),\n            \"lines_of_code\": len(self.lines),\n            \"avg_line_length\": round(\n                sum(len(l) for l in self.lines) / len(self.lines), 2\n            )\n            if self.lines\n            else 0,\n        }\n\n\ndef compare_files(before_file: str, after_file: str) -> None:\n    \"\"\"Compare complexity metrics between two code versions.\"\"\"\n\n    with open(before_file) as f:\n        before_code = f.read()\n\n    with open(after_file) as f:\n        after_code = f.read()\n\n    before_analyzer = ComplexityAnalyzer(before_code)\n    after_analyzer = ComplexityAnalyzer(after_code)\n\n    before_metrics = before_analyzer.get_complexity_report()\n    after_metrics = after_analyzer.get_complexity_report()\n\n    print(\"=\" * 60)\n    print(\"CODE COMPLEXITY COMPARISON\")\n    print(\"=\" * 60)\n\n    print(\"\\nBEFORE:\")\n    print(f\"  Cyclomatic Complexity:    {before_metrics['cyclomatic_complexity']}\")\n    print(f\"  Cognitive Complexity:     {before_metrics['cognitive_complexity']}\")\n    print(f\"  Maintainability Index:    {before_metrics['maintainability_index']}\")\n    print(f\"  Lines of Code:            {before_metrics['lines_of_code']}\")\n    print(f\"  Avg Line Length:          {before_metrics['avg_line_length']}\")\n\n    print(\"\\nAFTER:\")\n    print(f\"  Cyclomatic Complexity:    {after_metrics['cyclomatic_complexity']}\")\n    print(f\"  Cognitive Complexity:     {after_metrics['cognitive_complexity']}\")\n    print(f\"  Maintainability Index:    {after_metrics['maintainability_index']}\")\n    print(f\"  Lines of Code:            {after_metrics['lines_of_code']}\")\n    print(f\"  Avg Line Length:          {after_metrics['avg_line_length']}\")\n\n    print(\"\\nCHANGES:\")\n    cyclomatic_change = (\n        after_metrics[\"cyclomatic_complexity\"] - before_metrics[\"cyclomatic_complexity\"]\n    )\n    cognitive_change = (\n        after_metrics[\"cognitive_complexity\"] - before_metrics[\"cognitive_complexity\"]\n    )\n    mi_change = (\n        after_metrics[\"maintainability_index\"] - before_metrics[\"maintainability_index\"]\n    )\n    loc_change = after_metrics[\"lines_of_code\"] - before_metrics[\"lines_of_code\"]\n\n    print(f\"  Cyclomatic Complexity:    {cyclomatic_change:+d}\")\n    print(f\"  Cognitive Complexity:     {cognitive_change:+d}\")\n    print(f\"  Maintainability Index:    {mi_change:+.2f}\")\n    print(f\"  Lines of Code:            {loc_change:+d}\")\n\n    print(\"\\nASSESSMENT:\")\n    if mi_change > 0:\n        print(\"  ✅ Code is MORE maintainable\")\n    elif mi_change < 0:\n        print(\"  ⚠️  Code is LESS maintainable\")\n    else:\n        print(\"  ➡️  Maintainability unchanged\")\n\n    if cyclomatic_change < 0:\n        print(\"  ✅ Complexity DECREASED\")\n    elif cyclomatic_change > 0:\n        print(\"  ⚠️  Complexity INCREASED\")\n    else:\n        print(\"  ➡️  Complexity unchanged\")\n\n    print(\"=\" * 60)\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 3:\n        print(\"Usage: python compare-complexity.py <before_file> <after_file>\")\n        sys.exit(1)\n\n    compare_files(sys.argv[1], sys.argv[2])\n"
  },
  {
    "path": "03-skills/code-review/templates/finding-template.md",
    "content": "# Code Review Finding Template\n\nUse this template when documenting each issue found during code review.\n\n---\n\n## Issue: [TITLE]\n\n### Severity\n- [ ] Critical (blocks deployment)\n- [ ] High (should fix before merge)\n- [ ] Medium (should fix soon)\n- [ ] Low (nice to have)\n\n### Category\n- [ ] Security\n- [ ] Performance\n- [ ] Code Quality\n- [ ] Maintainability\n- [ ] Testing\n- [ ] Design Pattern\n- [ ] Documentation\n\n### Location\n**File:** `src/components/UserCard.tsx`\n\n**Lines:** 45-52\n\n**Function/Method:** `renderUserDetails()`\n\n### Issue Description\n\n**What:** Describe what the issue is.\n\n**Why it matters:** Explain the impact and why this needs to be fixed.\n\n**Current behavior:** Show the problematic code or behavior.\n\n**Expected behavior:** Describe what should happen instead.\n\n### Code Example\n\n#### Current (Problematic)\n\n```typescript\n// Shows the N+1 query problem\nconst users = fetchUsers();\nusers.forEach(user => {\n  const posts = fetchUserPosts(user.id); // Query per user!\n  renderUserPosts(posts);\n});\n```\n\n#### Suggested Fix\n\n```typescript\n// Optimized with JOIN query\nconst usersWithPosts = fetchUsersWithPosts();\nusersWithPosts.forEach(({ user, posts }) => {\n  renderUserPosts(posts);\n});\n```\n\n### Impact Analysis\n\n| Aspect | Impact | Severity |\n|--------|--------|----------|\n| Performance | 100+ queries for 20 users | High |\n| User Experience | Slow page load | High |\n| Scalability | Breaks at scale | Critical |\n| Maintainability | Hard to debug | Medium |\n\n### Related Issues\n\n- Similar issue in `AdminUserList.tsx` line 120\n- Related PR: #456\n- Related issue: #789\n\n### Additional Resources\n\n- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem)\n- [Database Join Documentation](https://docs.example.com/joins)\n- [Performance Optimization Guide](./docs/performance.md)\n\n### Reviewer Notes\n\n- This is a common pattern in this codebase\n- Consider adding this to the code style guide\n- Might be worth creating a helper function\n\n### Author Response (for feedback)\n\n*To be filled by the code author:*\n\n- [ ] Fix implemented in commit: `abc123`\n- [ ] Fix status: Complete / In Progress / Needs Discussion\n- [ ] Questions or concerns: (describe)\n\n---\n\n## Finding Statistics (for Reviewer)\n\nWhen reviewing multiple findings, track:\n\n- **Total Issues Found:** X\n- **Critical:** X\n- **High:** X\n- **Medium:** X\n- **Low:** X\n\n**Recommendation:** ✅ Approve / ⚠️ Request Changes / 🔄 Needs Discussion\n\n**Overall Code Quality:** 1-5 stars\n"
  },
  {
    "path": "03-skills/code-review/templates/review-checklist.md",
    "content": "# Code Review Checklist\n\n## Security Checklist\n- [ ] No hardcoded credentials or secrets\n- [ ] Input validation on all user inputs\n- [ ] SQL injection prevention (parameterized queries)\n- [ ] CSRF protection on state-changing operations\n- [ ] XSS prevention with proper escaping\n- [ ] Authentication checks on protected endpoints\n- [ ] Authorization checks on resources\n- [ ] Secure password hashing (bcrypt, argon2)\n- [ ] No sensitive data in logs\n- [ ] HTTPS enforced\n\n## Performance Checklist\n- [ ] No N+1 queries\n- [ ] Appropriate use of indexes\n- [ ] Caching implemented where beneficial\n- [ ] No blocking operations on main thread\n- [ ] Async/await used correctly\n- [ ] Large datasets paginated\n- [ ] Database connections pooled\n- [ ] Regular expressions optimized\n- [ ] No unnecessary object creation\n- [ ] Memory leaks prevented\n\n## Quality Checklist\n- [ ] Functions < 50 lines\n- [ ] Clear variable naming\n- [ ] No duplicate code\n- [ ] Proper error handling\n- [ ] Comments explain WHY, not WHAT\n- [ ] No console.logs in production\n- [ ] Type checking (TypeScript/JSDoc)\n- [ ] SOLID principles followed\n- [ ] Design patterns applied correctly\n- [ ] Self-documenting code\n\n## Testing Checklist\n- [ ] Unit tests written\n- [ ] Edge cases covered\n- [ ] Error scenarios tested\n- [ ] Integration tests present\n- [ ] Coverage > 80%\n- [ ] No flaky tests\n- [ ] Mock external dependencies\n- [ ] Clear test names\n"
  },
  {
    "path": "03-skills/doc-generator/SKILL.md",
    "content": "---\nname: api-documentation-generator\ndescription: Generate comprehensive, accurate API documentation from source code. Use when creating or updating API documentation, generating OpenAPI specs, or when users mention API docs, endpoints, or documentation.\n---\n\n# API Documentation Generator Skill\n\n## Generates\n\n- OpenAPI/Swagger specifications\n- API endpoint documentation\n- SDK usage examples\n- Integration guides\n- Error code references\n- Authentication guides\n\n## Documentation Structure\n\n### For Each Endpoint\n\n```markdown\n## GET /api/v1/users/:id\n\n### Description\nBrief explanation of what this endpoint does\n\n### Parameters\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| id | string | Yes | User ID |\n\n### Response\n\n**200 Success**\n```json\n{\n  \"id\": \"usr_123\",\n  \"name\": \"John Doe\",\n  \"email\": \"john@example.com\",\n  \"created_at\": \"2025-01-15T10:30:00Z\"\n}\n```\n\n**404 Not Found**\n```json\n{\n  \"error\": \"USER_NOT_FOUND\",\n  \"message\": \"User does not exist\"\n}\n```\n\n### Examples\n\n**cURL**\n```bash\ncurl -X GET \"https://api.example.com/api/v1/users/usr_123\" \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\n**JavaScript**\n```javascript\nconst user = await fetch('/api/v1/users/usr_123', {\n  headers: { 'Authorization': 'Bearer token' }\n}).then(r => r.json());\n```\n\n**Python**\n```python\nresponse = requests.get(\n    'https://api.example.com/api/v1/users/usr_123',\n    headers={'Authorization': 'Bearer token'}\n)\nuser = response.json()\n```\n```\n"
  },
  {
    "path": "03-skills/doc-generator/generate-docs.py",
    "content": "#!/usr/bin/env python3\nimport ast\n\n\nclass APIDocExtractor(ast.NodeVisitor):\n    \"\"\"Extract API documentation from Python source code.\"\"\"\n\n    def __init__(self):\n        self.endpoints = []\n\n    def visit_FunctionDef(self, node):\n        \"\"\"Extract function documentation.\"\"\"\n        if node.name.startswith(\"get_\") or node.name.startswith(\"post_\"):\n            doc = ast.get_docstring(node)\n            endpoint = {\n                \"name\": node.name,\n                \"docstring\": doc,\n                \"params\": [arg.arg for arg in node.args.args],\n                \"returns\": self._extract_return_type(node),\n            }\n            self.endpoints.append(endpoint)\n        self.generic_visit(node)\n\n    def _extract_return_type(self, node):\n        \"\"\"Extract return type from function annotation.\"\"\"\n        if node.returns:\n            return ast.unparse(node.returns)\n        return \"Any\"\n\n\ndef generate_markdown_docs(endpoints: list[dict]) -> str:\n    \"\"\"Generate markdown documentation from endpoints.\"\"\"\n    docs = \"# API Documentation\\n\\n\"\n\n    for endpoint in endpoints:\n        docs += f\"## {endpoint['name']}\\n\\n\"\n        docs += f\"{endpoint['docstring']}\\n\\n\"\n        docs += f\"**Parameters**: {', '.join(endpoint['params'])}\\n\\n\"\n        docs += f\"**Returns**: {endpoint['returns']}\\n\\n\"\n        docs += \"---\\n\\n\"\n\n    return docs\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    with open(sys.argv[1]) as f:\n        tree = ast.parse(f.read())\n\n    extractor = APIDocExtractor()\n    extractor.visit(tree)\n\n    markdown = generate_markdown_docs(extractor.endpoints)\n    print(markdown)\n"
  },
  {
    "path": "03-skills/refactor/SKILL.md",
    "content": "---\nname: code-refactor\ndescription: Systematic code refactoring based on Martin Fowler's methodology. Use when users ask to refactor code, improve code structure, reduce technical debt, clean up legacy code, eliminate code smells, or improve code maintainability. This skill guides through a phased approach with research, planning, and safe incremental implementation.\n---\n\n# Code Refactoring Skill\n\nA systematic approach to refactoring code based on Martin Fowler's *Refactoring: Improving the Design of Existing Code* (2nd Edition). This skill emphasizes safe, incremental changes backed by tests.\n\n> \"Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.\" — Martin Fowler\n\n## Core Principles\n\n1. **Behavior Preservation**: External behavior must remain unchanged\n2. **Small Steps**: Make tiny, testable changes\n3. **Test-Driven**: Tests are the safety net\n4. **Continuous**: Refactoring is ongoing, not a one-time event\n5. **Collaborative**: User approval required at each phase\n\n## Workflow Overview\n\n```\nPhase 1: Research & Analysis\n    ↓\nPhase 2: Test Coverage Assessment\n    ↓\nPhase 3: Code Smell Identification\n    ↓\nPhase 4: Refactoring Plan Creation\n    ↓\nPhase 5: Incremental Implementation\n    ↓\nPhase 6: Review & Iteration\n```\n\n---\n\n## Phase 1: Research & Analysis\n\n### Objectives\n- Understand the codebase structure and purpose\n- Identify the scope of refactoring\n- Gather context about business requirements\n\n### Questions to Ask User\nBefore starting, clarify:\n\n1. **Scope**: Which files/modules/functions need refactoring?\n2. **Goals**: What problems are you trying to solve? (readability, performance, maintainability)\n3. **Constraints**: Are there any areas that should NOT be changed?\n4. **Timeline pressure**: Is this blocking other work?\n5. **Test status**: Do tests exist? Are they passing?\n\n### Actions\n- [ ] Read and understand the target code\n- [ ] Identify dependencies and integrations\n- [ ] Document current architecture\n- [ ] Note any existing technical debt markers (TODOs, FIXMEs)\n\n### Output\nPresent findings to user:\n- Code structure summary\n- Identified problem areas\n- Initial recommendations\n- **Request approval to proceed**\n\n---\n\n## Phase 2: Test Coverage Assessment\n\n### Why Tests Matter\n> \"Refactoring without tests is like driving without a seatbelt.\" — Martin Fowler\n\nTests are the **key enabler** of safe refactoring. Without them, you risk introducing bugs.\n\n### Assessment Steps\n\n1. **Check for existing tests**\n   ```bash\n   # Look for test files\n   find . -name \"*test*\" -o -name \"*spec*\" | head -20\n   ```\n\n2. **Run existing tests**\n   ```bash\n   # JavaScript/TypeScript\n   npm test\n\n   # Python\n   pytest -v\n\n   # Java\n   mvn test\n   ```\n\n3. **Check coverage (if available)**\n   ```bash\n   # JavaScript\n   npm run test:coverage\n\n   # Python\n   pytest --cov=.\n   ```\n\n### Decision Point: Ask User\n\n**If tests exist and pass:**\n- Proceed to Phase 3\n\n**If tests are missing or incomplete:**\nPresent options:\n1. Write tests first (recommended)\n2. Add tests incrementally during refactoring\n3. Proceed without tests (risky - requires user acknowledgment)\n\n**If tests are failing:**\n- STOP. Fix failing tests before refactoring\n- Ask user: Should we fix tests first?\n\n### Test Writing Guidelines (if needed)\n\nFor each function being refactored, ensure tests cover:\n- Happy path (normal operation)\n- Edge cases (empty inputs, null, boundaries)\n- Error scenarios (invalid inputs, exceptions)\n\nUse the \"red-green-refactor\" cycle:\n1. Write failing test (red)\n2. Make it pass (green)\n3. Refactor\n\n---\n\n## Phase 3: Code Smell Identification\n\n### What Are Code Smells?\nSymptoms of deeper problems in code. They're not bugs, but indicators that the code could be improved.\n\n### Common Code Smells to Check\n\nSee [references/code-smells.md](references/code-smells.md) for the complete catalog.\n\n#### Quick Reference\n\n| Smell | Signs | Impact |\n|-------|-------|--------|\n| **Long Method** | Methods > 30-50 lines | Hard to understand, test, maintain |\n| **Duplicated Code** | Same logic in multiple places | Bug fixes needed in multiple places |\n| **Large Class** | Class with too many responsibilities | Violates Single Responsibility |\n| **Feature Envy** | Method uses another class's data more | Poor encapsulation |\n| **Primitive Obsession** | Overuse of primitives instead of objects | Missing domain concepts |\n| **Long Parameter List** | Methods with 4+ parameters | Hard to call correctly |\n| **Data Clumps** | Same data items appearing together | Missing abstraction |\n| **Switch Statements** | Complex switch/if-else chains | Hard to extend |\n| **Speculative Generality** | Code \"just in case\" | Unnecessary complexity |\n| **Dead Code** | Unused code | Confusion, maintenance burden |\n\n### Analysis Steps\n\n1. **Automated Analysis** (if scripts available)\n   ```bash\n   python scripts/detect-smells.py <file>\n   ```\n\n2. **Manual Review**\n   - Walk through code systematically\n   - Note each smell with location and severity\n   - Categorize by impact (Critical/High/Medium/Low)\n\n3. **Prioritization**\n   Focus on smells that:\n   - Block current development\n   - Cause bugs or confusion\n   - Affect most-changed code paths\n\n### Output: Smell Report\n\nPresent to user:\n- List of identified smells with locations\n- Severity assessment for each\n- Recommended priority order\n- **Request approval on priorities**\n\n---\n\n## Phase 4: Refactoring Plan Creation\n\n### Selecting Refactorings\n\nFor each smell, select an appropriate refactoring from the catalog.\n\nSee [references/refactoring-catalog.md](references/refactoring-catalog.md) for the complete list.\n\n#### Smell-to-Refactoring Mapping\n\n| Code Smell | Recommended Refactoring(s) |\n|------------|---------------------------|\n| Long Method | Extract Method, Replace Temp with Query |\n| Duplicated Code | Extract Method, Pull Up Method, Form Template Method |\n| Large Class | Extract Class, Extract Subclass |\n| Feature Envy | Move Method, Move Field |\n| Primitive Obsession | Replace Primitive with Object, Replace Type Code with Class |\n| Long Parameter List | Introduce Parameter Object, Preserve Whole Object |\n| Data Clumps | Extract Class, Introduce Parameter Object |\n| Switch Statements | Replace Conditional with Polymorphism |\n| Speculative Generality | Collapse Hierarchy, Inline Class, Remove Dead Code |\n| Dead Code | Remove Dead Code |\n\n### Plan Structure\n\nUse the template at [templates/refactoring-plan.md](templates/refactoring-plan.md).\n\nFor each refactoring:\n1. **Target**: What code will change\n2. **Smell**: What problem it addresses\n3. **Refactoring**: Which technique to apply\n4. **Steps**: Detailed micro-steps\n5. **Risks**: What could go wrong\n6. **Rollback**: How to undo if needed\n\n### Phased Approach\n\n**CRITICAL**: Introduce refactoring gradually in phases.\n\n**Phase A: Quick Wins** (Low risk, high value)\n- Rename variables for clarity\n- Extract obvious duplicate code\n- Remove dead code\n\n**Phase B: Structural Improvements** (Medium risk)\n- Extract methods from long functions\n- Introduce parameter objects\n- Move methods to appropriate classes\n\n**Phase C: Architectural Changes** (Higher risk)\n- Replace conditionals with polymorphism\n- Extract classes\n- Introduce design patterns\n\n### Decision Point: Present Plan to User\n\nBefore implementation:\n- Show complete refactoring plan\n- Explain each phase and its risks\n- Get explicit approval for each phase\n- **Ask**: \"Should I proceed with Phase A?\"\n\n---\n\n## Phase 5: Incremental Implementation\n\n### The Golden Rule\n> \"Change → Test → Green? → Commit → Next step\"\n\n### Implementation Rhythm\n\nFor each refactoring step:\n\n1. **Pre-check**\n   - Tests are passing (green)\n   - Code compiles\n\n2. **Make ONE small change**\n   - Follow the mechanics from the catalog\n   - Keep changes minimal\n\n3. **Verify**\n   - Run tests immediately\n   - Check for compilation errors\n\n4. **If tests pass (green)**\n   - Commit with descriptive message\n   - Move to next step\n\n5. **If tests fail (red)**\n   - STOP immediately\n   - Undo the change\n   - Analyze what went wrong\n   - Ask user if unclear\n\n### Commit Strategy\n\nEach commit should be:\n- **Atomic**: One logical change\n- **Reversible**: Easy to revert\n- **Descriptive**: Clear commit message\n\nExample commit messages:\n```\nrefactor: Extract calculateTotal() from processOrder()\nrefactor: Rename 'x' to 'customerCount' for clarity\nrefactor: Remove unused validateOldFormat() method\n```\n\n### Progress Reporting\n\nAfter each sub-phase, report to user:\n- Changes made\n- Tests still passing?\n- Any issues encountered\n- **Ask**: \"Continue with next batch?\"\n\n---\n\n## Phase 6: Review & Iteration\n\n### Post-Refactoring Checklist\n\n- [ ] All tests passing\n- [ ] No new warnings/errors\n- [ ] Code compiles successfully\n- [ ] Behavior unchanged (manual verification)\n- [ ] Documentation updated if needed\n- [ ] Commit history is clean\n\n### Metrics Comparison\n\nRun complexity analysis before and after:\n```bash\npython scripts/analyze-complexity.py <file>\n```\n\nPresent improvements:\n- Lines of code change\n- Cyclomatic complexity change\n- Maintainability index change\n\n### User Review\n\nPresent final results:\n- Summary of all changes\n- Before/after code comparison\n- Metrics improvements\n- Remaining technical debt\n- **Ask**: \"Are you satisfied with these changes?\"\n\n### Next Steps\n\nDiscuss with user:\n- Additional smells to address?\n- Schedule follow-up refactoring?\n- Apply similar changes elsewhere?\n\n---\n\n## Important Guidelines\n\n### When to STOP and Ask\n\nAlways pause and consult user when:\n- Unsure about business logic\n- Change might affect external APIs\n- Test coverage is inadequate\n- Significant architectural decision needed\n- Risk level increases\n- You encounter unexpected complexity\n\n### Safety Rules\n\n1. **Never refactor without tests** (unless user explicitly acknowledges risk)\n2. **Never make big changes** - break into tiny steps\n3. **Never skip the test run** after each change\n4. **Never continue if tests fail** - fix or rollback first\n5. **Never assume** - when in doubt, ask\n\n### What NOT to Do\n\n- Don't combine refactoring with feature additions\n- Don't refactor during production emergencies\n- Don't refactor code you don't understand\n- Don't over-engineer - keep it simple\n- Don't refactor everything at once\n\n---\n\n## Quick Start Example\n\n### Scenario: Long Method with Duplication\n\n**Before:**\n```javascript\nfunction processOrder(order) {\n  // 150 lines of code with:\n  // - Duplicated validation logic\n  // - Inline calculations\n  // - Mixed responsibilities\n}\n```\n\n**Refactoring Steps:**\n\n1. **Ensure tests exist** for processOrder()\n2. **Extract** validation into validateOrder()\n3. **Test** - should pass\n4. **Extract** calculation into calculateOrderTotal()\n5. **Test** - should pass\n6. **Extract** notification into notifyCustomer()\n7. **Test** - should pass\n8. **Review** - processOrder() now orchestrates 3 clear functions\n\n**After:**\n```javascript\nfunction processOrder(order) {\n  validateOrder(order);\n  const total = calculateOrderTotal(order);\n  notifyCustomer(order, total);\n  return { order, total };\n}\n```\n\n---\n\n## References\n\n- [Code Smells Catalog](references/code-smells.md) - Complete list of code smells\n- [Refactoring Catalog](references/refactoring-catalog.md) - Refactoring techniques\n- [Refactoring Plan Template](templates/refactoring-plan.md) - Planning template\n\n## Scripts\n\n- `scripts/analyze-complexity.py` - Analyze code complexity metrics\n- `scripts/detect-smells.py` - Automated smell detection\n\n## Version History\n\n- v1.0.0 (2025-01-15): Initial release with Fowler methodology, phased approach, user consultation points\n"
  },
  {
    "path": "03-skills/refactor/references/code-smells.md",
    "content": "# Code Smells Catalog\n\nA comprehensive reference of code smells based on Martin Fowler's *Refactoring* (2nd Edition). Code smells are symptoms of deeper problems—they indicate that something might be wrong with your code's design.\n\n> \"A code smell is a surface indication that usually corresponds to a deeper problem in the system.\" — Martin Fowler\n\n---\n\n## Bloaters\n\nCode smells representing something that has grown too large to be handled effectively.\n\n### Long Method\n\n**Signs:**\n- Method exceeds 30-50 lines\n- Need to scroll to see the whole method\n- Multiple levels of nesting\n- Comments explaining what sections do\n\n**Why it's bad:**\n- Hard to understand\n- Difficult to test in isolation\n- Changes have unintended consequences\n- Duplicate logic hides inside\n\n**Refactorings:**\n- Extract Method\n- Replace Temp with Query\n- Introduce Parameter Object\n- Replace Method with Method Object\n- Decompose Conditional\n\n**Example (Before):**\n```javascript\nfunction processOrder(order) {\n  // Validate order (20 lines)\n  if (!order.items) throw new Error('No items');\n  if (order.items.length === 0) throw new Error('Empty order');\n  // ... more validation\n\n  // Calculate totals (30 lines)\n  let subtotal = 0;\n  for (const item of order.items) {\n    subtotal += item.price * item.quantity;\n  }\n  // ... tax, shipping, discounts\n\n  // Send notifications (20 lines)\n  // ... email logic\n}\n```\n\n**Example (After):**\n```javascript\nfunction processOrder(order) {\n  validateOrder(order);\n  const totals = calculateOrderTotals(order);\n  sendOrderNotifications(order, totals);\n  return { order, totals };\n}\n```\n\n---\n\n### Large Class\n\n**Signs:**\n- Class has many instance variables (>7-10)\n- Class has many methods (>15-20)\n- Class name is vague (Manager, Handler, Processor)\n- Methods don't use all instance variables\n\n**Why it's bad:**\n- Violates Single Responsibility Principle\n- Hard to test\n- Changes ripple through unrelated features\n- Difficult to reuse parts\n\n**Refactorings:**\n- Extract Class\n- Extract Subclass\n- Extract Interface\n\n**Detection:**\n```\nLines of code > 300\nNumber of methods > 15\nNumber of fields > 10\n```\n\n---\n\n### Primitive Obsession\n\n**Signs:**\n- Using primitives for domain concepts (string for email, int for money)\n- Arrays of primitives instead of objects\n- String constants for type codes\n- Magic numbers/strings\n\n**Why it's bad:**\n- No validation at type level\n- Logic scattered across codebase\n- Easy to pass wrong values\n- Missing domain concepts\n\n**Refactorings:**\n- Replace Primitive with Object\n- Replace Type Code with Class\n- Replace Type Code with Subclasses\n- Replace Type Code with State/Strategy\n\n**Example (Before):**\n```javascript\nconst user = {\n  email: 'john@example.com',     // Just a string\n  phone: '1234567890',           // Just a string\n  status: 'active',              // Magic string\n  balance: 10050                 // Cents as integer\n};\n```\n\n**Example (After):**\n```javascript\nconst user = {\n  email: new Email('john@example.com'),\n  phone: new PhoneNumber('1234567890'),\n  status: UserStatus.ACTIVE,\n  balance: Money.cents(10050)\n};\n```\n\n---\n\n### Long Parameter List\n\n**Signs:**\n- Methods with 4+ parameters\n- Parameters that always appear together\n- Boolean flags changing method behavior\n- Null/undefined passed frequently\n\n**Why it's bad:**\n- Hard to call correctly\n- Parameter order confusion\n- Indicates method doing too much\n- Hard to add new parameters\n\n**Refactorings:**\n- Introduce Parameter Object\n- Preserve Whole Object\n- Replace Parameter with Method Call\n- Remove Flag Argument\n\n**Example (Before):**\n```javascript\nfunction createUser(firstName, lastName, email, phone,\n                    street, city, state, zip,\n                    isAdmin, isActive, createdBy) {\n  // ...\n}\n```\n\n**Example (After):**\n```javascript\nfunction createUser(personalInfo, address, options) {\n  // personalInfo: { firstName, lastName, email, phone }\n  // address: { street, city, state, zip }\n  // options: { isAdmin, isActive, createdBy }\n}\n```\n\n---\n\n### Data Clumps\n\n**Signs:**\n- Same 3+ fields appear together repeatedly\n- Parameters that always travel together\n- Classes with field subsets belonging together\n\n**Why it's bad:**\n- Duplicate handling logic\n- Missing abstraction\n- Harder to extend\n- Indicates hidden class\n\n**Refactorings:**\n- Extract Class\n- Introduce Parameter Object\n- Preserve Whole Object\n\n**Example:**\n```javascript\n// Data clump: (x, y, z) coordinates\nfunction movePoint(x, y, z, dx, dy, dz) { }\nfunction scalePoint(x, y, z, factor) { }\nfunction distanceBetween(x1, y1, z1, x2, y2, z2) { }\n\n// Extract Point3D class\nclass Point3D {\n  constructor(x, y, z) { }\n  move(delta) { }\n  scale(factor) { }\n  distanceTo(other) { }\n}\n```\n\n---\n\n## Object-Orientation Abusers\n\nSmells indicating incomplete or incorrect use of OOP principles.\n\n### Switch Statements\n\n**Signs:**\n- Long switch/case or if/else chains\n- Same switch in multiple places\n- Switch on type codes\n- Adding new cases requires changes everywhere\n\n**Why it's bad:**\n- Violates Open/Closed Principle\n- Changes ripple to all switch locations\n- Hard to extend\n- Often indicates missing polymorphism\n\n**Refactorings:**\n- Replace Conditional with Polymorphism\n- Replace Type Code with Subclasses\n- Replace Type Code with State/Strategy\n\n**Example (Before):**\n```javascript\nfunction calculatePay(employee) {\n  switch (employee.type) {\n    case 'hourly':\n      return employee.hours * employee.rate;\n    case 'salaried':\n      return employee.salary / 12;\n    case 'commissioned':\n      return employee.sales * employee.commission;\n  }\n}\n```\n\n**Example (After):**\n```javascript\nclass HourlyEmployee {\n  calculatePay() {\n    return this.hours * this.rate;\n  }\n}\n\nclass SalariedEmployee {\n  calculatePay() {\n    return this.salary / 12;\n  }\n}\n```\n\n---\n\n### Temporary Field\n\n**Signs:**\n- Instance variables only used in some methods\n- Fields set conditionally\n- Complex initialization for certain cases\n\n**Why it's bad:**\n- Confusing—field exists but might be null\n- Hard to understand object state\n- Indicates conditional logic hiding\n\n**Refactorings:**\n- Extract Class\n- Introduce Null Object\n- Replace Temp Field with Local\n\n---\n\n### Refused Bequest\n\n**Signs:**\n- Subclass doesn't use inherited methods/data\n- Subclass overrides to do nothing\n- Inheritance used for code reuse, not IS-A relationship\n\n**Why it's bad:**\n- Wrong abstraction\n- Violates Liskov Substitution Principle\n- Misleading hierarchy\n\n**Refactorings:**\n- Push Down Method/Field\n- Replace Subclass with Delegate\n- Replace Inheritance with Delegation\n\n---\n\n### Alternative Classes with Different Interfaces\n\n**Signs:**\n- Two classes that do similar things\n- Different method names for same concept\n- Could be used interchangeably\n\n**Why it's bad:**\n- Duplicate implementations\n- No common interface\n- Hard to switch between\n\n**Refactorings:**\n- Rename Method\n- Move Method\n- Extract Superclass\n- Extract Interface\n\n---\n\n## Change Preventers\n\nSmells that make changes difficult—changing one thing requires changing many others.\n\n### Divergent Change\n\n**Signs:**\n- One class changed for multiple different reasons\n- Changes in different areas trigger same class edits\n- Class is a \"God class\"\n\n**Why it's bad:**\n- Violates Single Responsibility\n- High change frequency\n- Merge conflicts\n\n**Refactorings:**\n- Extract Class\n- Extract Superclass\n- Extract Subclass\n\n**Example:**\nA `User` class changes for:\n- Authentication changes\n- Profile changes\n- Billing changes\n- Notification changes\n\n→ Extract: `AuthService`, `ProfileService`, `BillingService`, `NotificationService`\n\n---\n\n### Shotgun Surgery\n\n**Signs:**\n- One change requires edits in many classes\n- Small feature needs touching 10+ files\n- Changes are scattered, hard to find all\n\n**Why it's bad:**\n- Easy to miss a spot\n- High coupling\n- Changes are error-prone\n\n**Refactorings:**\n- Move Method\n- Move Field\n- Inline Class\n\n**Detection:**\nLook for: adding one field requires changes in >5 files.\n\n---\n\n### Parallel Inheritance Hierarchies\n\n**Signs:**\n- Creating subclass in one hierarchy requires subclass in another\n- Class prefixes match (e.g., `DatabaseOrder`, `DatabaseProduct`)\n\n**Why it's bad:**\n- Double the maintenance\n- Coupling between hierarchies\n- Easy to forget one side\n\n**Refactorings:**\n- Move Method\n- Move Field\n- Eliminate one hierarchy\n\n---\n\n## Dispensables\n\nSomething unnecessary that should be removed.\n\n### Comments (Excessive)\n\n**Signs:**\n- Comments explaining what code does\n- Commented-out code\n- TODO/FIXME that linger forever\n- Apologies in comments\n\n**Why it's bad:**\n- Comments lie (get out of sync)\n- Code should be self-documenting\n- Dead code causes confusion\n\n**Refactorings:**\n- Extract Method (name explains what)\n- Rename (clarity without comments)\n- Remove commented code\n- Introduce Assertion\n\n**Good vs Bad Comments:**\n```javascript\n// BAD: Explaining what\n// Loop through users and check if active\nfor (const user of users) {\n  if (user.status === 'active') { }\n}\n\n// GOOD: Explaining why\n// Active users only - inactive are handled by cleanup job\nconst activeUsers = users.filter(u => u.isActive);\n```\n\n---\n\n### Duplicate Code\n\n**Signs:**\n- Same code in multiple places\n- Similar code with small variations\n- Copy-paste patterns\n\n**Why it's bad:**\n- Bug fixes needed in multiple places\n- Inconsistency risk\n- Bloated codebase\n\n**Refactorings:**\n- Extract Method\n- Extract Class\n- Pull Up Method (in hierarchies)\n- Form Template Method\n\n**Detection Rule:**\nAny code duplicated 3+ times should be extracted.\n\n---\n\n### Lazy Class\n\n**Signs:**\n- Class doesn't do enough to justify existence\n- Wrapper with no added value\n- Result of over-engineering\n\n**Why it's bad:**\n- Maintenance overhead\n- Unnecessary indirection\n- Complexity without benefit\n\n**Refactorings:**\n- Inline Class\n- Collapse Hierarchy\n\n---\n\n### Dead Code\n\n**Signs:**\n- Unreachable code\n- Unused variables/methods/classes\n- Commented-out code\n- Code behind impossible conditions\n\n**Why it's bad:**\n- Confusion\n- Maintenance burden\n- Slows down understanding\n\n**Refactorings:**\n- Remove Dead Code\n- Safe Delete\n\n**Detection:**\n```bash\n# Look for unused exports\n# Look for unreferenced functions\n# IDE \"unused\" warnings\n```\n\n---\n\n### Speculative Generality\n\n**Signs:**\n- Abstract classes with one subclass\n- Unused parameters \"for future use\"\n- Methods that only delegate\n- \"Framework\" for one use case\n\n**Why it's bad:**\n- Complexity without benefit\n- YAGNI (You Ain't Gonna Need It)\n- Harder to understand\n\n**Refactorings:**\n- Collapse Hierarchy\n- Inline Class\n- Remove Parameter\n- Rename Method\n\n---\n\n## Couplers\n\nSmells that represent excessive coupling between classes.\n\n### Feature Envy\n\n**Signs:**\n- Method uses more data from another class than its own\n- Many getter calls to another object\n- Data and behavior are separated\n\n**Why it's bad:**\n- Wrong location for behavior\n- Poor encapsulation\n- Hard to maintain\n\n**Refactorings:**\n- Move Method\n- Move Field\n- Extract Method (then move)\n\n**Example (Before):**\n```javascript\nclass Order {\n  getDiscountedPrice(customer) {\n    // Uses customer data heavily\n    if (customer.loyaltyYears > 5) {\n      return this.price * customer.discountRate;\n    }\n    return this.price;\n  }\n}\n```\n\n**Example (After):**\n```javascript\nclass Customer {\n  getDiscountedPriceFor(price) {\n    if (this.loyaltyYears > 5) {\n      return price * this.discountRate;\n    }\n    return price;\n  }\n}\n```\n\n---\n\n### Inappropriate Intimacy\n\n**Signs:**\n- Classes access each other's private parts\n- Bidirectional references\n- Subclasses know too much about parents\n\n**Why it's bad:**\n- High coupling\n- Changes cascade\n- Hard to modify one without other\n\n**Refactorings:**\n- Move Method\n- Move Field\n- Change Bidirectional to Unidirectional\n- Extract Class\n- Hide Delegate\n\n---\n\n### Message Chains\n\n**Signs:**\n- Long chains of method calls: `a.getB().getC().getD().getValue()`\n- Client depends on navigation structure\n- \"Train wreck\" code\n\n**Why it's bad:**\n- Fragile—any change breaks chain\n- Violates Law of Demeter\n- Coupling to structure\n\n**Refactorings:**\n- Hide Delegate\n- Extract Method\n- Move Method\n\n**Example:**\n```javascript\n// Bad: Message chain\nconst managerName = employee.getDepartment().getManager().getName();\n\n// Better: Hide delegation\nconst managerName = employee.getManagerName();\n```\n\n---\n\n### Middle Man\n\n**Signs:**\n- Class that only delegates to another\n- Half the methods are delegations\n- No added value\n\n**Why it's bad:**\n- Unnecessary indirection\n- Maintenance overhead\n- Confusing architecture\n\n**Refactorings:**\n- Remove Middle Man\n- Inline Method\n\n---\n\n## Smell Severity Guide\n\n| Severity | Description | Action |\n|----------|-------------|--------|\n| **Critical** | Blocks development, causes bugs | Fix immediately |\n| **High** | Significant maintenance burden | Fix in current sprint |\n| **Medium** | Noticeable but manageable | Plan for near future |\n| **Low** | Minor inconvenience | Fix opportunistically |\n\n---\n\n## Quick Detection Checklist\n\nUse this checklist when scanning code:\n\n- [ ] Any method > 30 lines?\n- [ ] Any class > 300 lines?\n- [ ] Any method with > 4 parameters?\n- [ ] Any duplicated code blocks?\n- [ ] Any switch/case on type codes?\n- [ ] Any unused code?\n- [ ] Any methods using another class's data heavily?\n- [ ] Any long chains of method calls?\n- [ ] Any comments explaining \"what\" not \"why\"?\n- [ ] Any primitives that should be objects?\n\n---\n\n## Further Reading\n\n- Fowler, M. (2018). *Refactoring: Improving the Design of Existing Code* (2nd ed.)\n- Kerievsky, J. (2004). *Refactoring to Patterns*\n- Feathers, M. (2004). *Working Effectively with Legacy Code*\n"
  },
  {
    "path": "03-skills/refactor/references/refactoring-catalog.md",
    "content": "# Refactoring Catalog\n\nA curated catalog of refactoring techniques from Martin Fowler's *Refactoring* (2nd Edition). Each refactoring includes motivation, step-by-step mechanics, and examples.\n\n> \"A refactoring is defined by its mechanics—the precise sequence of steps that you follow to carry out the change.\" — Martin Fowler\n\n---\n\n## How to Use This Catalog\n\n1. **Identify the smell** using the code smells reference\n2. **Find the matching refactoring** in this catalog\n3. **Follow the mechanics** step by step\n4. **Test after each step** to ensure behavior is preserved\n\n**Golden Rule**: If any step takes more than 10 minutes, break it into smaller steps.\n\n---\n\n## Most Common Refactorings\n\n### Extract Method\n\n**When to use**: Long method, duplicate code, need to name a concept\n\n**Motivation**: Turn a code fragment into a method whose name explains the purpose.\n\n**Mechanics**:\n1. Create a new method named for what it does (not how)\n2. Copy the code fragment into the new method\n3. Scan for local variables used in the fragment\n4. Pass local variables as parameters (or declare in method)\n5. Handle return values appropriately\n6. Replace the original fragment with a call to the new method\n7. Test\n\n**Before**:\n```javascript\nfunction printOwing(invoice) {\n  let outstanding = 0;\n\n  console.log(\"***********************\");\n  console.log(\"**** Customer Owes ****\");\n  console.log(\"***********************\");\n\n  // Calculate outstanding\n  for (const order of invoice.orders) {\n    outstanding += order.amount;\n  }\n\n  // Print details\n  console.log(`name: ${invoice.customer}`);\n  console.log(`amount: ${outstanding}`);\n}\n```\n\n**After**:\n```javascript\nfunction printOwing(invoice) {\n  printBanner();\n  const outstanding = calculateOutstanding(invoice);\n  printDetails(invoice, outstanding);\n}\n\nfunction printBanner() {\n  console.log(\"***********************\");\n  console.log(\"**** Customer Owes ****\");\n  console.log(\"***********************\");\n}\n\nfunction calculateOutstanding(invoice) {\n  return invoice.orders.reduce((sum, order) => sum + order.amount, 0);\n}\n\nfunction printDetails(invoice, outstanding) {\n  console.log(`name: ${invoice.customer}`);\n  console.log(`amount: ${outstanding}`);\n}\n```\n\n---\n\n### Inline Method\n\n**When to use**: Method body is as clear as its name, excessive delegation\n\n**Motivation**: Remove needless indirection when the method doesn't add value.\n\n**Mechanics**:\n1. Check that the method isn't polymorphic\n2. Find all calls to the method\n3. Replace each call with the method body\n4. Test after each replacement\n5. Remove the method definition\n\n**Before**:\n```javascript\nfunction getRating(driver) {\n  return moreThanFiveLateDeliveries(driver) ? 2 : 1;\n}\n\nfunction moreThanFiveLateDeliveries(driver) {\n  return driver.numberOfLateDeliveries > 5;\n}\n```\n\n**After**:\n```javascript\nfunction getRating(driver) {\n  return driver.numberOfLateDeliveries > 5 ? 2 : 1;\n}\n```\n\n---\n\n### Extract Variable\n\n**When to use**: Complex expression that is hard to understand\n\n**Motivation**: Give a name to a piece of a complex expression.\n\n**Mechanics**:\n1. Ensure the expression has no side effects\n2. Declare an immutable variable\n3. Set it to the result of the expression (or part)\n4. Replace the original expression with the variable\n5. Test\n\n**Before**:\n```javascript\nreturn order.quantity * order.itemPrice -\n  Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 +\n  Math.min(order.quantity * order.itemPrice * 0.1, 100);\n```\n\n**After**:\n```javascript\nconst basePrice = order.quantity * order.itemPrice;\nconst quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05;\nconst shipping = Math.min(basePrice * 0.1, 100);\nreturn basePrice - quantityDiscount + shipping;\n```\n\n---\n\n### Inline Variable\n\n**When to use**: Variable name doesn't communicate more than the expression\n\n**Motivation**: Remove unnecessary indirection.\n\n**Mechanics**:\n1. Check that the right-hand side has no side effects\n2. If variable isn't immutable, make it so and test\n3. Find the first reference and replace with the expression\n4. Test\n5. Repeat for all references\n6. Remove the declaration and assignment\n7. Test\n\n---\n\n### Rename Variable\n\n**When to use**: Name doesn't clearly communicate purpose\n\n**Motivation**: Good names are crucial for clean code.\n\n**Mechanics**:\n1. If variable is widely used, consider encapsulating\n2. Find all references\n3. Change each reference\n4. Test\n\n**Tips**:\n- Use intention-revealing names\n- Avoid abbreviations\n- Use domain terminology\n\n```javascript\n// Bad\nconst d = 30;\nconst x = users.filter(u => u.a);\n\n// Good\nconst daysSinceLastLogin = 30;\nconst activeUsers = users.filter(user => user.isActive);\n```\n\n---\n\n### Change Function Declaration\n\n**When to use**: Function name doesn't explain purpose, parameters need change\n\n**Motivation**: Good function names make code self-documenting.\n\n**Mechanics (Simple)**:\n1. Remove parameters not needed\n2. Change the name\n3. Add parameters needed\n4. Test\n\n**Mechanics (Migration - for complex changes)**:\n1. If removing parameter, make sure it's not used\n2. Create new function with desired declaration\n3. Have old function call new function\n4. Test\n5. Change callers to use new function\n6. Test after each\n7. Remove old function\n\n**Before**:\n```javascript\nfunction circum(radius) {\n  return 2 * Math.PI * radius;\n}\n```\n\n**After**:\n```javascript\nfunction circumference(radius) {\n  return 2 * Math.PI * radius;\n}\n```\n\n---\n\n### Encapsulate Variable\n\n**When to use**: Direct access to data from multiple places\n\n**Motivation**: Provide a clear access point for data manipulation.\n\n**Mechanics**:\n1. Create getter and setter functions\n2. Find all references\n3. Replace reads with getter\n4. Replace writes with setter\n5. Test after each change\n6. Restrict visibility of the variable\n\n**Before**:\n```javascript\nlet defaultOwner = { firstName: \"Martin\", lastName: \"Fowler\" };\n\n// Used in many places\nspaceship.owner = defaultOwner;\n```\n\n**After**:\n```javascript\nlet defaultOwnerData = { firstName: \"Martin\", lastName: \"Fowler\" };\n\nfunction defaultOwner() { return defaultOwnerData; }\nfunction setDefaultOwner(arg) { defaultOwnerData = arg; }\n\nspaceship.owner = defaultOwner();\n```\n\n---\n\n### Introduce Parameter Object\n\n**When to use**: Several parameters that frequently go together\n\n**Motivation**: Group data that naturally belongs together.\n\n**Mechanics**:\n1. Create a new class/structure for the grouped parameters\n2. Test\n3. Use Change Function Declaration to add the new object\n4. Test\n5. For each parameter in the group, remove it from the function and use the new object\n6. Test after each\n\n**Before**:\n```javascript\nfunction amountInvoiced(startDate, endDate) { ... }\nfunction amountReceived(startDate, endDate) { ... }\nfunction amountOverdue(startDate, endDate) { ... }\n```\n\n**After**:\n```javascript\nclass DateRange {\n  constructor(start, end) {\n    this.start = start;\n    this.end = end;\n  }\n}\n\nfunction amountInvoiced(dateRange) { ... }\nfunction amountReceived(dateRange) { ... }\nfunction amountOverdue(dateRange) { ... }\n```\n\n---\n\n### Combine Functions into Class\n\n**When to use**: Several functions operate on the same data\n\n**Motivation**: Group functions with the data they operate on.\n\n**Mechanics**:\n1. Apply Encapsulate Record to the common data\n2. Move each function into the class\n3. Test after each move\n4. Replace data arguments with uses of class fields\n\n**Before**:\n```javascript\nfunction base(reading) { ... }\nfunction taxableCharge(reading) { ... }\nfunction calculateBaseCharge(reading) { ... }\n```\n\n**After**:\n```javascript\nclass Reading {\n  constructor(data) { this._data = data; }\n\n  get base() { ... }\n  get taxableCharge() { ... }\n  get calculateBaseCharge() { ... }\n}\n```\n\n---\n\n### Split Phase\n\n**When to use**: Code deals with two different things\n\n**Motivation**: Separate code into distinct phases with clear boundaries.\n\n**Mechanics**:\n1. Create a second function for the second phase\n2. Test\n3. Introduce an intermediate data structure between phases\n4. Test\n5. Extract first phase into its own function\n6. Test\n\n**Before**:\n```javascript\nfunction priceOrder(product, quantity, shippingMethod) {\n  const basePrice = product.basePrice * quantity;\n  const discount = Math.max(quantity - product.discountThreshold, 0)\n    * product.basePrice * product.discountRate;\n  const shippingPerCase = (basePrice > shippingMethod.discountThreshold)\n    ? shippingMethod.discountedFee : shippingMethod.feePerCase;\n  const shippingCost = quantity * shippingPerCase;\n  return basePrice - discount + shippingCost;\n}\n```\n\n**After**:\n```javascript\nfunction priceOrder(product, quantity, shippingMethod) {\n  const priceData = calculatePricingData(product, quantity);\n  return applyShipping(priceData, shippingMethod);\n}\n\nfunction calculatePricingData(product, quantity) {\n  const basePrice = product.basePrice * quantity;\n  const discount = Math.max(quantity - product.discountThreshold, 0)\n    * product.basePrice * product.discountRate;\n  return { basePrice, quantity, discount };\n}\n\nfunction applyShipping(priceData, shippingMethod) {\n  const shippingPerCase = (priceData.basePrice > shippingMethod.discountThreshold)\n    ? shippingMethod.discountedFee : shippingMethod.feePerCase;\n  const shippingCost = priceData.quantity * shippingPerCase;\n  return priceData.basePrice - priceData.discount + shippingCost;\n}\n```\n\n---\n\n## Moving Features\n\n### Move Method\n\n**When to use**: Method uses more features of another class than its own\n\n**Motivation**: Put functions with the data they use most.\n\n**Mechanics**:\n1. Examine all program elements used by method in its class\n2. Check if method is polymorphic\n3. Copy method to target class\n4. Adjust for new context\n5. Make original method delegate to target\n6. Test\n7. Consider removing original method\n\n---\n\n### Move Field\n\n**When to use**: Field is used more by another class\n\n**Motivation**: Keep data with the functions that use it.\n\n**Mechanics**:\n1. Encapsulate the field if not already\n2. Test\n3. Create field in target\n4. Update references to use target field\n5. Test\n6. Remove original field\n\n---\n\n### Move Statements into Function\n\n**When to use**: Same code always appears with a function call\n\n**Motivation**: Remove duplication by moving repeated code into the function.\n\n**Mechanics**:\n1. Extract the repeated code into a function if not already\n2. Move statements into that function\n3. Test\n4. If callers no longer need standalone statements, remove them\n\n---\n\n### Move Statements to Callers\n\n**When to use**: Common behavior varies between callers\n\n**Motivation**: When behavior needs to differ, move it out of the function.\n\n**Mechanics**:\n1. Use Extract Method on the code to move\n2. Use Inline Method on the original function\n3. Remove the now-inlined call\n4. Move extracted code to each caller\n5. Test\n\n---\n\n## Organizing Data\n\n### Replace Primitive with Object\n\n**When to use**: Data item needs more behavior than simple value\n\n**Motivation**: Encapsulate data with its behavior.\n\n**Mechanics**:\n1. Apply Encapsulate Variable\n2. Create a simple value class\n3. Change the setter to create a new instance\n4. Change the getter to return the value\n5. Test\n6. Add richer behavior to the new class\n\n**Before**:\n```javascript\nclass Order {\n  constructor(data) {\n    this.priority = data.priority; // string: \"high\", \"rush\", etc.\n  }\n}\n\n// Usage\nif (order.priority === \"high\" || order.priority === \"rush\") { ... }\n```\n\n**After**:\n```javascript\nclass Priority {\n  constructor(value) {\n    if (!Priority.legalValues().includes(value))\n      throw new Error(`Invalid priority: ${value}`);\n    this._value = value;\n  }\n\n  static legalValues() { return ['low', 'normal', 'high', 'rush']; }\n  get value() { return this._value; }\n\n  higherThan(other) {\n    return Priority.legalValues().indexOf(this._value) >\n           Priority.legalValues().indexOf(other._value);\n  }\n}\n\n// Usage\nif (order.priority.higherThan(new Priority(\"normal\"))) { ... }\n```\n\n---\n\n### Replace Temp with Query\n\n**When to use**: Temporary variable holds result of an expression\n\n**Motivation**: Make the code clearer by extracting the expression into a function.\n\n**Mechanics**:\n1. Check that the variable is assigned only once\n2. Extract the assignment's right-hand side into a method\n3. Replace references to the temp with the method call\n4. Test\n5. Remove the temp declaration and assignment\n\n**Before**:\n```javascript\nconst basePrice = this._quantity * this._itemPrice;\nif (basePrice > 1000) {\n  return basePrice * 0.95;\n} else {\n  return basePrice * 0.98;\n}\n```\n\n**After**:\n```javascript\nget basePrice() {\n  return this._quantity * this._itemPrice;\n}\n\n// In the method\nif (this.basePrice > 1000) {\n  return this.basePrice * 0.95;\n} else {\n  return this.basePrice * 0.98;\n}\n```\n\n---\n\n## Simplifying Conditional Logic\n\n### Decompose Conditional\n\n**When to use**: Complex conditional (if-then-else) statement\n\n**Motivation**: Make the intention clear by extracting conditions and actions.\n\n**Mechanics**:\n1. Apply Extract Method on the condition\n2. Apply Extract Method on the then-branch\n3. Apply Extract Method on the else-branch (if present)\n\n**Before**:\n```javascript\nif (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd)) {\n  charge = quantity * plan.summerRate;\n} else {\n  charge = quantity * plan.regularRate + plan.regularServiceCharge;\n}\n```\n\n**After**:\n```javascript\nif (isSummer(aDate, plan)) {\n  charge = summerCharge(quantity, plan);\n} else {\n  charge = regularCharge(quantity, plan);\n}\n\nfunction isSummer(date, plan) {\n  return !date.isBefore(plan.summerStart) && !date.isAfter(plan.summerEnd);\n}\n\nfunction summerCharge(quantity, plan) {\n  return quantity * plan.summerRate;\n}\n\nfunction regularCharge(quantity, plan) {\n  return quantity * plan.regularRate + plan.regularServiceCharge;\n}\n```\n\n---\n\n### Consolidate Conditional Expression\n\n**When to use**: Multiple conditions with the same result\n\n**Motivation**: Make it clear that conditions are a single check.\n\n**Mechanics**:\n1. Verify no side effects in conditions\n2. Combine conditions using `and` or `or`\n3. Consider Extract Method on the combined condition\n\n**Before**:\n```javascript\nif (employee.seniority < 2) return 0;\nif (employee.monthsDisabled > 12) return 0;\nif (employee.isPartTime) return 0;\n```\n\n**After**:\n```javascript\nif (isNotEligibleForDisability(employee)) return 0;\n\nfunction isNotEligibleForDisability(employee) {\n  return employee.seniority < 2 ||\n         employee.monthsDisabled > 12 ||\n         employee.isPartTime;\n}\n```\n\n---\n\n### Replace Nested Conditional with Guard Clauses\n\n**When to use**: Deeply nested conditionals making flow hard to follow\n\n**Motivation**: Use guard clauses for special cases, keeping normal flow clear.\n\n**Mechanics**:\n1. Find the special case conditions\n2. Replace them with guard clauses that return early\n3. Test after each change\n\n**Before**:\n```javascript\nfunction payAmount(employee) {\n  let result;\n  if (employee.isSeparated) {\n    result = { amount: 0, reasonCode: \"SEP\" };\n  } else {\n    if (employee.isRetired) {\n      result = { amount: 0, reasonCode: \"RET\" };\n    } else {\n      result = calculateNormalPay(employee);\n    }\n  }\n  return result;\n}\n```\n\n**After**:\n```javascript\nfunction payAmount(employee) {\n  if (employee.isSeparated) return { amount: 0, reasonCode: \"SEP\" };\n  if (employee.isRetired) return { amount: 0, reasonCode: \"RET\" };\n  return calculateNormalPay(employee);\n}\n```\n\n---\n\n### Replace Conditional with Polymorphism\n\n**When to use**: Switch/case based on type, conditional logic varying by type\n\n**Motivation**: Let objects handle their own behavior.\n\n**Mechanics**:\n1. Create class hierarchy (if not exists)\n2. Use Factory Function for object creation\n3. Move conditional logic into superclass method\n4. Create subclass method for each case\n5. Remove original conditional\n\n**Before**:\n```javascript\nfunction plumages(birds) {\n  return birds.map(b => plumage(b));\n}\n\nfunction plumage(bird) {\n  switch (bird.type) {\n    case 'EuropeanSwallow':\n      return \"average\";\n    case 'AfricanSwallow':\n      return (bird.numberOfCoconuts > 2) ? \"tired\" : \"average\";\n    case 'NorwegianBlueParrot':\n      return (bird.voltage > 100) ? \"scorched\" : \"beautiful\";\n    default:\n      return \"unknown\";\n  }\n}\n```\n\n**After**:\n```javascript\nclass Bird {\n  get plumage() { return \"unknown\"; }\n}\n\nclass EuropeanSwallow extends Bird {\n  get plumage() { return \"average\"; }\n}\n\nclass AfricanSwallow extends Bird {\n  get plumage() {\n    return (this.numberOfCoconuts > 2) ? \"tired\" : \"average\";\n  }\n}\n\nclass NorwegianBlueParrot extends Bird {\n  get plumage() {\n    return (this.voltage > 100) ? \"scorched\" : \"beautiful\";\n  }\n}\n\nfunction createBird(data) {\n  switch (data.type) {\n    case 'EuropeanSwallow': return new EuropeanSwallow(data);\n    case 'AfricanSwallow': return new AfricanSwallow(data);\n    case 'NorwegianBlueParrot': return new NorwegianBlueParrot(data);\n    default: return new Bird(data);\n  }\n}\n```\n\n---\n\n### Introduce Special Case (Null Object)\n\n**When to use**: Repeated null checks for special cases\n\n**Motivation**: Return a special object that handles the special case.\n\n**Mechanics**:\n1. Create special case class with expected interface\n2. Add isSpecialCase check\n3. Introduce factory method\n4. Replace null checks with special case object usage\n5. Test\n\n**Before**:\n```javascript\nconst customer = site.customer;\n// ... many places checking\nif (customer === \"unknown\") {\n  customerName = \"occupant\";\n} else {\n  customerName = customer.name;\n}\n```\n\n**After**:\n```javascript\nclass UnknownCustomer {\n  get name() { return \"occupant\"; }\n  get billingPlan() { return registry.defaultPlan; }\n}\n\n// Factory method\nfunction customer(site) {\n  return site.customer === \"unknown\"\n    ? new UnknownCustomer()\n    : site.customer;\n}\n\n// Usage - no null checks needed\nconst customerName = customer.name;\n```\n\n---\n\n## Refactoring APIs\n\n### Separate Query from Modifier\n\n**When to use**: Function both returns a value and has side effects\n\n**Motivation**: Make it clear which operations have side effects.\n\n**Mechanics**:\n1. Create a new query function\n2. Copy original function's return logic\n3. Modify original to return void\n4. Replace calls that use return value\n5. Test\n\n**Before**:\n```javascript\nfunction alertForMiscreant(people) {\n  for (const p of people) {\n    if (p === \"Don\") {\n      setOffAlarms();\n      return \"Don\";\n    }\n    if (p === \"John\") {\n      setOffAlarms();\n      return \"John\";\n    }\n  }\n  return \"\";\n}\n```\n\n**After**:\n```javascript\nfunction findMiscreant(people) {\n  for (const p of people) {\n    if (p === \"Don\") return \"Don\";\n    if (p === \"John\") return \"John\";\n  }\n  return \"\";\n}\n\nfunction alertForMiscreant(people) {\n  if (findMiscreant(people) !== \"\") setOffAlarms();\n}\n```\n\n---\n\n### Parameterize Function\n\n**When to use**: Several functions doing similar things with different values\n\n**Motivation**: Remove duplication by adding a parameter.\n\n**Mechanics**:\n1. Select one function\n2. Add parameter for the varying literal\n3. Change body to use the parameter\n4. Test\n5. Change callers to use the parameterized version\n6. Remove now-unused functions\n\n**Before**:\n```javascript\nfunction tenPercentRaise(person) {\n  person.salary = person.salary * 1.10;\n}\n\nfunction fivePercentRaise(person) {\n  person.salary = person.salary * 1.05;\n}\n```\n\n**After**:\n```javascript\nfunction raise(person, factor) {\n  person.salary = person.salary * (1 + factor);\n}\n\n// Usage\nraise(person, 0.10);\nraise(person, 0.05);\n```\n\n---\n\n### Remove Flag Argument\n\n**When to use**: Boolean parameter that changes function behavior\n\n**Motivation**: Make the behavior explicit through separate functions.\n\n**Mechanics**:\n1. Create explicit function for each flag value\n2. Replace each call with appropriate new function\n3. Test after each change\n4. Remove original function\n\n**Before**:\n```javascript\nfunction bookConcert(customer, isPremium) {\n  if (isPremium) {\n    // premium booking logic\n  } else {\n    // regular booking logic\n  }\n}\n\nbookConcert(customer, true);\nbookConcert(customer, false);\n```\n\n**After**:\n```javascript\nfunction bookPremiumConcert(customer) {\n  // premium booking logic\n}\n\nfunction bookRegularConcert(customer) {\n  // regular booking logic\n}\n\nbookPremiumConcert(customer);\nbookRegularConcert(customer);\n```\n\n---\n\n## Dealing with Inheritance\n\n### Pull Up Method\n\n**When to use**: Same method in multiple subclasses\n\n**Motivation**: Remove duplication in class hierarchy.\n\n**Mechanics**:\n1. Inspect methods to ensure they are identical\n2. Check signatures are the same\n3. Create new method in superclass\n4. Copy body from one subclass\n5. Delete one subclass method, test\n6. Delete other subclass methods, test each\n\n---\n\n### Push Down Method\n\n**When to use**: Behavior relevant only to a subset of subclasses\n\n**Motivation**: Put method where it's used.\n\n**Mechanics**:\n1. Copy method to each subclass that needs it\n2. Remove method from superclass\n3. Test\n4. Remove from subclasses that don't need it\n5. Test\n\n---\n\n### Replace Subclass with Delegate\n\n**When to use**: Inheritance is being used incorrectly, need more flexibility\n\n**Motivation**: Prefer composition over inheritance when appropriate.\n\n**Mechanics**:\n1. Create empty class for delegate\n2. Add field to host class holding delegate\n3. Create constructor for delegate, called from host\n4. Move features to delegate\n5. Test after each move\n6. Replace inheritance with delegation\n\n---\n\n## Extract Class\n\n**When to use**: Large class with multiple responsibilities\n\n**Motivation**: Split class to maintain single responsibility.\n\n**Mechanics**:\n1. Decide how to split responsibilities\n2. Create new class\n3. Move field from original to new class\n4. Test\n5. Move methods from original to new class\n6. Test after each move\n7. Review and rename both classes\n8. Decide how to expose new class\n\n**Before**:\n```javascript\nclass Person {\n  get name() { return this._name; }\n  set name(arg) { this._name = arg; }\n  get officeAreaCode() { return this._officeAreaCode; }\n  set officeAreaCode(arg) { this._officeAreaCode = arg; }\n  get officeNumber() { return this._officeNumber; }\n  set officeNumber(arg) { this._officeNumber = arg; }\n\n  get telephoneNumber() {\n    return `(${this._officeAreaCode}) ${this._officeNumber}`;\n  }\n}\n```\n\n**After**:\n```javascript\nclass Person {\n  constructor() {\n    this._telephoneNumber = new TelephoneNumber();\n  }\n  get name() { return this._name; }\n  set name(arg) { this._name = arg; }\n  get telephoneNumber() { return this._telephoneNumber.toString(); }\n  get officeAreaCode() { return this._telephoneNumber.areaCode; }\n  set officeAreaCode(arg) { this._telephoneNumber.areaCode = arg; }\n}\n\nclass TelephoneNumber {\n  get areaCode() { return this._areaCode; }\n  set areaCode(arg) { this._areaCode = arg; }\n  get number() { return this._number; }\n  set number(arg) { this._number = arg; }\n  toString() { return `(${this._areaCode}) ${this._number}`; }\n}\n```\n\n---\n\n## Quick Reference: Smell to Refactoring\n\n| Code Smell | Primary Refactoring | Alternative |\n|------------|-------------------|-------------|\n| Long Method | Extract Method | Replace Temp with Query |\n| Duplicate Code | Extract Method | Pull Up Method |\n| Large Class | Extract Class | Extract Subclass |\n| Long Parameter List | Introduce Parameter Object | Preserve Whole Object |\n| Feature Envy | Move Method | Extract Method + Move |\n| Data Clumps | Extract Class | Introduce Parameter Object |\n| Primitive Obsession | Replace Primitive with Object | Replace Type Code |\n| Switch Statements | Replace Conditional with Polymorphism | Replace Type Code |\n| Temporary Field | Extract Class | Introduce Null Object |\n| Message Chains | Hide Delegate | Extract Method |\n| Middle Man | Remove Middle Man | Inline Method |\n| Divergent Change | Extract Class | Split Phase |\n| Shotgun Surgery | Move Method | Inline Class |\n| Dead Code | Remove Dead Code | - |\n| Speculative Generality | Collapse Hierarchy | Inline Class |\n\n---\n\n## Further Reading\n\n- Fowler, M. (2018). *Refactoring: Improving the Design of Existing Code* (2nd ed.)\n- Online catalog: https://refactoring.com/catalog/\n"
  },
  {
    "path": "03-skills/refactor/scripts/analyze-complexity.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nCode Complexity Analyzer\n\nAnalyzes code complexity metrics for Python, JavaScript, and TypeScript files.\nHelps measure the impact of refactoring by comparing before/after metrics.\n\nUsage:\n    python analyze-complexity.py <file>\n    python analyze-complexity.py <before_file> <after_file>  # Compare mode\n    python analyze-complexity.py --dir <directory>           # Analyze directory\n\nMetrics:\n    - Cyclomatic Complexity: Decision points in code\n    - Cognitive Complexity: How hard is it to understand\n    - Maintainability Index: Overall maintainability score (0-100)\n    - Lines of Code: Total lines\n    - Function Count: Number of functions/methods\n    - Average Function Length: Lines per function\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport sys\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\n\n\n@dataclass\nclass FunctionMetrics:\n    \"\"\"Metrics for a single function.\"\"\"\n    name: str\n    start_line: int\n    end_line: int\n    lines: int\n    cyclomatic_complexity: int\n    cognitive_complexity: int\n    parameter_count: int\n\n\n@dataclass\nclass FileMetrics:\n    \"\"\"Metrics for a file.\"\"\"\n    filename: str\n    lines_of_code: int\n    blank_lines: int\n    comment_lines: int\n    function_count: int\n    class_count: int\n    cyclomatic_complexity: int\n    cognitive_complexity: int\n    maintainability_index: float\n    avg_function_length: float\n    max_function_length: int\n    functions: List[FunctionMetrics]\n\n\nclass ComplexityAnalyzer:\n    \"\"\"Analyze code complexity for multiple languages.\"\"\"\n\n    # Patterns for different languages\n    PATTERNS = {\n        'python': {\n            'function': r'^\\s*def\\s+(\\w+)\\s*\\(',\n            'class': r'^\\s*class\\s+(\\w+)',\n            'decision': [r'\\bif\\b', r'\\belif\\b', r'\\bfor\\b', r'\\bwhile\\b',\n                        r'\\bexcept\\b', r'\\band\\b(?!$)', r'\\bor\\b(?!$)',\n                        r'\\bcase\\b', r'\\btry\\b'],\n            'comment': r'^\\s*#',\n            'multiline_comment_start': r'^\\s*[\"\\'][\\\"\\'][\\\"\\']',\n            'multiline_comment_end': r'[\"\\'][\\\"\\'][\\\"\\']',\n        },\n        'javascript': {\n            'function': r'(?:function\\s+(\\w+)|(\\w+)\\s*[=:]\\s*(?:async\\s+)?(?:function|\\([^)]*\\)\\s*=>))',\n            'class': r'class\\s+(\\w+)',\n            'decision': [r'\\bif\\b', r'\\belse\\s+if\\b', r'\\bfor\\b', r'\\bwhile\\b',\n                        r'\\bcatch\\b', r'\\b\\?\\b', r'\\b&&\\b', r'\\b\\|\\|\\b',\n                        r'\\bcase\\b', r'\\btry\\b'],\n            'comment': r'^\\s*//',\n            'multiline_comment_start': r'/\\*',\n            'multiline_comment_end': r'\\*/',\n        },\n        'typescript': {\n            'function': r'(?:function\\s+(\\w+)|(\\w+)\\s*[=:]\\s*(?:async\\s+)?(?:function|\\([^)]*\\)\\s*=>))',\n            'class': r'class\\s+(\\w+)',\n            'decision': [r'\\bif\\b', r'\\belse\\s+if\\b', r'\\bfor\\b', r'\\bwhile\\b',\n                        r'\\bcatch\\b', r'\\b\\?\\b', r'\\b&&\\b', r'\\b\\|\\|\\b',\n                        r'\\bcase\\b', r'\\btry\\b'],\n            'comment': r'^\\s*//',\n            'multiline_comment_start': r'/\\*',\n            'multiline_comment_end': r'\\*/',\n        }\n    }\n\n    def __init__(self, filepath: str):\n        self.filepath = filepath\n        self.filename = os.path.basename(filepath)\n        self.language = self._detect_language()\n        self.patterns = self.PATTERNS.get(self.language, self.PATTERNS['python'])\n\n        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:\n            self.code = f.read()\n        self.lines = self.code.split('\\n')\n\n    def _detect_language(self) -> str:\n        \"\"\"Detect programming language from file extension.\"\"\"\n        ext = os.path.splitext(self.filepath)[1].lower()\n        ext_map = {\n            '.py': 'python',\n            '.js': 'javascript',\n            '.jsx': 'javascript',\n            '.ts': 'typescript',\n            '.tsx': 'typescript',\n        }\n        return ext_map.get(ext, 'python')\n\n    def calculate_cyclomatic_complexity(self, code: Optional[str] = None) -> int:\n        \"\"\"\n        Calculate cyclomatic complexity using McCabe's method.\n        CC = E - N + 2P where E=edges, N=nodes, P=connected components\n        Simplified: Count decision points + 1\n        \"\"\"\n        if code is None:\n            code = self.code\n\n        complexity = 1  # Base complexity\n\n        for pattern in self.patterns['decision']:\n            matches = re.findall(pattern, code)\n            complexity += len(matches)\n\n        return complexity\n\n    def calculate_cognitive_complexity(self, code: Optional[str] = None) -> int:\n        \"\"\"\n        Calculate cognitive complexity.\n        Measures how hard it is to understand the code.\n        Accounts for nesting depth and control flow breaks.\n        \"\"\"\n        if code is None:\n            code = self.code\n\n        lines = code.split('\\n')\n        cognitive = 0\n        nesting_depth = 0\n        in_function = False\n\n        for line in lines:\n            stripped = line.strip()\n\n            # Track function boundaries\n            if re.search(self.patterns['function'], line):\n                in_function = True\n                nesting_depth = 0\n\n            # Increment for control flow structures\n            if re.search(r'\\b(if|for|while|switch)\\b', stripped):\n                nesting_depth += 1\n                cognitive += nesting_depth  # Nested structures cost more\n\n            elif re.search(r'\\b(elif|else if|else|catch|finally)\\b', stripped):\n                cognitive += nesting_depth  # Same level as parent\n\n            # Track nesting through braces/indentation\n            if self.language in ['javascript', 'typescript']:\n                nesting_depth += stripped.count('{') - stripped.count('}')\n                nesting_depth = max(0, nesting_depth)\n\n            # Bonus for breaks in linear flow\n            if re.search(r'\\b(break|continue|return|throw)\\b', stripped):\n                if nesting_depth > 1:\n                    cognitive += 1\n\n            # Bonus for recursion\n            # (simplified: just look for function calling itself)\n\n        return cognitive\n\n    def calculate_maintainability_index(self) -> float:\n        \"\"\"\n        Calculate Maintainability Index (0-100).\n        Based on Halstead Volume, Cyclomatic Complexity, and Lines of Code.\n\n        MI = max(0, (171 - 5.2*ln(V) - 0.23*CC - 16.2*ln(LOC)) * 100/171)\n\n        Interpretation:\n        - 85-100: Highly maintainable\n        - 65-84: Moderately maintainable\n        - 50-64: Difficult to maintain\n        - 0-49: Very difficult to maintain\n        \"\"\"\n        import math\n\n        loc = len([l for l in self.lines if l.strip()])\n        cc = self.calculate_cyclomatic_complexity()\n\n        # Simplified Halstead Volume approximation\n        # Count unique operators and operands\n        operators = len(re.findall(r'[+\\-*/%=<>!&|^~]', self.code))\n        operands = len(re.findall(r'\\b\\w+\\b', self.code))\n        volume = (operators + operands) * math.log2(max(1, operators + operands))\n\n        # Calculate MI\n        mi = 171 - 5.2 * math.log(max(1, volume)) - 0.23 * cc - 16.2 * math.log(max(1, loc))\n        mi = max(0, min(100, mi * 100 / 171))\n\n        return round(mi, 2)\n\n    def count_lines(self) -> Dict[str, int]:\n        \"\"\"Count different types of lines.\"\"\"\n        total = len(self.lines)\n        blank = 0\n        comment = 0\n        in_multiline_comment = False\n\n        for line in self.lines:\n            stripped = line.strip()\n\n            # Check for multiline comments\n            if re.search(self.patterns['multiline_comment_start'], stripped):\n                in_multiline_comment = True\n            if re.search(self.patterns['multiline_comment_end'], stripped):\n                in_multiline_comment = False\n                comment += 1\n                continue\n\n            if in_multiline_comment:\n                comment += 1\n            elif not stripped:\n                blank += 1\n            elif re.match(self.patterns['comment'], stripped):\n                comment += 1\n\n        return {\n            'total': total,\n            'blank': blank,\n            'comment': comment,\n            'code': total - blank - comment\n        }\n\n    def find_functions(self) -> List[FunctionMetrics]:\n        \"\"\"Find all functions and calculate their individual metrics.\"\"\"\n        functions = []\n        current_function = None\n        function_start = 0\n        brace_depth = 0\n\n        for i, line in enumerate(self.lines):\n            # Check for function definition\n            match = re.search(self.patterns['function'], line)\n            if match:\n                # Save previous function if exists\n                if current_function:\n                    func_code = '\\n'.join(self.lines[function_start:i])\n                    functions.append(self._create_function_metrics(\n                        current_function, function_start, i - 1, func_code\n                    ))\n\n                current_function = match.group(1) or match.group(2) if match.lastindex and match.lastindex > 1 else match.group(1)\n                function_start = i\n                brace_depth = 0\n\n            # Track braces for JS/TS\n            if self.language in ['javascript', 'typescript']:\n                brace_depth += line.count('{') - line.count('}')\n\n        # Don't forget the last function\n        if current_function:\n            func_code = '\\n'.join(self.lines[function_start:])\n            functions.append(self._create_function_metrics(\n                current_function, function_start, len(self.lines) - 1, func_code\n            ))\n\n        return functions\n\n    def _create_function_metrics(self, name: str, start: int, end: int, code: str) -> FunctionMetrics:\n        \"\"\"Create metrics for a single function.\"\"\"\n        lines = end - start + 1\n\n        # Count parameters (simplified)\n        param_match = re.search(r'\\(([^)]*)\\)', code.split('\\n')[0])\n        param_count = 0\n        if param_match and param_match.group(1).strip():\n            param_count = len([p for p in param_match.group(1).split(',') if p.strip()])\n\n        return FunctionMetrics(\n            name=name,\n            start_line=start + 1,\n            end_line=end + 1,\n            lines=lines,\n            cyclomatic_complexity=self.calculate_cyclomatic_complexity(code),\n            cognitive_complexity=self.calculate_cognitive_complexity(code),\n            parameter_count=param_count\n        )\n\n    def analyze(self) -> FileMetrics:\n        \"\"\"Perform complete analysis of the file.\"\"\"\n        line_counts = self.count_lines()\n        functions = self.find_functions()\n\n        # Count classes\n        class_count = len(re.findall(self.patterns['class'], self.code))\n\n        # Calculate averages\n        func_lengths = [f.lines for f in functions] if functions else [0]\n        avg_func_length = sum(func_lengths) / len(func_lengths)\n        max_func_length = max(func_lengths)\n\n        return FileMetrics(\n            filename=self.filename,\n            lines_of_code=line_counts['code'],\n            blank_lines=line_counts['blank'],\n            comment_lines=line_counts['comment'],\n            function_count=len(functions),\n            class_count=class_count,\n            cyclomatic_complexity=self.calculate_cyclomatic_complexity(),\n            cognitive_complexity=self.calculate_cognitive_complexity(),\n            maintainability_index=self.calculate_maintainability_index(),\n            avg_function_length=round(avg_func_length, 1),\n            max_function_length=max_func_length,\n            functions=functions\n        )\n\n\ndef print_metrics(metrics: FileMetrics, verbose: bool = False) -> None:\n    \"\"\"Print metrics in a readable format.\"\"\"\n    print(\"=\" * 60)\n    print(f\"CODE COMPLEXITY ANALYSIS: {metrics.filename}\")\n    print(\"=\" * 60)\n\n    print(\"\\n📊 OVERVIEW\")\n    print(\"-\" * 40)\n    print(f\"  Lines of Code:          {metrics.lines_of_code}\")\n    print(f\"  Blank Lines:            {metrics.blank_lines}\")\n    print(f\"  Comment Lines:          {metrics.comment_lines}\")\n    print(f\"  Functions/Methods:      {metrics.function_count}\")\n    print(f\"  Classes:                {metrics.class_count}\")\n\n    print(\"\\n📈 COMPLEXITY METRICS\")\n    print(\"-\" * 40)\n    print(f\"  Cyclomatic Complexity:  {metrics.cyclomatic_complexity}\")\n    print(f\"  Cognitive Complexity:   {metrics.cognitive_complexity}\")\n    print(f\"  Maintainability Index:  {metrics.maintainability_index}\")\n\n    # Interpret maintainability\n    mi = metrics.maintainability_index\n    if mi >= 85:\n        mi_label = \"Highly maintainable ✅\"\n    elif mi >= 65:\n        mi_label = \"Moderately maintainable 🔶\"\n    elif mi >= 50:\n        mi_label = \"Difficult to maintain ⚠️\"\n    else:\n        mi_label = \"Very difficult to maintain ❌\"\n    print(f\"    → {mi_label}\")\n\n    print(\"\\n📐 FUNCTION METRICS\")\n    print(\"-\" * 40)\n    print(f\"  Avg Function Length:    {metrics.avg_function_length} lines\")\n    print(f\"  Max Function Length:    {metrics.max_function_length} lines\")\n\n    if verbose and metrics.functions:\n        print(\"\\n📋 FUNCTION DETAILS\")\n        print(\"-\" * 40)\n        for f in sorted(metrics.functions, key=lambda x: x.cyclomatic_complexity, reverse=True):\n            flag = \" ⚠️\" if f.cyclomatic_complexity > 10 or f.lines > 50 else \"\"\n            print(f\"  {f.name}() [lines {f.start_line}-{f.end_line}]{flag}\")\n            print(f\"    - Lines: {f.lines}, CC: {f.cyclomatic_complexity}, \"\n                  f\"Cognitive: {f.cognitive_complexity}, Params: {f.parameter_count}\")\n\n    print(\"\\n\" + \"=\" * 60)\n\n\ndef print_comparison(before: FileMetrics, after: FileMetrics) -> None:\n    \"\"\"Print comparison between two analyses.\"\"\"\n    print(\"=\" * 70)\n    print(\"CODE COMPLEXITY COMPARISON\")\n    print(\"=\" * 70)\n\n    print(f\"\\n{'Metric':<30} {'Before':<15} {'After':<15} {'Change':<10}\")\n    print(\"-\" * 70)\n\n    def fmt_change(before_val, after_val, lower_is_better=True):\n        diff = after_val - before_val\n        if lower_is_better:\n            symbol = \"✅\" if diff < 0 else (\"⚠️\" if diff > 0 else \"➖\")\n        else:\n            symbol = \"✅\" if diff > 0 else (\"⚠️\" if diff < 0 else \"➖\")\n        return f\"{diff:+.1f} {symbol}\" if isinstance(diff, float) else f\"{diff:+d} {symbol}\"\n\n    metrics = [\n        (\"Lines of Code\", before.lines_of_code, after.lines_of_code, True),\n        (\"Function Count\", before.function_count, after.function_count, False),\n        (\"Class Count\", before.class_count, after.class_count, False),\n        (\"Cyclomatic Complexity\", before.cyclomatic_complexity, after.cyclomatic_complexity, True),\n        (\"Cognitive Complexity\", before.cognitive_complexity, after.cognitive_complexity, True),\n        (\"Maintainability Index\", before.maintainability_index, after.maintainability_index, False),\n        (\"Avg Function Length\", before.avg_function_length, after.avg_function_length, True),\n        (\"Max Function Length\", before.max_function_length, after.max_function_length, True),\n    ]\n\n    for name, b_val, a_val, lower_better in metrics:\n        change = fmt_change(b_val, a_val, lower_better)\n        print(f\"{name:<30} {b_val:<15} {a_val:<15} {change:<10}\")\n\n    print(\"\\n\" + \"=\" * 70)\n\n    # Overall assessment\n    print(\"\\n🎯 ASSESSMENT\")\n    print(\"-\" * 40)\n\n    improvements = 0\n    regressions = 0\n\n    if after.maintainability_index > before.maintainability_index:\n        print(\"  ✅ Maintainability improved\")\n        improvements += 1\n    elif after.maintainability_index < before.maintainability_index:\n        print(\"  ⚠️ Maintainability decreased\")\n        regressions += 1\n\n    if after.cyclomatic_complexity < before.cyclomatic_complexity:\n        print(\"  ✅ Complexity reduced\")\n        improvements += 1\n    elif after.cyclomatic_complexity > before.cyclomatic_complexity:\n        print(\"  ⚠️ Complexity increased\")\n        regressions += 1\n\n    if after.avg_function_length < before.avg_function_length:\n        print(\"  ✅ Functions are smaller on average\")\n        improvements += 1\n    elif after.avg_function_length > before.avg_function_length:\n        print(\"  ⚠️ Functions grew larger on average\")\n        regressions += 1\n\n    print(f\"\\n  Summary: {improvements} improvements, {regressions} regressions\")\n    print(\"=\" * 70)\n\n\ndef analyze_directory(directory: str, verbose: bool = False) -> None:\n    \"\"\"Analyze all supported files in a directory.\"\"\"\n    supported_extensions = ['.py', '.js', '.jsx', '.ts', '.tsx']\n    files = []\n\n    for root, _, filenames in os.walk(directory):\n        for filename in filenames:\n            if any(filename.endswith(ext) for ext in supported_extensions):\n                files.append(os.path.join(root, filename))\n\n    if not files:\n        print(f\"No supported files found in {directory}\")\n        return\n\n    print(f\"Analyzing {len(files)} files in {directory}...\\n\")\n\n    total_loc = 0\n    total_cc = 0\n    total_functions = 0\n    all_metrics = []\n\n    for filepath in sorted(files):\n        try:\n            analyzer = ComplexityAnalyzer(filepath)\n            metrics = analyzer.analyze()\n            all_metrics.append(metrics)\n\n            total_loc += metrics.lines_of_code\n            total_cc += metrics.cyclomatic_complexity\n            total_functions += metrics.function_count\n\n            if verbose:\n                print_metrics(metrics, verbose=True)\n            else:\n                flag = \" ⚠️\" if metrics.maintainability_index < 65 else \"\"\n                print(f\"  {metrics.filename}: LOC={metrics.lines_of_code}, \"\n                      f\"CC={metrics.cyclomatic_complexity}, MI={metrics.maintainability_index}{flag}\")\n        except Exception as e:\n            print(f\"  Error analyzing {filepath}: {e}\")\n\n    print(\"\\n\" + \"=\" * 60)\n    print(\"SUMMARY\")\n    print(\"=\" * 60)\n    print(f\"  Files analyzed:         {len(all_metrics)}\")\n    print(f\"  Total lines of code:    {total_loc}\")\n    print(f\"  Total complexity:       {total_cc}\")\n    print(f\"  Total functions:        {total_functions}\")\n\n    if all_metrics:\n        avg_mi = sum(m.maintainability_index for m in all_metrics) / len(all_metrics)\n        print(f\"  Avg maintainability:    {avg_mi:.1f}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description='Analyze code complexity metrics',\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s myfile.py                    Analyze single file\n  %(prog)s before.py after.py           Compare two versions\n  %(prog)s --dir src/                   Analyze directory\n  %(prog)s -v myfile.py                 Verbose output with function details\n        \"\"\"\n    )\n    parser.add_argument('files', nargs='*', help='File(s) to analyze')\n    parser.add_argument('--dir', '-d', help='Directory to analyze')\n    parser.add_argument('--verbose', '-v', action='store_true', help='Show detailed function metrics')\n    parser.add_argument('--json', '-j', action='store_true', help='Output as JSON')\n\n    args = parser.parse_args()\n\n    if args.dir:\n        analyze_directory(args.dir, args.verbose)\n    elif len(args.files) == 1:\n        analyzer = ComplexityAnalyzer(args.files[0])\n        metrics = analyzer.analyze()\n\n        if args.json:\n            import json\n            print(json.dumps({\n                'filename': metrics.filename,\n                'lines_of_code': metrics.lines_of_code,\n                'cyclomatic_complexity': metrics.cyclomatic_complexity,\n                'cognitive_complexity': metrics.cognitive_complexity,\n                'maintainability_index': metrics.maintainability_index,\n                'function_count': metrics.function_count,\n                'avg_function_length': metrics.avg_function_length,\n            }, indent=2))\n        else:\n            print_metrics(metrics, args.verbose)\n    elif len(args.files) == 2:\n        before_analyzer = ComplexityAnalyzer(args.files[0])\n        after_analyzer = ComplexityAnalyzer(args.files[1])\n        before_metrics = before_analyzer.analyze()\n        after_metrics = after_analyzer.analyze()\n        print_comparison(before_metrics, after_metrics)\n    else:\n        parser.print_help()\n        sys.exit(1)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "03-skills/refactor/scripts/detect-smells.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nCode Smell Detector\n\nDetects common code smells in Python, JavaScript, and TypeScript files.\nBased on Martin Fowler's catalog of code smells.\n\nUsage:\n    python detect-smells.py <file>\n    python detect-smells.py --dir <directory>\n    python detect-smells.py -v <file>  # Verbose with code snippets\n\nDetects:\n    - Long Method (>30 lines)\n    - Long Parameter List (>4 params)\n    - Duplicate Code (similar code blocks)\n    - Large Class (>300 lines, >10 methods)\n    - Dead Code (unused variables/functions)\n    - Complex Conditionals (deep nesting, long chains)\n    - Magic Numbers/Strings\n    - Feature Envy (methods using other class data heavily)\n    - Comments explaining what (not why)\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport sys\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Dict, List, Optional, Set, Tuple\nfrom collections import defaultdict\n\n\nclass SmellSeverity(Enum):\n    \"\"\"Severity levels for code smells.\"\"\"\n    LOW = \"Low\"\n    MEDIUM = \"Medium\"\n    HIGH = \"High\"\n    CRITICAL = \"Critical\"\n\n\nclass SmellType(Enum):\n    \"\"\"Types of code smells.\"\"\"\n    LONG_METHOD = \"Long Method\"\n    LONG_PARAMETER_LIST = \"Long Parameter List\"\n    DUPLICATE_CODE = \"Duplicate Code\"\n    LARGE_CLASS = \"Large Class\"\n    DEAD_CODE = \"Dead Code\"\n    COMPLEX_CONDITIONAL = \"Complex Conditional\"\n    MAGIC_NUMBER = \"Magic Number/String\"\n    FEATURE_ENVY = \"Feature Envy\"\n    EXCESSIVE_COMMENTS = \"Excessive Comments\"\n    DEEPLY_NESTED = \"Deeply Nested Code\"\n    PRIMITIVE_OBSESSION = \"Primitive Obsession\"\n    DATA_CLUMPS = \"Data Clumps\"\n    SWITCH_STATEMENT = \"Switch Statement\"\n    MESSAGE_CHAIN = \"Message Chain\"\n\n\n@dataclass\nclass CodeSmell:\n    \"\"\"Represents a detected code smell.\"\"\"\n    smell_type: SmellType\n    severity: SmellSeverity\n    location: str\n    line_start: int\n    line_end: int\n    description: str\n    suggestion: str\n    code_snippet: str = \"\"\n\n\n@dataclass\nclass SmellReport:\n    \"\"\"Report of all smells found in a file.\"\"\"\n    filename: str\n    smells: List[CodeSmell] = field(default_factory=list)\n\n    @property\n    def critical_count(self) -> int:\n        return sum(1 for s in self.smells if s.severity == SmellSeverity.CRITICAL)\n\n    @property\n    def high_count(self) -> int:\n        return sum(1 for s in self.smells if s.severity == SmellSeverity.HIGH)\n\n    @property\n    def medium_count(self) -> int:\n        return sum(1 for s in self.smells if s.severity == SmellSeverity.MEDIUM)\n\n    @property\n    def low_count(self) -> int:\n        return sum(1 for s in self.smells if s.severity == SmellSeverity.LOW)\n\n\nclass SmellDetector:\n    \"\"\"Detect code smells in source files.\"\"\"\n\n    # Thresholds (configurable)\n    THRESHOLDS = {\n        'long_method_lines': 30,\n        'very_long_method_lines': 50,\n        'max_parameters': 4,\n        'large_class_lines': 300,\n        'large_class_methods': 10,\n        'max_nesting_depth': 4,\n        'long_chain_length': 3,\n        'duplicate_min_lines': 5,\n    }\n\n    def __init__(self, filepath: str):\n        self.filepath = filepath\n        self.filename = os.path.basename(filepath)\n        self.language = self._detect_language()\n\n        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:\n            self.code = f.read()\n        self.lines = self.code.split('\\n')\n        self.smells: List[CodeSmell] = []\n\n    def _detect_language(self) -> str:\n        \"\"\"Detect programming language from file extension.\"\"\"\n        ext = os.path.splitext(self.filepath)[1].lower()\n        ext_map = {\n            '.py': 'python',\n            '.js': 'javascript',\n            '.jsx': 'javascript',\n            '.ts': 'typescript',\n            '.tsx': 'typescript',\n        }\n        return ext_map.get(ext, 'python')\n\n    def detect_all(self) -> SmellReport:\n        \"\"\"Run all smell detectors.\"\"\"\n        self._detect_long_methods()\n        self._detect_long_parameter_lists()\n        self._detect_large_class()\n        self._detect_complex_conditionals()\n        self._detect_magic_numbers()\n        self._detect_excessive_comments()\n        self._detect_deeply_nested()\n        self._detect_switch_statements()\n        self._detect_message_chains()\n        self._detect_duplicate_code()\n        self._detect_dead_code()\n\n        return SmellReport(filename=self.filename, smells=self.smells)\n\n    def _get_snippet(self, start: int, end: int, context: int = 2) -> str:\n        \"\"\"Get code snippet with context.\"\"\"\n        actual_start = max(0, start - context)\n        actual_end = min(len(self.lines), end + context)\n        snippet_lines = []\n        for i in range(actual_start, actual_end):\n            prefix = \"→ \" if start <= i < end else \"  \"\n            snippet_lines.append(f\"{i+1:4d} {prefix}{self.lines[i]}\")\n        return '\\n'.join(snippet_lines)\n\n    def _detect_long_methods(self) -> None:\n        \"\"\"Detect methods that are too long.\"\"\"\n        if self.language == 'python':\n            pattern = r'^\\s*def\\s+(\\w+)\\s*\\([^)]*\\):'\n        else:\n            pattern = r'(?:function\\s+(\\w+)|(\\w+)\\s*[=:]\\s*(?:async\\s+)?(?:function|\\([^)]*\\)\\s*=>))'\n\n        current_method = None\n        method_start = 0\n        brace_depth = 0\n        indent_level = 0\n\n        for i, line in enumerate(self.lines):\n            match = re.search(pattern, line)\n            if match:\n                # Check previous method if exists\n                if current_method:\n                    method_lines = i - method_start\n                    self._check_method_length(current_method, method_start, i - 1, method_lines)\n\n                current_method = match.group(1) or (match.group(2) if match.lastindex and match.lastindex > 1 else None)\n                method_start = i\n                indent_level = len(line) - len(line.lstrip())\n\n            # Track end of Python functions by indentation\n            if self.language == 'python' and current_method:\n                if line.strip() and not line.strip().startswith('#'):\n                    current_indent = len(line) - len(line.lstrip())\n                    if current_indent <= indent_level and i > method_start:\n                        method_lines = i - method_start\n                        self._check_method_length(current_method, method_start, i - 1, method_lines)\n                        current_method = None\n\n        # Check last method\n        if current_method:\n            method_lines = len(self.lines) - method_start\n            self._check_method_length(current_method, method_start, len(self.lines) - 1, method_lines)\n\n    def _check_method_length(self, name: str, start: int, end: int, lines: int) -> None:\n        \"\"\"Check if method is too long and add smell if so.\"\"\"\n        if lines > self.THRESHOLDS['very_long_method_lines']:\n            severity = SmellSeverity.HIGH\n            desc = f\"Method '{name}' is {lines} lines (threshold: {self.THRESHOLDS['long_method_lines']})\"\n        elif lines > self.THRESHOLDS['long_method_lines']:\n            severity = SmellSeverity.MEDIUM\n            desc = f\"Method '{name}' is {lines} lines (threshold: {self.THRESHOLDS['long_method_lines']})\"\n        else:\n            return\n\n        self.smells.append(CodeSmell(\n            smell_type=SmellType.LONG_METHOD,\n            severity=severity,\n            location=f\"{self.filename}:{start+1}-{end+1}\",\n            line_start=start + 1,\n            line_end=end + 1,\n            description=desc,\n            suggestion=\"Apply Extract Method to break down into smaller functions\",\n            code_snippet=self._get_snippet(start, min(start + 5, end), 0)\n        ))\n\n    def _detect_long_parameter_lists(self) -> None:\n        \"\"\"Detect functions with too many parameters.\"\"\"\n        if self.language == 'python':\n            pattern = r'def\\s+(\\w+)\\s*\\(([^)]*)\\)'\n        else:\n            pattern = r'(?:function\\s+(\\w+)\\s*\\(([^)]*)\\)|(\\w+)\\s*[=:]\\s*(?:async\\s+)?(?:function\\s*)?\\(([^)]*)\\))'\n\n        for i, line in enumerate(self.lines):\n            match = re.search(pattern, line)\n            if match:\n                # Safely extract groups\n                groups = match.groups()\n                func_name = groups[0] or (groups[2] if len(groups) > 2 else None)\n                params_str = groups[1] if len(groups) > 1 else \"\"\n                if not params_str and len(groups) > 3:\n                    params_str = groups[3] or \"\"\n\n                # Count parameters\n                if params_str.strip():\n                    params = [p.strip() for p in params_str.split(',') if p.strip()]\n                    # Filter out 'self', 'cls' for Python\n                    if self.language == 'python':\n                        params = [p for p in params if p not in ('self', 'cls')]\n                    param_count = len(params)\n\n                    if param_count > self.THRESHOLDS['max_parameters']:\n                        severity = SmellSeverity.HIGH if param_count > 6 else SmellSeverity.MEDIUM\n                        self.smells.append(CodeSmell(\n                            smell_type=SmellType.LONG_PARAMETER_LIST,\n                            severity=severity,\n                            location=f\"{self.filename}:{i+1}\",\n                            line_start=i + 1,\n                            line_end=i + 1,\n                            description=f\"Function '{func_name}' has {param_count} parameters (max: {self.THRESHOLDS['max_parameters']})\",\n                            suggestion=\"Consider Introduce Parameter Object or Preserve Whole Object\",\n                            code_snippet=self._get_snippet(i, i + 1, 1)\n                        ))\n\n    def _detect_large_class(self) -> None:\n        \"\"\"Detect classes that are too large.\"\"\"\n        if self.language == 'python':\n            class_pattern = r'^\\s*class\\s+(\\w+)'\n            method_pattern = r'^\\s+def\\s+\\w+'\n        else:\n            class_pattern = r'class\\s+(\\w+)'\n            method_pattern = r'(?:^\\s+\\w+\\s*\\([^)]*\\)\\s*\\{|^\\s+(?:async\\s+)?\\w+\\s*=)'\n\n        current_class = None\n        class_start = 0\n        method_count = 0\n        class_indent = 0\n\n        for i, line in enumerate(self.lines):\n            class_match = re.search(class_pattern, line)\n            if class_match:\n                # Check previous class\n                if current_class:\n                    self._check_class_size(current_class, class_start, i - 1, method_count)\n\n                current_class = class_match.group(1)\n                class_start = i\n                method_count = 0\n                class_indent = len(line) - len(line.lstrip())\n\n            # Count methods in current class\n            if current_class and re.search(method_pattern, line):\n                method_count += 1\n\n        # Check last class\n        if current_class:\n            self._check_class_size(current_class, class_start, len(self.lines) - 1, method_count)\n\n    def _check_class_size(self, name: str, start: int, end: int, methods: int) -> None:\n        \"\"\"Check if class is too large.\"\"\"\n        lines = end - start + 1\n\n        issues = []\n        severity = SmellSeverity.MEDIUM\n\n        if lines > self.THRESHOLDS['large_class_lines']:\n            issues.append(f\"{lines} lines (max: {self.THRESHOLDS['large_class_lines']})\")\n            severity = SmellSeverity.HIGH\n\n        if methods > self.THRESHOLDS['large_class_methods']:\n            issues.append(f\"{methods} methods (max: {self.THRESHOLDS['large_class_methods']})\")\n            if severity != SmellSeverity.HIGH:\n                severity = SmellSeverity.MEDIUM\n\n        if issues:\n            self.smells.append(CodeSmell(\n                smell_type=SmellType.LARGE_CLASS,\n                severity=severity,\n                location=f\"{self.filename}:{start+1}-{end+1}\",\n                line_start=start + 1,\n                line_end=end + 1,\n                description=f\"Class '{name}' is too large: {', '.join(issues)}\",\n                suggestion=\"Apply Extract Class to split responsibilities\",\n                code_snippet=self._get_snippet(start, start + 3, 0)\n            ))\n\n    def _detect_complex_conditionals(self) -> None:\n        \"\"\"Detect complex conditional expressions.\"\"\"\n        for i, line in enumerate(self.lines):\n            # Count logical operators in line\n            and_or_count = len(re.findall(r'\\b(and|or|&&|\\|\\|)\\b', line))\n\n            if and_or_count >= 3:\n                self.smells.append(CodeSmell(\n                    smell_type=SmellType.COMPLEX_CONDITIONAL,\n                    severity=SmellSeverity.MEDIUM,\n                    location=f\"{self.filename}:{i+1}\",\n                    line_start=i + 1,\n                    line_end=i + 1,\n                    description=f\"Complex conditional with {and_or_count} logical operators\",\n                    suggestion=\"Apply Decompose Conditional or Consolidate Conditional Expression\",\n                    code_snippet=self._get_snippet(i, i + 1, 1)\n                ))\n\n    def _detect_magic_numbers(self) -> None:\n        \"\"\"Detect magic numbers and strings.\"\"\"\n        # Skip common acceptable values\n        acceptable = {'0', '1', '-1', '2', '100', 'true', 'false', 'null', 'None', '\"\"', \"''\"}\n\n        for i, line in enumerate(self.lines):\n            # Skip comments and imports\n            stripped = line.strip()\n            if stripped.startswith('#') or stripped.startswith('//') or \\\n               stripped.startswith('import') or stripped.startswith('from'):\n                continue\n\n            # Find numeric literals (excluding in variable names)\n            numbers = re.findall(r'(?<![a-zA-Z_])\\b(\\d+\\.?\\d*)\\b(?![a-zA-Z_])', line)\n\n            for num in numbers:\n                if num not in acceptable and float(num) > 2:\n                    # Check if it's likely a magic number (in calculation or comparison)\n                    if re.search(rf'[<>=+\\-*/]\\s*{re.escape(num)}|{re.escape(num)}\\s*[<>=+\\-*/]', line):\n                        self.smells.append(CodeSmell(\n                            smell_type=SmellType.MAGIC_NUMBER,\n                            severity=SmellSeverity.LOW,\n                            location=f\"{self.filename}:{i+1}\",\n                            line_start=i + 1,\n                            line_end=i + 1,\n                            description=f\"Magic number '{num}' - consider using a named constant\",\n                            suggestion=\"Replace magic number with named constant\",\n                            code_snippet=self._get_snippet(i, i + 1, 0)\n                        ))\n                        break  # One magic number per line is enough\n\n    def _detect_excessive_comments(self) -> None:\n        \"\"\"Detect comments that explain 'what' instead of 'why'.\"\"\"\n        what_patterns = [\n            r'#\\s*(set|get|return|loop|iterate|check|if|increment|decrement)',\n            r'//\\s*(set|get|return|loop|iterate|check|if|increment|decrement)',\n        ]\n\n        for i, line in enumerate(self.lines):\n            for pattern in what_patterns:\n                if re.search(pattern, line, re.IGNORECASE):\n                    self.smells.append(CodeSmell(\n                        smell_type=SmellType.EXCESSIVE_COMMENTS,\n                        severity=SmellSeverity.LOW,\n                        location=f\"{self.filename}:{i+1}\",\n                        line_start=i + 1,\n                        line_end=i + 1,\n                        description=\"Comment explains 'what' not 'why' - consider renaming or removing\",\n                        suggestion=\"Use Extract Method with descriptive name instead of comment\",\n                        code_snippet=self._get_snippet(i, i + 1, 0)\n                    ))\n                    break\n\n    def _detect_deeply_nested(self) -> None:\n        \"\"\"Detect deeply nested code blocks.\"\"\"\n        max_depth = 0\n        current_depth = 0\n        depth_start = 0\n\n        for i, line in enumerate(self.lines):\n            if self.language == 'python':\n                # Count by indentation\n                if line.strip():\n                    indent = len(line) - len(line.lstrip())\n                    depth = indent // 4  # Assume 4-space indent\n                    if depth > current_depth:\n                        if depth > max_depth:\n                            max_depth = depth\n                            if depth >= self.THRESHOLDS['max_nesting_depth']:\n                                depth_start = i\n                    current_depth = depth\n            else:\n                # Count braces\n                current_depth += line.count('{') - line.count('}')\n                if current_depth > max_depth:\n                    max_depth = current_depth\n                    if current_depth >= self.THRESHOLDS['max_nesting_depth']:\n                        depth_start = i\n\n        if max_depth >= self.THRESHOLDS['max_nesting_depth']:\n            self.smells.append(CodeSmell(\n                smell_type=SmellType.DEEPLY_NESTED,\n                severity=SmellSeverity.HIGH if max_depth > 5 else SmellSeverity.MEDIUM,\n                location=f\"{self.filename}:{depth_start+1}\",\n                line_start=depth_start + 1,\n                line_end=depth_start + 1,\n                description=f\"Code nested {max_depth} levels deep (max: {self.THRESHOLDS['max_nesting_depth']})\",\n                suggestion=\"Apply Replace Nested Conditional with Guard Clauses or Extract Method\",\n                code_snippet=self._get_snippet(depth_start, depth_start + 5, 0)\n            ))\n\n    def _detect_switch_statements(self) -> None:\n        \"\"\"Detect switch statements that might need polymorphism.\"\"\"\n        if self.language == 'python':\n            # Python 3.10+ match statements or if/elif chains\n            pattern = r'^\\s*(if|elif).*==.*:'\n            consecutive_conditions = 0\n            chain_start = 0\n\n            for i, line in enumerate(self.lines):\n                if re.search(pattern, line):\n                    if consecutive_conditions == 0:\n                        chain_start = i\n                    consecutive_conditions += 1\n                else:\n                    if consecutive_conditions >= 4:\n                        self._add_switch_smell(chain_start, i - 1, consecutive_conditions)\n                    consecutive_conditions = 0\n        else:\n            # JavaScript/TypeScript switch\n            pattern = r'\\bswitch\\s*\\('\n            for i, line in enumerate(self.lines):\n                if re.search(pattern, line):\n                    # Count cases\n                    case_count = 0\n                    for j in range(i, min(i + 50, len(self.lines))):\n                        case_count += len(re.findall(r'\\bcase\\b', self.lines[j]))\n                    if case_count >= 4:\n                        self._add_switch_smell(i, i + 1, case_count)\n\n    def _add_switch_smell(self, start: int, end: int, cases: int) -> None:\n        \"\"\"Add a switch statement smell.\"\"\"\n        self.smells.append(CodeSmell(\n            smell_type=SmellType.SWITCH_STATEMENT,\n            severity=SmellSeverity.MEDIUM,\n            location=f\"{self.filename}:{start+1}\",\n            line_start=start + 1,\n            line_end=end + 1,\n            description=f\"Switch/case statement with {cases} cases - consider polymorphism\",\n            suggestion=\"Apply Replace Conditional with Polymorphism\",\n            code_snippet=self._get_snippet(start, start + 5, 0)\n        ))\n\n    def _detect_message_chains(self) -> None:\n        \"\"\"Detect long method chains (train wrecks).\"\"\"\n        chain_pattern = r'(\\w+(?:\\.\\w+\\([^)]*\\)){3,})'\n\n        for i, line in enumerate(self.lines):\n            matches = re.findall(chain_pattern, line)\n            for match in matches:\n                chain_length = match.count('.')\n                if chain_length >= self.THRESHOLDS['long_chain_length']:\n                    self.smells.append(CodeSmell(\n                        smell_type=SmellType.MESSAGE_CHAIN,\n                        severity=SmellSeverity.MEDIUM,\n                        location=f\"{self.filename}:{i+1}\",\n                        line_start=i + 1,\n                        line_end=i + 1,\n                        description=f\"Message chain with {chain_length} calls - violates Law of Demeter\",\n                        suggestion=\"Apply Hide Delegate to reduce coupling\",\n                        code_snippet=self._get_snippet(i, i + 1, 0)\n                    ))\n\n    def _detect_duplicate_code(self) -> None:\n        \"\"\"Detect potential duplicate code blocks (simplified).\"\"\"\n        # Create line hashes for comparison\n        line_hashes: Dict[str, List[int]] = defaultdict(list)\n\n        for i, line in enumerate(self.lines):\n            normalized = re.sub(r'\\s+', ' ', line.strip())\n            if len(normalized) > 20:  # Only significant lines\n                line_hashes[normalized].append(i)\n\n        # Find duplicates\n        for normalized, positions in line_hashes.items():\n            if len(positions) >= 3:  # At least 3 occurrences\n                self.smells.append(CodeSmell(\n                    smell_type=SmellType.DUPLICATE_CODE,\n                    severity=SmellSeverity.MEDIUM,\n                    location=f\"{self.filename}:{positions[0]+1}\",\n                    line_start=positions[0] + 1,\n                    line_end=positions[0] + 1,\n                    description=f\"Potential duplicate code found {len(positions)} times\",\n                    suggestion=\"Apply Extract Method to eliminate duplication\",\n                    code_snippet=self._get_snippet(positions[0], positions[0] + 1, 0)\n                ))\n\n    def _detect_dead_code(self) -> None:\n        \"\"\"Detect potentially dead code (simplified).\"\"\"\n        # Look for common dead code patterns\n        patterns = [\n            (r'^\\s*#.*TODO.*delete', \"TODO to delete\"),\n            (r'^\\s*#.*FIXME.*remove', \"FIXME to remove\"),\n            (r'^\\s*//.*TODO.*delete', \"TODO to delete\"),\n            (r'^\\s*//.*FIXME.*remove', \"FIXME to remove\"),\n            (r'^\\s*if\\s+False:', \"Code behind 'if False'\"),\n            (r'^\\s*if\\s*\\(\\s*false\\s*\\)', \"Code behind 'if (false)'\"),\n        ]\n\n        for i, line in enumerate(self.lines):\n            for pattern, desc in patterns:\n                if re.search(pattern, line, re.IGNORECASE):\n                    self.smells.append(CodeSmell(\n                        smell_type=SmellType.DEAD_CODE,\n                        severity=SmellSeverity.LOW,\n                        location=f\"{self.filename}:{i+1}\",\n                        line_start=i + 1,\n                        line_end=i + 1,\n                        description=f\"Potential dead code: {desc}\",\n                        suggestion=\"Remove dead code\",\n                        code_snippet=self._get_snippet(i, i + 1, 0)\n                    ))\n\n\ndef print_report(report: SmellReport, verbose: bool = False) -> None:\n    \"\"\"Print smell report in readable format.\"\"\"\n    print(\"=\" * 70)\n    print(f\"CODE SMELL DETECTION REPORT: {report.filename}\")\n    print(\"=\" * 70)\n\n    print(f\"\\n📊 SUMMARY\")\n    print(\"-\" * 40)\n    print(f\"  Total smells found:     {len(report.smells)}\")\n    print(f\"  Critical:               {report.critical_count}\")\n    print(f\"  High:                   {report.high_count}\")\n    print(f\"  Medium:                 {report.medium_count}\")\n    print(f\"  Low:                    {report.low_count}\")\n\n    if not report.smells:\n        print(\"\\n✅ No code smells detected!\")\n        print(\"=\" * 70)\n        return\n\n    # Group by type\n    by_type: Dict[SmellType, List[CodeSmell]] = defaultdict(list)\n    for smell in report.smells:\n        by_type[smell.smell_type].append(smell)\n\n    print(f\"\\n📋 FINDINGS BY TYPE\")\n    print(\"-\" * 40)\n\n    for smell_type, smells in sorted(by_type.items(), key=lambda x: -len(x[1])):\n        print(f\"\\n### {smell_type.value} ({len(smells)} found)\")\n\n        for smell in sorted(smells, key=lambda x: x.severity.value):\n            severity_icon = {\n                SmellSeverity.CRITICAL: \"🔴\",\n                SmellSeverity.HIGH: \"🟠\",\n                SmellSeverity.MEDIUM: \"🟡\",\n                SmellSeverity.LOW: \"🟢\",\n            }[smell.severity]\n\n            print(f\"\\n  {severity_icon} [{smell.severity.value}] {smell.location}\")\n            print(f\"     {smell.description}\")\n            print(f\"     💡 {smell.suggestion}\")\n\n            if verbose and smell.code_snippet:\n                print(f\"\\n     Code:\")\n                for snippet_line in smell.code_snippet.split('\\n'):\n                    print(f\"       {snippet_line}\")\n\n    print(\"\\n\" + \"=\" * 70)\n    print(\"💡 RECOMMENDED ACTIONS\")\n    print(\"-\" * 40)\n\n    if report.critical_count > 0:\n        print(\"  1. Address CRITICAL issues immediately\")\n    if report.high_count > 0:\n        print(\"  2. Plan to fix HIGH severity issues this sprint\")\n    if report.medium_count > 0:\n        print(\"  3. Schedule MEDIUM issues for upcoming work\")\n    if report.low_count > 0:\n        print(\"  4. Fix LOW issues opportunistically\")\n\n    print(\"\\n\" + \"=\" * 70)\n\n\ndef analyze_directory(directory: str, verbose: bool = False) -> None:\n    \"\"\"Analyze all supported files in a directory.\"\"\"\n    supported_extensions = ['.py', '.js', '.jsx', '.ts', '.tsx']\n    files = []\n\n    for root, _, filenames in os.walk(directory):\n        for filename in filenames:\n            if any(filename.endswith(ext) for ext in supported_extensions):\n                files.append(os.path.join(root, filename))\n\n    if not files:\n        print(f\"No supported files found in {directory}\")\n        return\n\n    print(f\"Scanning {len(files)} files in {directory}...\\n\")\n\n    total_smells = 0\n    total_critical = 0\n    total_high = 0\n    files_with_smells = 0\n\n    for filepath in sorted(files):\n        try:\n            detector = SmellDetector(filepath)\n            report = detector.detect_all()\n\n            if report.smells:\n                files_with_smells += 1\n                total_smells += len(report.smells)\n                total_critical += report.critical_count\n                total_high += report.high_count\n\n                flag = \" 🔴\" if report.critical_count else (\" 🟠\" if report.high_count else \" 🟡\")\n                print(f\"  {report.filename}: {len(report.smells)} smells{flag}\")\n\n                if verbose:\n                    for smell in report.smells:\n                        print(f\"    - [{smell.severity.value}] {smell.smell_type.value}: line {smell.line_start}\")\n            else:\n                print(f\"  {report.filename}: ✅ Clean\")\n\n        except Exception as e:\n            print(f\"  Error analyzing {filepath}: {e}\")\n\n    print(\"\\n\" + \"=\" * 60)\n    print(\"SUMMARY\")\n    print(\"=\" * 60)\n    print(f\"  Files analyzed:         {len(files)}\")\n    print(f\"  Files with smells:      {files_with_smells}\")\n    print(f\"  Total smells found:     {total_smells}\")\n    print(f\"  Critical issues:        {total_critical}\")\n    print(f\"  High severity issues:   {total_high}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description='Detect code smells in source files',\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s myfile.py                    Analyze single file\n  %(prog)s --dir src/                   Analyze directory\n  %(prog)s -v myfile.py                 Verbose with code snippets\n        \"\"\"\n    )\n    parser.add_argument('file', nargs='?', help='File to analyze')\n    parser.add_argument('--dir', '-d', help='Directory to analyze')\n    parser.add_argument('--verbose', '-v', action='store_true', help='Show code snippets')\n    parser.add_argument('--json', '-j', action='store_true', help='Output as JSON')\n\n    args = parser.parse_args()\n\n    if args.dir:\n        analyze_directory(args.dir, args.verbose)\n    elif args.file:\n        detector = SmellDetector(args.file)\n        report = detector.detect_all()\n\n        if args.json:\n            import json\n            smells_data = [{\n                'type': s.smell_type.value,\n                'severity': s.severity.value,\n                'location': s.location,\n                'line_start': s.line_start,\n                'line_end': s.line_end,\n                'description': s.description,\n                'suggestion': s.suggestion,\n            } for s in report.smells]\n            print(json.dumps({\n                'filename': report.filename,\n                'total_smells': len(report.smells),\n                'critical': report.critical_count,\n                'high': report.high_count,\n                'medium': report.medium_count,\n                'low': report.low_count,\n                'smells': smells_data\n            }, indent=2))\n        else:\n            print_report(report, args.verbose)\n    else:\n        parser.print_help()\n        sys.exit(1)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "03-skills/refactor/templates/refactoring-plan.md",
    "content": "# Refactoring Plan Template\n\nUse this template to document and track your refactoring effort.\n\n---\n\n## Project Information\n\n| Field | Value |\n|-------|-------|\n| **Project/Module** | [Project name] |\n| **Target Files** | [List of files to refactor] |\n| **Date Created** | [Date] |\n| **Author** | [Name] |\n| **Status** | Draft / In Review / Approved / In Progress / Completed |\n\n---\n\n## Executive Summary\n\n### Goals\n- [ ] [Primary goal: e.g., Improve readability of payment processing]\n- [ ] [Secondary goal: e.g., Reduce code duplication]\n- [ ] [Tertiary goal: e.g., Improve testability]\n\n### Constraints\n- [ ] [Constraint 1: e.g., Cannot change public API]\n- [ ] [Constraint 2: e.g., Must maintain backward compatibility]\n- [ ] [Constraint 3: e.g., No changes to database schema]\n\n### Risk Level\n- [ ] Low - Minor changes, well-tested code\n- [ ] Medium - Moderate changes, some risk\n- [ ] High - Significant changes, careful attention needed\n\n---\n\n## Pre-Refactoring Checklist\n\n### Test Coverage Assessment\n\n| Metric | Current | Target | Status |\n|--------|---------|--------|--------|\n| Unit Test Coverage | __%  | ≥80% | |\n| Integration Tests | Yes/No | Yes | |\n| All Tests Passing | Yes/No | Yes | |\n\n### Required Before Starting\n- [ ] All tests passing\n- [ ] Code reviewed and understood\n- [ ] Backup/version control in place\n- [ ] User approval obtained\n\n---\n\n## Identified Code Smells\n\n### Summary\n\n| # | Smell | Location | Severity | Priority |\n|---|-------|----------|----------|----------|\n| 1 | [e.g., Long Method] | [file:line] | High | P1 |\n| 2 | [e.g., Duplicate Code] | [file:line] | Medium | P2 |\n| 3 | [e.g., Feature Envy] | [file:line] | Low | P3 |\n\n### Detailed Analysis\n\n#### Smell #1: [Name]\n\n**Location**: `path/to/file.js:45-120`\n\n**Description**: [Detailed description of the problem]\n\n**Impact**:\n- [Impact 1]\n- [Impact 2]\n\n**Proposed Solution**: [Brief overview of how to fix]\n\n---\n\n## Refactoring Phases\n\n### Phase A: Quick Wins (Low Risk)\n\n**Objective**: Simple improvements with immediate value\n\n**Estimated Changes**: [X files, Y methods]\n\n**User Approval Required**: Yes / No\n\n| # | Task | File | Refactoring | Status |\n|---|------|------|-------------|--------|\n| A1 | Rename variable `x` to `userCount` | utils.js:15 | Rename Variable | [ ] |\n| A2 | Remove unused `oldHandler()` | api.js:89 | Remove Dead Code | [ ] |\n| A3 | Extract duplicate validation | form.js:23,67 | Extract Method | [ ] |\n\n**Rollback Plan**: Revert commits A1-A3\n\n---\n\n### Phase B: Structural Improvements (Medium Risk)\n\n**Objective**: Improve code organization and clarity\n\n**Estimated Changes**: [X files, Y methods]\n\n**User Approval Required**: Yes\n\n**Dependencies**: Phase A must be complete\n\n| # | Task | File | Refactoring | Status |\n|---|------|------|-------------|--------|\n| B1 | Extract `calculatePrice()` from long method | order.js:45 | Extract Method | [ ] |\n| B2 | Introduce `OrderDetails` parameter object | order.js:12 | Introduce Parameter Object | [ ] |\n| B3 | Move `formatAddress()` to Address class | customer.js:78 | Move Method | [ ] |\n\n**Rollback Plan**: Revert to post-Phase-A commit\n\n---\n\n### Phase C: Architectural Changes (Higher Risk)\n\n**Objective**: Address deeper structural issues\n\n**Estimated Changes**: [X files, Y methods]\n\n**User Approval Required**: Yes\n\n**Dependencies**: Phases A and B must be complete\n\n| # | Task | File | Refactoring | Status |\n|---|------|------|-------------|--------|\n| C1 | Replace price switch with polymorphism | pricing.js:30 | Replace Conditional with Polymorphism | [ ] |\n| C2 | Extract `NotificationService` class | user.js:100 | Extract Class | [ ] |\n\n**Rollback Plan**: Revert to post-Phase-B commit\n\n---\n\n## Detailed Refactoring Steps\n\n### Task [ID]: [Task Name]\n\n**Smell Addressed**: [Smell name]\n\n**Refactoring Technique**: [Technique name]\n\n**Risk Level**: Low / Medium / High\n\n#### Context\n\n**Before** (Current State):\n```javascript\n// Paste current code here\n```\n\n**After** (Expected State):\n```javascript\n// Paste expected code here\n```\n\n#### Step-by-Step Mechanics\n\n1. [ ] **Step 1**: [Description]\n   - Test: Run tests after this step\n   - Expected: All tests pass\n\n2. [ ] **Step 2**: [Description]\n   - Test: Run tests after this step\n   - Expected: All tests pass\n\n3. [ ] **Step 3**: [Description]\n   - Test: Run tests after this step\n   - Expected: All tests pass\n\n#### Verification\n\n- [ ] All tests passing\n- [ ] Behavior unchanged\n- [ ] Code compiles\n- [ ] No new warnings\n\n#### Commit Message\n```\nrefactor: [Describe the refactoring]\n```\n\n---\n\n## Progress Tracking\n\n### Phase Status\n\n| Phase | Status | Started | Completed | Tests Passing |\n|-------|--------|---------|-----------|---------------|\n| A | Not Started / In Progress / Done | | | |\n| B | Not Started / In Progress / Done | | | |\n| C | Not Started / In Progress / Done | | | |\n\n### Issues Encountered\n\n| # | Issue | Resolution | Status |\n|---|-------|------------|--------|\n| 1 | [Description] | [How resolved] | Open / Resolved |\n\n---\n\n## Metrics Comparison\n\n### Before Refactoring\n\n| Metric | File 1 | File 2 | Total |\n|--------|--------|--------|-------|\n| Lines of Code | | | |\n| Cyclomatic Complexity | | | |\n| Maintainability Index | | | |\n| Number of Methods | | | |\n| Avg Method Length | | | |\n\n### After Refactoring\n\n| Metric | File 1 | File 2 | Total | Change |\n|--------|--------|--------|-------|--------|\n| Lines of Code | | | | |\n| Cyclomatic Complexity | | | | |\n| Maintainability Index | | | | |\n| Number of Methods | | | | |\n| Avg Method Length | | | | |\n\n---\n\n## Post-Refactoring Checklist\n\n- [ ] All tests passing\n- [ ] No new warnings or errors\n- [ ] Code compiles successfully\n- [ ] Manual verification completed\n- [ ] Documentation updated (if needed)\n- [ ] Code reviewed\n- [ ] Metrics improved\n- [ ] User sign-off obtained\n\n---\n\n## Lessons Learned\n\n### What Went Well\n- [Item 1]\n- [Item 2]\n\n### What Could Be Improved\n- [Item 1]\n- [Item 2]\n\n### Recommendations for Future\n- [Item 1]\n- [Item 2]\n\n---\n\n## Approvals\n\n| Role | Name | Date | Signature |\n|------|------|------|-----------|\n| Plan Author | | | |\n| Technical Lead | | | |\n| Product Owner | | | |\n\n---\n\n## Appendix\n\n### A. Related Documentation\n- [Link to relevant docs]\n\n### B. Reference Materials\n- [Link to code smells catalog]\n- [Link to refactoring catalog]\n\n### C. Tools Used\n- [Testing framework]\n- [Linting tools]\n- [Complexity analysis tools]\n"
  },
  {
    "path": "04-subagents/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Subagents - Complete Reference Guide\n\nSubagents are specialized AI assistants that Claude Code can delegate tasks to. Each subagent has a specific purpose, uses its own context window separate from the main conversation, and can be configured with specific tools and a custom system prompt.\n\n## Table of Contents\n\n1. [Overview](#overview)\n2. [Key Benefits](#key-benefits)\n3. [File Locations](#file-locations)\n4. [Configuration](#configuration)\n5. [Built-in Subagents](#built-in-subagents)\n6. [Managing Subagents](#managing-subagents)\n7. [Using Subagents](#using-subagents)\n8. [Resumable Agents](#resumable-agents)\n9. [Chaining Subagents](#chaining-subagents)\n10. [Persistent Memory for Subagents](#persistent-memory-for-subagents)\n11. [Background Subagents](#background-subagents)\n12. [Worktree Isolation](#worktree-isolation)\n13. [Restrict Spawnable Subagents](#restrict-spawnable-subagents)\n14. [`claude agents` CLI Command](#claude-agents-cli-command)\n15. [Agent Teams (Experimental)](#agent-teams-experimental)\n16. [Plugin Subagent Security](#plugin-subagent-security)\n17. [Architecture](#architecture)\n18. [Context Management](#context-management)\n19. [When to Use Subagents](#when-to-use-subagents)\n20. [Best Practices](#best-practices)\n21. [Example Subagents in This Folder](#example-subagents-in-this-folder)\n22. [Installation Instructions](#installation-instructions)\n23. [Related Concepts](#related-concepts)\n\n---\n\n## Overview\n\nSubagents enable delegated task execution in Claude Code by:\n\n- Creating **isolated AI assistants** with separate context windows\n- Providing **customized system prompts** for specialized expertise\n- Enforcing **tool access control** to limit capabilities\n- Preventing **context pollution** from complex tasks\n- Enabling **parallel execution** of multiple specialized tasks\n\nEach 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.\n\n**Quick Start**: Use the `/agents` command to create, view, edit, and manage your subagents interactively.\n\n---\n\n## Key Benefits\n\n| Benefit | Description |\n|---------|-------------|\n| **Context preservation** | Operates in separate context, preventing pollution of main conversation |\n| **Specialized expertise** | Fine-tuned for specific domains with higher success rates |\n| **Reusability** | Use across different projects and share with teams |\n| **Flexible permissions** | Different tool access levels for different subagent types |\n| **Scalability** | Multiple agents work on different aspects simultaneously |\n\n---\n\n## File Locations\n\nSubagent files can be stored in multiple locations with different scopes:\n\n| Priority | Type | Location | Scope |\n|----------|------|----------|-------|\n| 1 (highest) | **CLI-defined** | Via `--agents` flag (JSON) | Session only |\n| 2 | **Project subagents** | `.claude/agents/` | Current project |\n| 3 | **User subagents** | `~/.claude/agents/` | All projects |\n| 4 (lowest) | **Plugin agents** | Plugin `agents/` directory | Via plugins |\n\nWhen duplicate names exist, higher-priority sources take precedence.\n\n---\n\n## Configuration\n\n### File Format\n\nSubagents are defined in YAML frontmatter followed by the system prompt in markdown:\n\n```yaml\n---\nname: your-sub-agent-name\ndescription: Description of when this subagent should be invoked\ntools: tool1, tool2, tool3  # Optional - inherits all tools if omitted\ndisallowedTools: tool4  # Optional - explicitly disallowed tools\nmodel: sonnet  # Optional - sonnet, opus, haiku, or inherit\npermissionMode: default  # Optional - permission mode\nmaxTurns: 20  # Optional - limit agentic turns\nskills: skill1, skill2  # Optional - skills to preload into context\nmcpServers: server1  # Optional - MCP servers to make available\nmemory: user  # Optional - persistent memory scope (user, project, local)\nbackground: false  # Optional - run as background task\neffort: high  # Optional - reasoning effort (low, medium, high, max)\nisolation: worktree  # Optional - git worktree isolation\ninitialPrompt: \"Start by analyzing the codebase\"  # Optional - auto-submitted first turn\nhooks:  # Optional - component-scoped hooks\n  PreToolUse:\n    - matcher: \"Bash\"\n      hooks:\n        - type: command\n          command: \"./scripts/security-check.sh\"\n---\n\nYour subagent's system prompt goes here. This can be multiple paragraphs\nand should clearly define the subagent's role, capabilities, and approach\nto solving problems.\n```\n\n### Configuration Fields\n\n| Field | Required | Description |\n|-------|----------|-------------|\n| `name` | Yes | Unique identifier (lowercase letters and hyphens) |\n| `description` | Yes | Natural language description of purpose. Include \"use PROACTIVELY\" to encourage automatic invocation |\n| `tools` | No | Comma-separated list of specific tools. Omit to inherit all tools. Supports `Agent(agent_name)` syntax to restrict spawnable subagents |\n| `disallowedTools` | No | Comma-separated list of tools the subagent must not use |\n| `model` | No | Model to use: `sonnet`, `opus`, `haiku`, full model ID, or `inherit`. Defaults to configured subagent model |\n| `permissionMode` | No | `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan` |\n| `maxTurns` | No | Maximum number of agentic turns the subagent can take |\n| `skills` | No | Comma-separated list of skills to preload. Injects full skill content into the subagent's context at startup |\n| `mcpServers` | No | MCP servers to make available to the subagent |\n| `hooks` | No | Component-scoped hooks (PreToolUse, PostToolUse, Stop) |\n| `memory` | No | Persistent memory directory scope: `user`, `project`, or `local` |\n| `background` | No | Set to `true` to always run this subagent as a background task |\n| `effort` | No | Reasoning effort level: `low`, `medium`, `high`, or `max` |\n| `isolation` | No | Set to `worktree` to give the subagent its own git worktree |\n| `initialPrompt` | No | Auto-submitted first turn when the subagent runs as the main agent |\n\n### Tool Configuration Options\n\n**Option 1: Inherit All Tools (omit the field)**\n```yaml\n---\nname: full-access-agent\ndescription: Agent with all available tools\n---\n```\n\n**Option 2: Specify Individual Tools**\n```yaml\n---\nname: limited-agent\ndescription: Agent with specific tools only\ntools: Read, Grep, Glob, Bash\n---\n```\n\n**Option 3: Conditional Tool Access**\n```yaml\n---\nname: conditional-agent\ndescription: Agent with filtered tool access\ntools: Read, Bash(npm:*), Bash(test:*)\n---\n```\n\n### CLI-Based Configuration\n\nDefine subagents for a single session using the `--agents` flag with JSON format:\n\n```bash\nclaude --agents '{\n  \"code-reviewer\": {\n    \"description\": \"Expert code reviewer. Use proactively after code changes.\",\n    \"prompt\": \"You are a senior code reviewer. Focus on code quality, security, and best practices.\",\n    \"tools\": [\"Read\", \"Grep\", \"Glob\", \"Bash\"],\n    \"model\": \"sonnet\"\n  }\n}'\n```\n\n**JSON Format for `--agents` flag:**\n\n```json\n{\n  \"agent-name\": {\n    \"description\": \"Required: when to invoke this agent\",\n    \"prompt\": \"Required: system prompt for the agent\",\n    \"tools\": [\"Optional\", \"array\", \"of\", \"tools\"],\n    \"model\": \"optional: sonnet|opus|haiku\"\n  }\n}\n```\n\n**Priority of Agent Definitions:**\n\nAgent definitions are loaded with this priority order (first match wins):\n1. **CLI-defined** - `--agents` flag (session only, JSON)\n2. **Project-level** - `.claude/agents/` (current project)\n3. **User-level** - `~/.claude/agents/` (all projects)\n4. **Plugin-level** - Plugin `agents/` directory\n\nThis allows CLI definitions to override all other sources for a single session.\n\n---\n\n## Built-in Subagents\n\nClaude Code includes several built-in subagents that are always available:\n\n| Agent | Model | Purpose |\n|-------|-------|---------|\n| **general-purpose** | Inherits | Complex, multi-step tasks |\n| **Plan** | Inherits | Research for plan mode |\n| **Explore** | Haiku | Read-only codebase exploration (quick/medium/very thorough) |\n| **Bash** | Inherits | Terminal commands in separate context |\n| **statusline-setup** | Sonnet | Configure status line |\n| **Claude Code Guide** | Haiku | Answer Claude Code feature questions |\n\n### General-Purpose Subagent\n\n| Property | Value |\n|----------|-------|\n| **Model** | Inherits from parent |\n| **Tools** | All tools |\n| **Purpose** | Complex research tasks, multi-step operations, code modifications |\n\n**When used**: Tasks requiring both exploration and modification with complex reasoning.\n\n### Plan Subagent\n\n| Property | Value |\n|----------|-------|\n| **Model** | Inherits from parent |\n| **Tools** | Read, Glob, Grep, Bash |\n| **Purpose** | Used automatically in plan mode to research codebase |\n\n**When used**: When Claude needs to understand the codebase before presenting a plan.\n\n### Explore Subagent\n\n| Property | Value |\n|----------|-------|\n| **Model** | Haiku (fast, low-latency) |\n| **Mode** | Strictly read-only |\n| **Tools** | Glob, Grep, Read, Bash (read-only commands only) |\n| **Purpose** | Fast codebase searching and analysis |\n\n**When used**: When searching/understanding code without making changes.\n\n**Thoroughness Levels** - Specify the depth of exploration:\n- **\"quick\"** - Fast searches with minimal exploration, good for finding specific patterns\n- **\"medium\"** - Moderate exploration, balanced speed and thoroughness, default approach\n- **\"very thorough\"** - Comprehensive analysis across multiple locations and naming conventions, may take longer\n\n### Bash Subagent\n\n| Property | Value |\n|----------|-------|\n| **Model** | Inherits from parent |\n| **Tools** | Bash |\n| **Purpose** | Execute terminal commands in a separate context window |\n\n**When used**: When running shell commands that benefit from isolated context.\n\n### Statusline Setup Subagent\n\n| Property | Value |\n|----------|-------|\n| **Model** | Sonnet |\n| **Tools** | Read, Write, Bash |\n| **Purpose** | Configure the Claude Code status line display |\n\n**When used**: When setting up or customizing the status line.\n\n### Claude Code Guide Subagent\n\n| Property | Value |\n|----------|-------|\n| **Model** | Haiku (fast, low-latency) |\n| **Tools** | Read-only |\n| **Purpose** | Answer questions about Claude Code features and usage |\n\n**When used**: When users ask questions about how Claude Code works or how to use specific features.\n\n---\n\n## Managing Subagents\n\n### Using the `/agents` Command (Recommended)\n\n```bash\n/agents\n```\n\nThis provides an interactive menu to:\n- View all available subagents (built-in, user, and project)\n- Create new subagents with guided setup\n- Edit existing custom subagents and tool access\n- Delete custom subagents\n- See which subagents are active when duplicates exist\n\n### Direct File Management\n\n```bash\n# Create a project subagent\nmkdir -p .claude/agents\ncat > .claude/agents/test-runner.md << 'EOF'\n---\nname: test-runner\ndescription: Use proactively to run tests and fix failures\n---\n\nYou are a test automation expert. When you see code changes, proactively\nrun the appropriate tests. If tests fail, analyze the failures and fix\nthem while preserving the original test intent.\nEOF\n\n# Create a user subagent (available in all projects)\nmkdir -p ~/.claude/agents\n```\n\n---\n\n## Using Subagents\n\n### Automatic Delegation\n\nClaude proactively delegates tasks based on:\n- Task description in your request\n- The `description` field in subagent configurations\n- Current context and available tools\n\nTo encourage proactive use, include \"use PROACTIVELY\" or \"MUST BE USED\" in your `description` field:\n\n```yaml\n---\nname: code-reviewer\ndescription: Expert code review specialist. Use PROACTIVELY after writing or modifying code.\n---\n```\n\n### Explicit Invocation\n\nYou can explicitly request a specific subagent:\n\n```\n> Use the test-runner subagent to fix failing tests\n> Have the code-reviewer subagent look at my recent changes\n> Ask the debugger subagent to investigate this error\n```\n\n### @-Mention Invocation\n\nUse the `@` prefix to guarantee a specific subagent is invoked (bypasses automatic delegation heuristics):\n\n```\n> @\"code-reviewer (agent)\" review the auth module\n```\n\n### Session-Wide Agent\n\nRun an entire session using a specific agent as the main agent:\n\n```bash\n# Via CLI flag\nclaude --agent code-reviewer\n\n# Via settings.json\n{\n  \"agent\": \"code-reviewer\"\n}\n```\n\n### Listing Available Agents\n\nUse the `claude agents` command to list all configured agents from all sources:\n\n```bash\nclaude agents\n```\n\n---\n\n## Resumable Agents\n\nSubagents can continue previous conversations with full context preserved:\n\n```bash\n# Initial invocation\n> Use the code-analyzer agent to start reviewing the authentication module\n# Returns agentId: \"abc123\"\n\n# Resume the agent later\n> Resume agent abc123 and now analyze the authorization logic as well\n```\n\n**Use cases**:\n- Long-running research across multiple sessions\n- Iterative refinement without losing context\n- Multi-step workflows maintaining context\n\n---\n\n## Chaining Subagents\n\nExecute multiple subagents in sequence:\n\n```bash\n> First use the code-analyzer subagent to find performance issues,\n  then use the optimizer subagent to fix them\n```\n\nThis enables complex workflows where the output of one subagent feeds into another.\n\n---\n\n## Persistent Memory for Subagents\n\nThe `memory` field gives subagents a persistent directory that survives across conversations. This allows subagents to build up knowledge over time, storing notes, findings, and context that persist between sessions.\n\n### Memory Scopes\n\n| Scope | Directory | Use Case |\n|-------|-----------|----------|\n| `user` | `~/.claude/agent-memory/<name>/` | Personal notes and preferences across all projects |\n| `project` | `.claude/agent-memory/<name>/` | Project-specific knowledge shared with the team |\n| `local` | `.claude/agent-memory-local/<name>/` | Local project knowledge not committed to version control |\n\n### How It Works\n\n- The first 200 lines of `MEMORY.md` in the memory directory are automatically loaded into the subagent's system prompt\n- The `Read`, `Write`, and `Edit` tools are automatically enabled for the subagent to manage its memory files\n- The subagent can create additional files in its memory directory as needed\n\n### Example Configuration\n\n```yaml\n---\nname: researcher\nmemory: user\n---\n\nYou are a research assistant. Use your memory directory to store findings,\ntrack progress across sessions, and build up knowledge over time.\n\nCheck your MEMORY.md file at the start of each session to recall previous context.\n```\n\n```mermaid\ngraph LR\n    A[\"Subagent<br/>Session 1\"] -->|writes| M[\"MEMORY.md<br/>(persistent)\"]\n    M -->|loads into| B[\"Subagent<br/>Session 2\"]\n    B -->|updates| M\n    M -->|loads into| C[\"Subagent<br/>Session 3\"]\n\n    style A fill:#e1f5fe,stroke:#333,color:#333\n    style B fill:#e1f5fe,stroke:#333,color:#333\n    style C fill:#e1f5fe,stroke:#333,color:#333\n    style M fill:#f3e5f5,stroke:#333,color:#333\n```\n\n---\n\n## Background Subagents\n\nSubagents can run in the background, freeing up the main conversation for other tasks.\n\n### Configuration\n\nSet `background: true` in the frontmatter to always run the subagent as a background task:\n\n```yaml\n---\nname: long-runner\nbackground: true\ndescription: Performs long-running analysis tasks in the background\n---\n```\n\n### Keyboard Shortcuts\n\n| Shortcut | Action |\n|----------|--------|\n| `Ctrl+B` | Background a currently running subagent task |\n| `Ctrl+F` | Kill all background agents (press twice to confirm) |\n\n### Disabling Background Tasks\n\nSet the environment variable to disable background task support entirely:\n\n```bash\nexport CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1\n```\n\n---\n\n## Worktree Isolation\n\nThe `isolation: worktree` setting gives a subagent its own git worktree, allowing it to make changes independently without affecting the main working tree.\n\n### Configuration\n\n```yaml\n---\nname: feature-builder\nisolation: worktree\ndescription: Implements features in an isolated git worktree\ntools: Read, Write, Edit, Bash, Grep, Glob\n---\n```\n\n### How It Works\n\n```mermaid\ngraph TB\n    Main[\"Main Working Tree\"] -->|spawns| Sub[\"Subagent with<br/>Isolated Worktree\"]\n    Sub -->|makes changes in| WT[\"Separate Git<br/>Worktree + Branch\"]\n    WT -->|no changes| Clean[\"Auto-cleaned\"]\n    WT -->|has changes| Return[\"Returns worktree<br/>path and branch\"]\n\n    style Main fill:#e1f5fe,stroke:#333,color:#333\n    style Sub fill:#f3e5f5,stroke:#333,color:#333\n    style WT fill:#e8f5e9,stroke:#333,color:#333\n    style Clean fill:#fff3e0,stroke:#333,color:#333\n    style Return fill:#fff3e0,stroke:#333,color:#333\n```\n\n- The subagent operates in its own git worktree on a separate branch\n- If the subagent makes no changes, the worktree is automatically cleaned up\n- If changes exist, the worktree path and branch name are returned to the main agent for review or merging\n\n---\n\n## Restrict Spawnable Subagents\n\nYou can control which subagents a given subagent is allowed to spawn by using the `Agent(agent_type)` syntax in the `tools` field. This provides a way to allowlist specific subagents for delegation.\n\n> **Note**: In v2.1.63, the `Task` tool was renamed to `Agent`. Existing `Task(...)` references still work as aliases.\n\n### Example\n\n```yaml\n---\nname: coordinator\ndescription: Coordinates work between specialized agents\ntools: Agent(worker, researcher), Read, Bash\n---\n\nYou are a coordinator agent. You can delegate work to the \"worker\" and\n\"researcher\" subagents only. Use Read and Bash for your own exploration.\n```\n\nIn this example, the `coordinator` subagent can only spawn the `worker` and `researcher` subagents. It cannot spawn any other subagents, even if they are defined elsewhere.\n\n---\n\n## `claude agents` CLI Command\n\nThe `claude agents` command lists all configured agents grouped by source (built-in, user-level, project-level):\n\n```bash\nclaude agents\n```\n\nThis command:\n- Shows all available agents from all sources\n- Groups agents by their source location\n- Indicates **overrides** when an agent at a higher priority level shadows one at a lower level (e.g., a project-level agent with the same name as a user-level agent)\n\n---\n\n## Agent Teams (Experimental)\n\nAgent Teams coordinate multiple Claude Code instances working together on complex tasks. Unlike subagents (which are delegated subtasks returning results), teammates work independently with their own context and communicate directly through a shared mailbox system.\n\n> **Note**: Agent Teams is experimental and requires Claude Code v2.1.32+. Enable it before use.\n\n### Subagents vs Agent Teams\n\n| Aspect | Subagents | Agent Teams |\n|--------|-----------|-------------|\n| **Delegation model** | Parent delegates subtask, waits for result | Team lead assigns work, teammates execute independently |\n| **Context** | Fresh context per subtask, results distilled back | Each teammate maintains its own persistent context |\n| **Coordination** | Sequential or parallel, managed by parent | Shared task list with automatic dependency management |\n| **Communication** | Return values only | Inter-agent messaging via mailbox |\n| **Session resumption** | Supported | Not supported with in-process teammates |\n| **Best for** | Focused, well-defined subtasks | Large multi-file projects requiring parallel work |\n\n### Enabling Agent Teams\n\nSet the environment variable or add it to your `settings.json`:\n\n```bash\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\n```\n\nOr in `settings.json`:\n\n```json\n{\n  \"env\": {\n    \"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS\": \"1\"\n  }\n}\n```\n\n### Starting a team\n\nOnce enabled, ask Claude to work with teammates in your prompt:\n\n```\nUser: Build the authentication module. Use a team — one teammate for the API endpoints,\n      one for the database schema, and one for the test suite.\n```\n\nClaude will create the team, assign tasks, and coordinate the work automatically.\n\n### Display modes\n\nControl how teammate activity is displayed:\n\n| Mode | Flag | Description |\n|------|------|-------------|\n| **Auto** | `--teammate-mode auto` | Automatically chooses the best display mode for your terminal |\n| **In-process** | `--teammate-mode in-process` | Shows teammate output inline in the current terminal (default) |\n| **Split-panes** | `--teammate-mode tmux` | Opens each teammate in a separate tmux or iTerm2 pane |\n\n```bash\nclaude --teammate-mode tmux\n```\n\nYou can also set the display mode in `settings.json`:\n\n```json\n{\n  \"teammateMode\": \"tmux\"\n}\n```\n\n> **Note**: Split-pane mode requires tmux or iTerm2. It is not available in VS Code terminal, Windows Terminal, or Ghostty.\n\n### Navigation\n\nUse `Shift+Down` to navigate between teammates in split-pane mode.\n\n### Team Configuration\n\nTeam configurations are stored at `~/.claude/teams/{team-name}/config.json`.\n\n### Architecture\n\n```mermaid\ngraph TB\n    Lead[\"Team Lead<br/>(Coordinator)\"]\n    TaskList[\"Shared Task List<br/>(Dependencies)\"]\n    Mailbox[\"Mailbox<br/>(Messages)\"]\n    T1[\"Teammate 1<br/>(Own Context)\"]\n    T2[\"Teammate 2<br/>(Own Context)\"]\n    T3[\"Teammate 3<br/>(Own Context)\"]\n\n    Lead -->|assigns tasks| TaskList\n    Lead -->|sends messages| Mailbox\n    TaskList -->|picks up work| T1\n    TaskList -->|picks up work| T2\n    TaskList -->|picks up work| T3\n    T1 -->|reads/writes| Mailbox\n    T2 -->|reads/writes| Mailbox\n    T3 -->|reads/writes| Mailbox\n    T1 -->|updates status| TaskList\n    T2 -->|updates status| TaskList\n    T3 -->|updates status| TaskList\n\n    style Lead fill:#e1f5fe,stroke:#333,color:#333\n    style TaskList fill:#fff9c4,stroke:#333,color:#333\n    style Mailbox fill:#f3e5f5,stroke:#333,color:#333\n    style T1 fill:#e8f5e9,stroke:#333,color:#333\n    style T2 fill:#e8f5e9,stroke:#333,color:#333\n    style T3 fill:#e8f5e9,stroke:#333,color:#333\n```\n\n**Key components**:\n\n- **Team Lead**: The main Claude Code session that creates the team, assigns tasks, and coordinates\n- **Shared Task List**: A synchronized list of tasks with automatic dependency tracking\n- **Mailbox**: An inter-agent messaging system for teammates to communicate status and coordinate\n- **Teammates**: Independent Claude Code instances, each with their own context window\n\n### Task assignment and messaging\n\nThe team lead breaks work into tasks and assigns them to teammates. The shared task list handles:\n\n- **Automatic dependency management** — tasks wait for their dependencies to complete\n- **Status tracking** — teammates update task status as they work\n- **Inter-agent messaging** — teammates send messages via the mailbox for coordination (e.g., \"Database schema is ready, you can start writing queries\")\n\n### Plan approval workflow\n\nFor complex tasks, the team lead creates an execution plan before teammates begin work. The user reviews and approves the plan, ensuring the team's approach aligns with expectations before any code changes are made.\n\n### Hook events for teams\n\nAgent Teams introduce two additional [hook events](../06-hooks/):\n\n| Event | Fires When | Use Case |\n|-------|-----------|----------|\n| `TeammateIdle` | A teammate finishes its current task and has no pending work | Trigger notifications, assign follow-up tasks |\n| `TaskCompleted` | A task in the shared task list is marked complete | Run validation, update dashboards, chain dependent work |\n\n### Best practices\n\n- **Team size**: Keep teams at 3-5 teammates for optimal coordination\n- **Task sizing**: Break work into tasks that take 5-15 minutes each — small enough to parallelize, large enough to be meaningful\n- **Avoid file conflicts**: Assign different files or directories to different teammates to prevent merge conflicts\n- **Start simple**: Use in-process mode for your first team; switch to split-panes once comfortable\n- **Clear task descriptions**: Provide specific, actionable task descriptions so teammates can work independently\n\n### Limitations\n\n- **Experimental**: Feature behavior may change in future releases\n- **No session resumption**: In-process teammates cannot be resumed after a session ends\n- **One team per session**: Cannot create nested teams or multiple teams in a single session\n- **Fixed leadership**: The team lead role cannot be transferred to a teammate\n- **Split-pane restrictions**: tmux/iTerm2 required; not available in VS Code terminal, Windows Terminal, or Ghostty\n- **No cross-session teams**: Teammates exist only within the current session\n\n> **Warning**: Agent Teams is experimental. Test with non-critical work first and monitor teammate coordination for unexpected behavior.\n\n---\n\n## Plugin Subagent Security\n\nPlugin-provided subagents have restricted frontmatter capabilities for security. The following fields are **not allowed** in plugin subagent definitions:\n\n- `hooks` - Cannot define lifecycle hooks\n- `mcpServers` - Cannot configure MCP servers\n- `permissionMode` - Cannot override permission settings\n\nThis prevents plugins from escalating privileges or executing arbitrary commands through subagent hooks.\n\n---\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TB\n    User[\"User\"]\n    Main[\"Main Agent<br/>(Coordinator)\"]\n    Reviewer[\"Code Reviewer<br/>Subagent\"]\n    Tester[\"Test Engineer<br/>Subagent\"]\n    Docs[\"Documentation<br/>Subagent\"]\n\n    User -->|asks| Main\n    Main -->|delegates| Reviewer\n    Main -->|delegates| Tester\n    Main -->|delegates| Docs\n    Reviewer -->|returns result| Main\n    Tester -->|returns result| Main\n    Docs -->|returns result| Main\n    Main -->|synthesizes| User\n```\n\n### Subagent Lifecycle\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MainAgent as Main Agent\n    participant CodeReviewer as Code Reviewer<br/>Subagent\n    participant Context as Separate<br/>Context Window\n\n    User->>MainAgent: \"Build new auth feature\"\n    MainAgent->>MainAgent: Analyze task\n    MainAgent->>CodeReviewer: \"Review this code\"\n    CodeReviewer->>Context: Initialize clean context\n    Context->>CodeReviewer: Load reviewer instructions\n    CodeReviewer->>CodeReviewer: Perform review\n    CodeReviewer-->>MainAgent: Return findings\n    MainAgent->>MainAgent: Incorporate results\n    MainAgent-->>User: Provide synthesis\n```\n\n---\n\n## Context Management\n\n```mermaid\ngraph TB\n    A[\"Main Agent Context<br/>50,000 tokens\"]\n    B[\"Subagent 1 Context<br/>20,000 tokens\"]\n    C[\"Subagent 2 Context<br/>20,000 tokens\"]\n    D[\"Subagent 3 Context<br/>20,000 tokens\"]\n\n    A -->|Clean slate| B\n    A -->|Clean slate| C\n    A -->|Clean slate| D\n\n    B -->|Results only| A\n    C -->|Results only| A\n    D -->|Results only| A\n\n    style A fill:#e1f5fe\n    style B fill:#fff9c4\n    style C fill:#fff9c4\n    style D fill:#fff9c4\n```\n\n### Key Points\n\n- Each subagent gets a **fresh context window** without the main conversation history\n- Only the **relevant context** is passed to the subagent for their specific task\n- Results are **distilled** back to the main agent\n- This prevents **context token exhaustion** on long projects\n\n### Performance Considerations\n\n- **Context efficiency** - Agents preserve main context, enabling longer sessions\n- **Latency** - Subagents start with clean slate and may add latency gathering initial context\n\n### Key Behaviors\n\n- **No nested spawning** - Subagents cannot spawn other subagents\n- **Background permissions** - Background subagents auto-deny any permissions that are not pre-approved\n- **Backgrounding** - Press `Ctrl+B` to background a currently running task\n- **Transcripts** - Subagent transcripts are stored at `~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl`\n- **Auto-compaction** - Subagent context auto-compacts at ~95% capacity (override with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` environment variable)\n\n---\n\n## When to Use Subagents\n\n| Scenario | Use Subagent | Why |\n|----------|--------------|-----|\n| Complex feature with many steps | Yes | Separate concerns, prevent context pollution |\n| Quick code review | No | Unnecessary overhead |\n| Parallel task execution | Yes | Each subagent has own context |\n| Specialized expertise needed | Yes | Custom system prompts |\n| Long-running analysis | Yes | Prevents main context exhaustion |\n| Single task | No | Adds latency unnecessarily |\n\n---\n\n## Best Practices\n\n### Design Principles\n\n**Do:**\n- Start with Claude-generated agents - Generate initial subagent with Claude, then iterate to customize\n- Design focused subagents - Single, clear responsibilities rather than one doing everything\n- Write detailed prompts - Include specific instructions, examples, and constraints\n- Limit tool access - Grant only necessary tools for the subagent's purpose\n- Version control - Check project subagents into version control for team collaboration\n\n**Don't:**\n- Create overlapping subagents with same roles\n- Give subagents unnecessary tool access\n- Use subagents for simple, single-step tasks\n- Mix concerns in one subagent's prompt\n- Forget to pass necessary context\n\n### System Prompt Best Practices\n\n1. **Be Specific About Role**\n   ```\n   You are an expert code reviewer specializing in [specific areas]\n   ```\n\n2. **Define Priorities Clearly**\n   ```\n   Review priorities (in order):\n   1. Security Issues\n   2. Performance Problems\n   3. Code Quality\n   ```\n\n3. **Specify Output Format**\n   ```\n   For each issue provide: Severity, Category, Location, Description, Fix, Impact\n   ```\n\n4. **Include Action Steps**\n   ```\n   When invoked:\n   1. Run git diff to see recent changes\n   2. Focus on modified files\n   3. Begin review immediately\n   ```\n\n### Tool Access Strategy\n\n1. **Start Restrictive**: Begin with only essential tools\n2. **Expand Only When Needed**: Add tools as requirements demand\n3. **Read-Only When Possible**: Use Read/Grep for analysis agents\n4. **Sandboxed Execution**: Limit Bash commands to specific patterns\n\n---\n\n## Example Subagents in This Folder\n\nThis folder contains ready-to-use example subagents:\n\n### 1. Code Reviewer (`code-reviewer.md`)\n\n**Purpose**: Comprehensive code quality and maintainability analysis\n\n**Tools**: Read, Grep, Glob, Bash\n\n**Specialization**:\n- Security vulnerability detection\n- Performance optimization identification\n- Code maintainability assessment\n- Test coverage analysis\n\n**Use When**: You need automated code reviews with focus on quality and security\n\n---\n\n### 2. Test Engineer (`test-engineer.md`)\n\n**Purpose**: Test strategy, coverage analysis, and automated testing\n\n**Tools**: Read, Write, Bash, Grep\n\n**Specialization**:\n- Unit test creation\n- Integration test design\n- Edge case identification\n- Coverage analysis (>80% target)\n\n**Use When**: You need comprehensive test suite creation or coverage analysis\n\n---\n\n### 3. Documentation Writer (`documentation-writer.md`)\n\n**Purpose**: Technical documentation, API docs, and user guides\n\n**Tools**: Read, Write, Grep\n\n**Specialization**:\n- API endpoint documentation\n- User guide creation\n- Architecture documentation\n- Code comment improvement\n\n**Use When**: You need to create or update project documentation\n\n---\n\n### 4. Secure Reviewer (`secure-reviewer.md`)\n\n**Purpose**: Security-focused code review with minimal permissions\n\n**Tools**: Read, Grep\n\n**Specialization**:\n- Security vulnerability detection\n- Authentication/authorization issues\n- Data exposure risks\n- Injection attack identification\n\n**Use When**: You need security audits without modification capabilities\n\n---\n\n### 5. Implementation Agent (`implementation-agent.md`)\n\n**Purpose**: Full implementation capabilities for feature development\n\n**Tools**: Read, Write, Edit, Bash, Grep, Glob\n\n**Specialization**:\n- Feature implementation\n- Code generation\n- Build and test execution\n- Codebase modification\n\n**Use When**: You need a subagent to implement features end-to-end\n\n---\n\n### 6. Debugger (`debugger.md`)\n\n**Purpose**: Debugging specialist for errors, test failures, and unexpected behavior\n\n**Tools**: Read, Edit, Bash, Grep, Glob\n\n**Specialization**:\n- Root cause analysis\n- Error investigation\n- Test failure resolution\n- Minimal fix implementation\n\n**Use When**: You encounter bugs, errors, or unexpected behavior\n\n---\n\n### 7. Data Scientist (`data-scientist.md`)\n\n**Purpose**: Data analysis expert for SQL queries and data insights\n\n**Tools**: Bash, Read, Write\n\n**Specialization**:\n- SQL query optimization\n- BigQuery operations\n- Data analysis and visualization\n- Statistical insights\n\n**Use When**: You need data analysis, SQL queries, or BigQuery operations\n\n---\n\n## Installation Instructions\n\n### Method 1: Using /agents Command (Recommended)\n\n```bash\n/agents\n```\n\nThen:\n1. Select 'Create New Agent'\n2. Choose project-level or user-level\n3. Describe your subagent in detail\n4. Select tools to grant access (or leave blank to inherit all)\n5. Save and use\n\n### Method 2: Copy to Project\n\nCopy the agent files to your project's `.claude/agents/` directory:\n\n```bash\n# Navigate to your project\ncd /path/to/your/project\n\n# Create agents directory if it doesn't exist\nmkdir -p .claude/agents\n\n# Copy all agent files from this folder\ncp /path/to/04-subagents/*.md .claude/agents/\n\n# Remove the README (not needed in .claude/agents)\nrm .claude/agents/README.md\n```\n\n### Method 3: Copy to User Directory\n\nFor agents available in all your projects:\n\n```bash\n# Create user agents directory\nmkdir -p ~/.claude/agents\n\n# Copy agents\ncp /path/to/04-subagents/code-reviewer.md ~/.claude/agents/\ncp /path/to/04-subagents/debugger.md ~/.claude/agents/\n# ... copy others as needed\n```\n\n### Verification\n\nAfter installation, verify the agents are recognized:\n\n```bash\n/agents\n```\n\nYou should see your installed agents listed alongside the built-in ones.\n\n---\n\n## File Structure\n\n```\nproject/\n├── .claude/\n│   └── agents/\n│       ├── code-reviewer.md\n│       ├── test-engineer.md\n│       ├── documentation-writer.md\n│       ├── secure-reviewer.md\n│       ├── implementation-agent.md\n│       ├── debugger.md\n│       └── data-scientist.md\n└── ...\n```\n\n---\n\n## Related Concepts\n\n### Related Features\n\n- **[Slash Commands](../01-slash-commands/)** - Quick user-invoked shortcuts\n- **[Memory](../02-memory/)** - Persistent cross-session context\n- **[Skills](../03-skills/)** - Reusable autonomous capabilities\n- **[MCP Protocol](../05-mcp/)** - Real-time external data access\n- **[Hooks](../06-hooks/)** - Event-driven shell command automation\n- **[Plugins](../07-plugins/)** - Bundled extension packages\n\n### Comparison with Other Features\n\n| Feature | User-Invoked | Auto-Invoked | Persistent | External Access | Isolated Context |\n|---------|--------------|--------------|-----------|------------------|------------------|\n| **Slash Commands** | Yes | No | No | No | No |\n| **Subagents** | Yes | Yes | No | No | Yes |\n| **Memory** | Auto | Auto | Yes | No | No |\n| **MCP** | Auto | Yes | No | Yes | No |\n| **Skills** | Yes | Yes | No | No | No |\n\n### Integration Pattern\n\n```mermaid\ngraph TD\n    User[\"User Request\"] --> Main[\"Main Agent\"]\n    Main -->|Uses| Memory[\"Memory<br/>(Context)\"]\n    Main -->|Queries| MCP[\"MCP<br/>(Live Data)\"]\n    Main -->|Invokes| Skills[\"Skills<br/>(Auto Tools)\"]\n    Main -->|Delegates| Subagents[\"Subagents<br/>(Specialists)\"]\n\n    Subagents -->|Use| Memory\n    Subagents -->|Query| MCP\n    Subagents -->|Isolated| Context[\"Clean Context<br/>Window\"]\n```\n\n---\n\n## Additional Resources\n\n- [Official Subagents Documentation](https://code.claude.com/docs/en/sub-agents)\n- [CLI Reference](https://code.claude.com/docs/en/cli-reference) - `--agents` flag and other CLI options\n- [Plugins Guide](../07-plugins/) - For bundling agents with other features\n- [Skills Guide](../03-skills/) - For auto-invoked capabilities\n- [Memory Guide](../02-memory/) - For persistent context\n- [Hooks Guide](../06-hooks/) - For event-driven automation\n\n---\n\n*Last updated: March 2026*\n\n*This guide covers complete subagent configuration, delegation patterns, and best practices for Claude Code.*\n"
  },
  {
    "path": "04-subagents/clean-code-reviewer.md",
    "content": "---\nname: clean-code-reviewer\ndescription: Clean Code principles enforcement specialist. Reviews code for violations of Clean Code theory and best practices. Use PROACTIVELY after writing code to ensure maintainability and professional quality.\ntools: Read, Grep, Glob, Bash\nmodel: inherit\n---\n\n# Clean Code Reviewer Agent\n\nYou are a senior code reviewer specializing in Clean Code principles (Robert C. Martin). Identify violations and provide actionable fixes.\n\n## Process\n1. Run `git diff` to see recent changes\n2. Read relevant files thoroughly\n3. Report violations with file:line, code snippet, and fix\n\n## What to Check\n\n**Naming**: Intention-revealing, pronounceable, searchable. No encodings/prefixes. Classes=nouns, methods=verbs.\n\n**Functions**: <20 lines, do ONE thing, max 3 params, no flag args, no side effects, no null returns.\n\n**Comments**: Code should be self-explanatory. Delete commented-out code. No redundant/misleading comments.\n\n**Structure**: Small focused classes, single responsibility, high cohesion, low coupling. Avoid god classes.\n\n**SOLID**: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion.\n\n**DRY/KISS/YAGNI**: No duplication, keep it simple, don't build for hypothetical futures.\n\n**Error Handling**: Use exceptions (not error codes), provide context, never return/pass null.\n\n**Smells**: Dead code, feature envy, long param lists, message chains, primitive obsession, speculative generality.\n\n## Severity Levels\n- **Critical**: Functions >50 lines, 5+ params, 4+ nesting levels, multiple responsibilities\n- **High**: Functions 20-50 lines, 4 params, unclear naming, significant duplication\n- **Medium**: Minor duplication, comments explaining code, formatting issues\n- **Low**: Minor readability/organization improvements\n\n## Output Format\n\n```\n# Clean Code Review\n\n## Summary\nFiles: [n] | Critical: [n] | High: [n] | Medium: [n] | Low: [n]\n\n## Violations\n\n**[Severity] [Category]** `file:line`\n> [code snippet]\nProblem: [what's wrong]\nFix: [how to fix]\n\n## Good Practices\n[What's done well]\n```\n\n## Guidelines\n- Be specific: exact code + line numbers\n- Be constructive: explain WHY + provide fixes\n- Be practical: focus on impact, skip nitpicks\n- Skip: generated code, configs, test fixtures\n\n**Core Philosophy**: Code is read 10x more than written. Optimize for readability, not cleverness.\n"
  },
  {
    "path": "04-subagents/code-reviewer.md",
    "content": "---\nname: code-reviewer\ndescription: Expert code review specialist. Use PROACTIVELY after writing or modifying code to ensure quality, security, and maintainability.\ntools: Read, Grep, Glob, Bash\nmodel: inherit\n---\n\n# Code Reviewer Agent\n\nYou are a senior code reviewer ensuring high standards of code quality and security.\n\nWhen invoked:\n1. Run git diff to see recent changes\n2. Focus on modified files\n3. Begin review immediately\n\n## Review Priorities (in order)\n\n1. **Security Issues** - Authentication, authorization, data exposure\n2. **Performance Problems** - O(n^2) operations, memory leaks, inefficient queries\n3. **Code Quality** - Readability, naming, documentation\n4. **Test Coverage** - Missing tests, edge cases\n5. **Design Patterns** - SOLID principles, architecture\n\n## Review Checklist\n\n- Code is clear and readable\n- Functions and variables are well-named\n- No duplicated code\n- Proper error handling\n- No exposed secrets or API keys\n- Input validation implemented\n- Good test coverage\n- Performance considerations addressed\n\n## Review Output Format\n\nFor each issue:\n- **Severity**: Critical / High / Medium / Low\n- **Category**: Security / Performance / Quality / Testing / Design\n- **Location**: File path and line number\n- **Issue Description**: What's wrong and why\n- **Suggested Fix**: Code example\n- **Impact**: How this affects the system\n\nProvide feedback organized by priority:\n1. Critical issues (must fix)\n2. Warnings (should fix)\n3. Suggestions (consider improving)\n\nInclude specific examples of how to fix issues.\n\n## Example Review\n\n### Issue: N+1 Query Problem\n- **Severity**: High\n- **Category**: Performance\n- **Location**: src/user-service.ts:45\n- **Issue**: Loop executes database query in each iteration\n- **Fix**: Use JOIN or batch query\n- **Impact**: Response time increases linearly with data size\n"
  },
  {
    "path": "04-subagents/data-scientist.md",
    "content": "---\nname: data-scientist\ndescription: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use PROACTIVELY for data analysis tasks and queries.\ntools: Bash, Read, Write\nmodel: sonnet\n---\n\n# Data Scientist Agent\n\nYou are a data scientist specializing in SQL and BigQuery analysis.\n\nWhen invoked:\n1. Understand the data analysis requirement\n2. Write efficient SQL queries\n3. Use BigQuery command line tools (bq) when appropriate\n4. Analyze and summarize results\n5. Present findings clearly\n\n## Key Practices\n\n- Write optimized SQL queries with proper filters\n- Use appropriate aggregations and joins\n- Include comments explaining complex logic\n- Format results for readability\n- Provide data-driven recommendations\n\n## SQL Best Practices\n\n### Query Optimization\n\n- Filter early with WHERE clauses\n- Use appropriate indexes\n- Avoid SELECT * in production\n- Limit result sets when exploring\n\n### BigQuery Specific\n\n```bash\n# Run a query\nbq query --use_legacy_sql=false 'SELECT * FROM dataset.table LIMIT 10'\n\n# Export results\nbq query --use_legacy_sql=false --format=csv 'SELECT ...' > results.csv\n\n# Get table schema\nbq show --schema dataset.table\n```\n\n## Analysis Types\n\n1. **Exploratory Analysis**\n   - Data profiling\n   - Distribution analysis\n   - Missing value detection\n\n2. **Statistical Analysis**\n   - Aggregations and summaries\n   - Trend analysis\n   - Correlation detection\n\n3. **Reporting**\n   - Key metrics extraction\n   - Period-over-period comparisons\n   - Executive summaries\n\n## Output Format\n\nFor each analysis:\n- **Objective**: What question we're answering\n- **Query**: SQL used (with comments)\n- **Results**: Key findings\n- **Insights**: Data-driven conclusions\n- **Recommendations**: Suggested next steps\n\n## Example Query\n\n```sql\n-- Monthly active users trend\nSELECT\n  DATE_TRUNC(created_at, MONTH) as month,\n  COUNT(DISTINCT user_id) as active_users,\n  COUNT(*) as total_events\nFROM events\nWHERE\n  created_at >= DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH)\n  AND event_type = 'login'\nGROUP BY 1\nORDER BY 1 DESC;\n```\n\n## Analysis Checklist\n\n- [ ] Requirements understood\n- [ ] Query optimized\n- [ ] Results validated\n- [ ] Findings documented\n- [ ] Recommendations provided\n"
  },
  {
    "path": "04-subagents/debugger.md",
    "content": "---\nname: debugger\ndescription: Debugging specialist for errors, test failures, and unexpected behavior. Use PROACTIVELY when encountering any issues.\ntools: Read, Edit, Bash, Grep, Glob\nmodel: inherit\n---\n\n# Debugger Agent\n\nYou are an expert debugger specializing in root cause analysis.\n\nWhen invoked:\n1. Capture error message and stack trace\n2. Identify reproduction steps\n3. Isolate the failure location\n4. Implement minimal fix\n5. Verify solution works\n\n## Debugging Process\n\n1. **Analyze error messages and logs**\n   - Read the full error message\n   - Examine stack traces\n   - Check recent log output\n\n2. **Check recent code changes**\n   - Run git diff to see modifications\n   - Identify potentially breaking changes\n   - Review commit history\n\n3. **Form and test hypotheses**\n   - Start with most likely cause\n   - Add strategic debug logging\n   - Inspect variable states\n\n4. **Isolate the failure**\n   - Narrow down to specific function/line\n   - Create minimal reproduction case\n   - Verify the isolation\n\n5. **Implement and verify fix**\n   - Make minimal necessary changes\n   - Run tests to confirm fix\n   - Check for regressions\n\n## Debug Output Format\n\nFor each issue investigated:\n- **Error**: Original error message\n- **Root Cause**: Explanation of why it failed\n- **Evidence**: How you determined the cause\n- **Fix**: Specific code changes made\n- **Testing**: How the fix was verified\n- **Prevention**: Recommendations to prevent recurrence\n\n## Common Debug Commands\n\n```bash\n# Check recent changes\ngit diff HEAD~3\n\n# Search for error patterns\ngrep -r \"error\" --include=\"*.log\"\n\n# Find related code\ngrep -r \"functionName\" --include=\"*.ts\"\n\n# Run specific test\nnpm test -- --grep \"test name\"\n```\n\n## Investigation Checklist\n\n- [ ] Error message captured\n- [ ] Stack trace analyzed\n- [ ] Recent changes reviewed\n- [ ] Root cause identified\n- [ ] Fix implemented\n- [ ] Tests pass\n- [ ] No regressions introduced\n"
  },
  {
    "path": "04-subagents/documentation-writer.md",
    "content": "---\nname: documentation-writer\ndescription: Technical documentation specialist for API docs, user guides, and architecture documentation.\ntools: Read, Write, Grep\nmodel: inherit\n---\n\n# Documentation Writer Agent\n\nYou are a technical writer creating clear, comprehensive documentation.\n\nWhen invoked:\n1. Analyze the code or feature to document\n2. Identify the target audience\n3. Create documentation following project conventions\n4. Verify accuracy against actual code\n\n## Documentation Types\n\n- API documentation with examples\n- User guides and tutorials\n- Architecture documentation\n- Changelog entries\n- Code comment improvements\n\n## Documentation Standards\n\n1. **Clarity** - Use simple, clear language\n2. **Examples** - Include practical code examples\n3. **Completeness** - Cover all parameters and returns\n4. **Structure** - Use consistent formatting\n5. **Accuracy** - Verify against actual code\n\n## Documentation Sections\n\n### For APIs\n\n- Description\n- Parameters (with types)\n- Returns (with types)\n- Throws (possible errors)\n- Examples (curl, JavaScript, Python)\n- Related endpoints\n\n### For Features\n\n- Overview\n- Prerequisites\n- Step-by-step instructions\n- Expected outcomes\n- Troubleshooting\n- Related topics\n\n## Output Format\n\nFor each documentation created:\n- **Type**: API / Guide / Architecture / Changelog\n- **File**: Documentation file path\n- **Sections**: List of sections covered\n- **Examples**: Number of code examples included\n\n## API Documentation Example\n\n```markdown\n## GET /api/users/:id\n\nRetrieves a user by their unique identifier.\n\n### Parameters\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| id | string | Yes | The user's unique identifier |\n\n### Response\n\n```json\n{\n  \"id\": \"abc123\",\n  \"name\": \"John Doe\",\n  \"email\": \"john@example.com\"\n}\n```\n\n### Errors\n\n| Code | Description |\n|------|-------------|\n| 404 | User not found |\n| 401 | Unauthorized |\n\n### Example\n\n```bash\ncurl -X GET https://api.example.com/api/users/abc123 \\\n  -H \"Authorization: Bearer <token>\"\n```\n```\n"
  },
  {
    "path": "04-subagents/implementation-agent.md",
    "content": "---\nname: implementation-agent\ndescription: Full-stack implementation specialist for feature development. Has complete tool access for end-to-end implementation.\ntools: Read, Write, Edit, Bash, Grep, Glob\nmodel: inherit\n---\n\n# Implementation Agent\n\nYou are a senior developer implementing features from specifications.\n\nThis agent has full capabilities:\n- Read specifications and existing code\n- Write new code files\n- Edit existing files\n- Run build commands\n- Search codebase\n- Find files matching patterns\n\n## Implementation Process\n\nWhen invoked:\n1. Understand the requirements fully\n2. Analyze existing codebase patterns\n3. Plan the implementation approach\n4. Implement incrementally\n5. Test as you go\n6. Clean up and refactor\n\n## Implementation Guidelines\n\n### Code Quality\n\n- Follow existing project conventions\n- Write self-documenting code\n- Add comments only where logic is complex\n- Keep functions small and focused\n- Use meaningful variable names\n\n### File Organization\n\n- Place files according to project structure\n- Group related functionality\n- Follow naming conventions\n- Avoid deeply nested directories\n\n### Error Handling\n\n- Handle all error cases\n- Provide meaningful error messages\n- Log errors appropriately\n- Fail gracefully\n\n### Testing\n\n- Write tests for new functionality\n- Ensure existing tests pass\n- Cover edge cases\n- Include integration tests for APIs\n\n## Output Format\n\nFor each implementation task:\n- **Files Created**: List of new files\n- **Files Modified**: List of changed files\n- **Tests Added**: Test file paths\n- **Build Status**: Pass/Fail\n- **Notes**: Any important considerations\n\n## Implementation Checklist\n\nBefore marking complete:\n- [ ] Code follows project conventions\n- [ ] All tests pass\n- [ ] Build succeeds\n- [ ] No linting errors\n- [ ] Edge cases handled\n- [ ] Error handling implemented\n"
  },
  {
    "path": "04-subagents/secure-reviewer.md",
    "content": "---\nname: secure-reviewer\ndescription: Security-focused code review specialist with minimal permissions. Read-only access ensures safe security audits.\ntools: Read, Grep\nmodel: inherit\n---\n\n# Secure Code Reviewer\n\nYou are a security specialist focused exclusively on identifying vulnerabilities.\n\nThis agent has minimal permissions by design:\n- Can read files to analyze\n- Can search for patterns\n- Cannot execute code\n- Cannot modify files\n- Cannot run tests\n\nThis ensures the reviewer cannot accidentally break anything during security audits.\n\n## Security Review Focus\n\n1. **Authentication Issues**\n   - Weak password policies\n   - Missing multi-factor authentication\n   - Session management flaws\n\n2. **Authorization Issues**\n   - Broken access control\n   - Privilege escalation\n   - Missing role checks\n\n3. **Data Exposure**\n   - Sensitive data in logs\n   - Unencrypted storage\n   - API key exposure\n   - PII handling\n\n4. **Injection Vulnerabilities**\n   - SQL injection\n   - Command injection\n   - XSS (Cross-Site Scripting)\n   - LDAP injection\n\n5. **Configuration Issues**\n   - Debug mode in production\n   - Default credentials\n   - Insecure defaults\n\n## Patterns to Search\n\n```bash\n# Hardcoded secrets\ngrep -r \"password\\s*=\" --include=\"*.js\" --include=\"*.ts\"\ngrep -r \"api_key\\s*=\" --include=\"*.py\"\ngrep -r \"SECRET\" --include=\"*.env*\"\n\n# SQL injection risks\ngrep -r \"query.*\\$\" --include=\"*.js\"\ngrep -r \"execute.*%\" --include=\"*.py\"\n\n# Command injection risks\ngrep -r \"exec(\" --include=\"*.js\"\ngrep -r \"os.system\" --include=\"*.py\"\n```\n\n## Output Format\n\nFor each vulnerability:\n- **Severity**: Critical / High / Medium / Low\n- **Type**: OWASP category\n- **Location**: File path and line number\n- **Description**: What the vulnerability is\n- **Risk**: Potential impact if exploited\n- **Remediation**: How to fix it\n"
  },
  {
    "path": "04-subagents/test-engineer.md",
    "content": "---\nname: test-engineer\ndescription: Test automation expert for writing comprehensive tests. Use PROACTIVELY when new features are implemented or code is modified.\ntools: Read, Write, Bash, Grep\nmodel: inherit\n---\n\n# Test Engineer Agent\n\nYou are an expert test engineer specializing in comprehensive test coverage.\n\nWhen invoked:\n1. Analyze the code that needs testing\n2. Identify critical paths and edge cases\n3. Write tests following project conventions\n4. Run tests to verify they pass\n\n## Testing Strategy\n\n1. **Unit Tests** - Individual functions/methods in isolation\n2. **Integration Tests** - Component interactions\n3. **End-to-End Tests** - Complete workflows\n4. **Edge Cases** - Boundary conditions, null values, empty collections\n5. **Error Scenarios** - Failure handling, invalid inputs\n\n## Test Requirements\n\n- Use the project's existing test framework (Jest, pytest, etc.)\n- Include setup/teardown for each test\n- Mock external dependencies\n- Document test purpose with clear descriptions\n- Include performance assertions when relevant\n\n## Coverage Requirements\n\n- Minimum 80% code coverage\n- 100% for critical paths (auth, payments, data handling)\n- Report missing coverage areas\n\n## Test Output Format\n\nFor each test file created:\n- **File**: Test file path\n- **Tests**: Number of test cases\n- **Coverage**: Estimated coverage improvement\n- **Critical Paths**: Which critical paths are covered\n\n## Test Structure Example\n\n```javascript\ndescribe('Feature: User Authentication', () => {\n  beforeEach(() => {\n    // Setup\n  });\n\n  afterEach(() => {\n    // Cleanup\n  });\n\n  it('should authenticate valid credentials', async () => {\n    // Arrange\n    // Act\n    // Assert\n  });\n\n  it('should reject invalid credentials', async () => {\n    // Test error case\n  });\n\n  it('should handle edge case: empty password', async () => {\n    // Test edge case\n  });\n});\n```\n"
  },
  {
    "path": "05-mcp/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# MCP (Model Context Protocol)\n\nThis folder contains comprehensive documentation and examples for MCP server configurations and usage with Claude Code.\n\n## Overview\n\nMCP (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.\n\nKey characteristics:\n- Real-time access to external services\n- Live data synchronization\n- Extensible architecture\n- Secure authentication\n- Tool-based interactions\n\n## MCP Architecture\n\n```mermaid\ngraph TB\n    A[\"Claude\"]\n    B[\"MCP Server\"]\n    C[\"External Service\"]\n\n    A -->|Request: list_issues| B\n    B -->|Query| C\n    C -->|Data| B\n    B -->|Response| A\n\n    A -->|Request: create_issue| B\n    B -->|Action| C\n    C -->|Result| B\n    B -->|Response| A\n\n    style A fill:#e1f5fe,stroke:#333,color:#333\n    style B fill:#f3e5f5,stroke:#333,color:#333\n    style C fill:#e8f5e9,stroke:#333,color:#333\n```\n\n## MCP Ecosystem\n\n```mermaid\ngraph TB\n    A[\"Claude\"] -->|MCP| B[\"Filesystem<br/>MCP Server\"]\n    A -->|MCP| C[\"GitHub<br/>MCP Server\"]\n    A -->|MCP| D[\"Database<br/>MCP Server\"]\n    A -->|MCP| E[\"Slack<br/>MCP Server\"]\n    A -->|MCP| F[\"Google Docs<br/>MCP Server\"]\n\n    B -->|File I/O| G[\"Local Files\"]\n    C -->|API| H[\"GitHub Repos\"]\n    D -->|Query| I[\"PostgreSQL/MySQL\"]\n    E -->|Messages| J[\"Slack Workspace\"]\n    F -->|Docs| K[\"Google Drive\"]\n\n    style A fill:#e1f5fe,stroke:#333,color:#333\n    style B fill:#f3e5f5,stroke:#333,color:#333\n    style C fill:#f3e5f5,stroke:#333,color:#333\n    style D fill:#f3e5f5,stroke:#333,color:#333\n    style E fill:#f3e5f5,stroke:#333,color:#333\n    style F fill:#f3e5f5,stroke:#333,color:#333\n    style G fill:#e8f5e9,stroke:#333,color:#333\n    style H fill:#e8f5e9,stroke:#333,color:#333\n    style I fill:#e8f5e9,stroke:#333,color:#333\n    style J fill:#e8f5e9,stroke:#333,color:#333\n    style K fill:#e8f5e9,stroke:#333,color:#333\n```\n\n## MCP Installation Methods\n\nClaude Code supports multiple transport protocols for MCP server connections:\n\n### HTTP Transport (Recommended)\n\n```bash\n# Basic HTTP connection\nclaude mcp add --transport http notion https://mcp.notion.com/mcp\n\n# HTTP with authentication header\nclaude mcp add --transport http secure-api https://api.example.com/mcp \\\n  --header \"Authorization: Bearer your-token\"\n```\n\n### Stdio Transport (Local)\n\nFor locally running MCP servers:\n\n```bash\n# Local Node.js server\nclaude mcp add --transport stdio myserver -- npx @myorg/mcp-server\n\n# With environment variables\nclaude mcp add --transport stdio myserver --env KEY=value -- npx server\n```\n\n### SSE Transport (Deprecated)\n\nServer-Sent Events transport is deprecated in favor of `http` but still supported:\n\n```bash\nclaude mcp add --transport sse legacy-server https://example.com/sse\n```\n\n### WebSocket Transport\n\nWebSocket transport for persistent bidirectional connections:\n\n```bash\nclaude mcp add --transport ws realtime-server wss://example.com/mcp\n```\n\n### Windows-Specific Note\n\nOn native Windows (not WSL), use `cmd /c` for npx commands:\n\n```bash\nclaude mcp add --transport stdio my-server -- cmd /c npx -y @some/package\n```\n\n### OAuth 2.0 Authentication\n\nClaude Code supports OAuth 2.0 for MCP servers that require it. When connecting to an OAuth-enabled server, Claude Code handles the entire authentication flow:\n\n```bash\n# Connect to an OAuth-enabled MCP server (interactive flow)\nclaude mcp add --transport http my-service https://my-service.example.com/mcp\n\n# Pre-configure OAuth credentials for non-interactive setup\nclaude mcp add --transport http my-service https://my-service.example.com/mcp \\\n  --client-id \"your-client-id\" \\\n  --client-secret \"your-client-secret\" \\\n  --callback-port 8080\n```\n\n| Feature | Description |\n|---------|-------------|\n| **Interactive OAuth** | Use `/mcp` to trigger the browser-based OAuth flow |\n| **Pre-configured OAuth clients** | Built-in OAuth clients for common services like Notion, Stripe, and others (v2.1.30+) |\n| **Pre-configured credentials** | `--client-id`, `--client-secret`, `--callback-port` flags for automated setup |\n| **Token storage** | Tokens are stored securely in your system keychain |\n| **Step-up auth** | Supports step-up authentication for privileged operations |\n| **Discovery caching** | OAuth discovery metadata is cached for faster reconnections |\n| **Metadata override** | `oauth.authServerMetadataUrl` in `.mcp.json` to override default OAuth metadata discovery |\n\n#### Overriding OAuth Metadata Discovery\n\nIf your MCP server returns errors on the standard OAuth metadata endpoint (`/.well-known/oauth-authorization-server`) but exposes a working OIDC endpoint, you can tell Claude Code to fetch OAuth metadata from a specific URL. Set `authServerMetadataUrl` in the `oauth` object of your server config:\n\n```json\n{\n  \"mcpServers\": {\n    \"my-server\": {\n      \"type\": \"http\",\n      \"url\": \"https://mcp.example.com/mcp\",\n      \"oauth\": {\n        \"authServerMetadataUrl\": \"https://auth.example.com/.well-known/openid-configuration\"\n      }\n    }\n  }\n}\n```\n\nThe URL must use `https://`. This option requires Claude Code v2.1.64 or later.\n\n### Claude.ai MCP Connectors\n\nMCP servers configured in your Claude.ai account are automatically available in Claude Code. This means any MCP connections you set up through the Claude.ai web interface will be accessible without additional configuration.\n\nClaude.ai MCP connectors are also available in `--print` mode (v2.1.83+), enabling non-interactive and scripted usage.\n\nTo disable Claude.ai MCP servers in Claude Code, set the `ENABLE_CLAUDEAI_MCP_SERVERS` environment variable to `false`:\n\n```bash\nENABLE_CLAUDEAI_MCP_SERVERS=false claude\n```\n\n> **Note:** This feature is only available for users logged in with Claude.ai accounts.\n\n## MCP Setup Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Config as Config File\n    participant Service as External Service\n\n    User->>Claude: Type /mcp\n    Claude->>Claude: List available MCP servers\n    Claude->>User: Show options\n    User->>Claude: Select GitHub MCP\n    Claude->>Config: Update configuration\n    Config->>Claude: Activate connection\n    Claude->>Service: Test connection\n    Service-->>Claude: Authentication successful\n    Claude->>User: ✅ MCP connected!\n```\n\n## MCP Tool Search\n\nWhen MCP tool descriptions exceed 10% of the context window, Claude Code automatically enables tool search to efficiently select the right tools without overwhelming the model context.\n\n| Setting | Value | Description |\n|---------|-------|-------------|\n| `ENABLE_TOOL_SEARCH` | `auto` (default) | Automatically enables when tool descriptions exceed 10% of context |\n| `ENABLE_TOOL_SEARCH` | `auto:<N>` | Automatically enables at a custom threshold of `N` tools |\n| `ENABLE_TOOL_SEARCH` | `true` | Always enabled regardless of tool count |\n| `ENABLE_TOOL_SEARCH` | `false` | Disabled; all tool descriptions sent in full |\n\n> **Note:** Tool search requires Sonnet 4 or later, or Opus 4 or later. Haiku models are not supported for tool search.\n\n## Dynamic Tool Updates\n\nClaude Code supports MCP `list_changed` notifications. When an MCP server dynamically adds, removes, or modifies its available tools, Claude Code receives the update and adjusts its tool list automatically -- no reconnection or restart required.\n\n## MCP Elicitation\n\nMCP servers can request structured input from the user via interactive dialogs (v2.1.49+). This allows an MCP server to ask for additional information mid-workflow -- for example, prompting for a confirmation, selecting from a list of options, or filling in required fields -- adding interactivity to MCP server interactions.\n\n## Tool Description and Instruction Cap\n\nAs of v2.1.84, Claude Code enforces a **2 KB cap** on tool descriptions and instructions per MCP server. This prevents individual servers from consuming excessive context with overly verbose tool definitions, reducing context bloat and keeping interactions efficient.\n\n## MCP Prompts as Slash Commands\n\nMCP servers can expose prompts that appear as slash commands in Claude Code. Prompts are accessible using the naming convention:\n\n```\n/mcp__<server>__<prompt>\n```\n\nFor example, if a server named `github` exposes a prompt called `review`, you can invoke it as `/mcp__github__review`.\n\n## Server Deduplication\n\nWhen the same MCP server is defined at multiple scopes (local, project, user), the local configuration takes precedence. This allows you to override project-level or user-level MCP settings with local customizations without conflicts.\n\n## MCP Resources via @ Mentions\n\nYou can reference MCP resources directly in your prompts using the `@` mention syntax:\n\n```\n@server-name:protocol://resource/path\n```\n\nFor example, to reference a specific database resource:\n\n```\n@database:postgres://mydb/users\n```\n\nThis allows Claude to fetch and include MCP resource content inline as part of the conversation context.\n\n## MCP Scopes\n\nMCP configurations can be stored at different scopes with varying levels of sharing:\n\n| Scope | Location | Description | Shared With | Requires Approval |\n|-------|----------|-------------|-------------|------------------|\n| **Local** (default) | `~/.claude.json` (under project path) | Private to current user, current project only (was called `project` in older versions) | Just you | No |\n| **Project** | `.mcp.json` | Checked into git repository | Team members | Yes (first use) |\n| **User** | `~/.claude.json` | Available across all projects (was called `global` in older versions) | Just you | No |\n\n### Using Project Scope\n\nStore project-specific MCP configurations in `.mcp.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"type\": \"http\",\n      \"url\": \"https://api.github.com/mcp\"\n    }\n  }\n}\n```\n\nTeam members will see an approval prompt on first use of project MCPs.\n\n## MCP Configuration Management\n\n### Adding MCP Servers\n\n```bash\n# Add HTTP-based server\nclaude mcp add --transport http github https://api.github.com/mcp\n\n# Add local stdio server\nclaude mcp add --transport stdio database -- npx @company/db-server\n\n# List all MCP servers\nclaude mcp list\n\n# Get details on specific server\nclaude mcp get github\n\n# Remove an MCP server\nclaude mcp remove github\n\n# Reset project-specific approval choices\nclaude mcp reset-project-choices\n\n# Import from Claude Desktop\nclaude mcp add-from-claude-desktop\n```\n\n## Available MCP Servers Table\n\n| MCP Server | Purpose | Common Tools | Auth | Real-time |\n|------------|---------|--------------|------|-----------|\n| **Filesystem** | File operations | read, write, delete | OS permissions | ✅ Yes |\n| **GitHub** | Repository management | list_prs, create_issue, push | OAuth | ✅ Yes |\n| **Slack** | Team communication | send_message, list_channels | Token | ✅ Yes |\n| **Database** | SQL queries | query, insert, update | Credentials | ✅ Yes |\n| **Google Docs** | Document access | read, write, share | OAuth | ✅ Yes |\n| **Asana** | Project management | create_task, update_status | API Key | ✅ Yes |\n| **Stripe** | Payment data | list_charges, create_invoice | API Key | ✅ Yes |\n| **Memory** | Persistent memory | store, retrieve, delete | Local | ❌ No |\n\n## Practical Examples\n\n### Example 1: GitHub MCP Configuration\n\n**File:** `.mcp.json` (project root)\n\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n**Available GitHub MCP Tools:**\n\n#### Pull Request Management\n- `list_prs` - List all PRs in repository\n- `get_pr` - Get PR details including diff\n- `create_pr` - Create new PR\n- `update_pr` - Update PR description/title\n- `merge_pr` - Merge PR to main branch\n- `review_pr` - Add review comments\n\n**Example request:**\n```\n/mcp__github__get_pr 456\n\n# Returns:\nTitle: Add dark mode support\nAuthor: @alice\nDescription: Implements dark theme using CSS variables\nStatus: OPEN\nReviewers: @bob, @charlie\n```\n\n#### Issue Management\n- `list_issues` - List all issues\n- `get_issue` - Get issue details\n- `create_issue` - Create new issue\n- `close_issue` - Close issue\n- `add_comment` - Add comment to issue\n\n#### Repository Information\n- `get_repo_info` - Repository details\n- `list_files` - File tree structure\n- `get_file_content` - Read file contents\n- `search_code` - Search across codebase\n\n#### Commit Operations\n- `list_commits` - Commit history\n- `get_commit` - Specific commit details\n- `create_commit` - Create new commit\n\n**Setup**:\n```bash\nexport GITHUB_TOKEN=\"your_github_token\"\n# Or use the CLI to add directly:\nclaude mcp add --transport stdio github -- npx @modelcontextprotocol/server-github\n```\n\n### Environment Variable Expansion in Configuration\n\nMCP configurations support environment variable expansion with fallback defaults. The `${VAR}` and `${VAR:-default}` syntax works in the following fields: `command`, `args`, `env`, `url`, and `headers`.\n\n```json\n{\n  \"mcpServers\": {\n    \"api-server\": {\n      \"type\": \"http\",\n      \"url\": \"${API_BASE_URL:-https://api.example.com}/mcp\",\n      \"headers\": {\n        \"Authorization\": \"Bearer ${API_KEY}\",\n        \"X-Custom-Header\": \"${CUSTOM_HEADER:-default-value}\"\n      }\n    },\n    \"local-server\": {\n      \"command\": \"${MCP_BIN_PATH:-npx}\",\n      \"args\": [\"${MCP_PACKAGE:-@company/mcp-server}\"],\n      \"env\": {\n        \"DB_URL\": \"${DATABASE_URL:-postgresql://localhost/dev}\"\n      }\n    }\n  }\n}\n```\n\nVariables are expanded at runtime:\n- `${VAR}` - Uses environment variable, error if not set\n- `${VAR:-default}` - Uses environment variable, falls back to default if not set\n\n### Example 2: Database MCP Setup\n\n**Configuration:**\n\n```json\n{\n  \"mcpServers\": {\n    \"database\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-database\"],\n      \"env\": {\n        \"DATABASE_URL\": \"postgresql://user:pass@localhost/mydb\"\n      }\n    }\n  }\n}\n```\n\n**Example Usage:**\n\n```markdown\nUser: Fetch all users with more than 10 orders\n\nClaude: I'll query your database to find that information.\n\n# Using MCP database tool:\nSELECT u.*, COUNT(o.id) as order_count\nFROM users u\nLEFT JOIN orders o ON u.id = o.user_id\nGROUP BY u.id\nHAVING COUNT(o.id) > 10\nORDER BY order_count DESC;\n\n# Results:\n- Alice: 15 orders\n- Bob: 12 orders\n- Charlie: 11 orders\n```\n\n**Setup**:\n```bash\nexport DATABASE_URL=\"postgresql://user:pass@localhost/mydb\"\n# Or use the CLI to add directly:\nclaude mcp add --transport stdio database -- npx @modelcontextprotocol/server-database\n```\n\n### Example 3: Multi-MCP Workflow\n\n**Scenario: Daily Report Generation**\n\n```markdown\n# Daily Report Workflow using Multiple MCPs\n\n## Setup\n1. GitHub MCP - fetch PR metrics\n2. Database MCP - query sales data\n3. Slack MCP - post report\n4. Filesystem MCP - save report\n\n## Workflow\n\n### Step 1: Fetch GitHub Data\n/mcp__github__list_prs completed:true last:7days\n\nOutput:\n- Total PRs: 42\n- Average merge time: 2.3 hours\n- Review turnaround: 1.1 hours\n\n### Step 2: Query Database\nSELECT COUNT(*) as sales, SUM(amount) as revenue\nFROM orders\nWHERE created_at > NOW() - INTERVAL '1 day'\n\nOutput:\n- Sales: 247\n- Revenue: $12,450\n\n### Step 3: Generate Report\nCombine data into HTML report\n\n### Step 4: Save to Filesystem\nWrite report.html to /reports/\n\n### Step 5: Post to Slack\nSend summary to #daily-reports channel\n\nFinal Output:\n✅ Report generated and posted\n📊 47 PRs merged this week\n💰 $12,450 in daily sales\n```\n\n**Setup**:\n```bash\nexport GITHUB_TOKEN=\"your_github_token\"\nexport DATABASE_URL=\"postgresql://user:pass@localhost/mydb\"\nexport SLACK_TOKEN=\"your_slack_token\"\n# Add each MCP server via the CLI or configure them in .mcp.json\n```\n\n### Example 4: Filesystem MCP Operations\n\n**Configuration:**\n\n```json\n{\n  \"mcpServers\": {\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-filesystem\", \"/home/user/projects\"]\n    }\n  }\n}\n```\n\n**Available Operations:**\n\n| Operation | Command | Purpose |\n|-----------|---------|---------|\n| List files | `ls ~/projects` | Show directory contents |\n| Read file | `cat src/main.ts` | Read file contents |\n| Write file | `create docs/api.md` | Create new file |\n| Edit file | `edit src/app.ts` | Modify file |\n| Search | `grep \"async function\"` | Search in files |\n| Delete | `rm old-file.js` | Delete file |\n\n**Setup**:\n```bash\n# Use the CLI to add directly:\nclaude mcp add --transport stdio filesystem -- npx @modelcontextprotocol/server-filesystem /home/user/projects\n```\n\n## MCP vs Memory: Decision Matrix\n\n```mermaid\ngraph TD\n    A[\"Need external data?\"]\n    A -->|No| B[\"Use Memory\"]\n    A -->|Yes| C[\"Does it change frequently?\"]\n    C -->|No/Rarely| B\n    C -->|Yes/Often| D[\"Use MCP\"]\n\n    B -->|Stores| E[\"Preferences<br/>Context<br/>History\"]\n    D -->|Accesses| F[\"Live APIs<br/>Databases<br/>Services\"]\n\n    style A fill:#fff3e0,stroke:#333,color:#333\n    style B fill:#e1f5fe,stroke:#333,color:#333\n    style C fill:#fff3e0,stroke:#333,color:#333\n    style D fill:#f3e5f5,stroke:#333,color:#333\n    style E fill:#e8f5e9,stroke:#333,color:#333\n    style F fill:#e8f5e9,stroke:#333,color:#333\n```\n\n## Request/Response Pattern\n\n```mermaid\nsequenceDiagram\n    participant App as Claude\n    participant MCP as MCP Server\n    participant DB as Database\n\n    App->>MCP: Request: \"SELECT * FROM users WHERE id=1\"\n    MCP->>DB: Execute query\n    DB-->>MCP: Result set\n    MCP-->>App: Return parsed data\n    App->>App: Process result\n    App->>App: Continue task\n\n    Note over MCP,DB: Real-time access<br/>No caching\n```\n\n## Environment Variables\n\nStore sensitive credentials in environment variables:\n\n```bash\n# ~/.bashrc or ~/.zshrc\nexport GITHUB_TOKEN=\"ghp_xxxxxxxxxxxxx\"\nexport DATABASE_URL=\"postgresql://user:pass@localhost/mydb\"\nexport SLACK_TOKEN=\"xoxb-xxxxxxxxxxxxx\"\n```\n\nThen reference them in MCP config:\n\n```json\n{\n  \"env\": {\n    \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n  }\n}\n```\n\n## Claude as MCP Server (`claude mcp serve`)\n\nClaude Code itself can act as an MCP server for other applications. This enables external tools, editors, and automation systems to leverage Claude's capabilities through the standard MCP protocol.\n\n```bash\n# Start Claude Code as an MCP server on stdio\nclaude mcp serve\n```\n\nOther applications can then connect to this server as they would any stdio-based MCP server. For example, to add Claude Code as an MCP server in another Claude Code instance:\n\n```bash\nclaude mcp add --transport stdio claude-agent -- claude mcp serve\n```\n\nThis is useful for building multi-agent workflows where one Claude instance orchestrates another.\n\n## Managed MCP Configuration (Enterprise)\n\nFor enterprise deployments, IT administrators can enforce MCP server policies through the `managed-mcp.json` configuration file. This file provides exclusive control over which MCP servers are permitted or blocked organization-wide.\n\n**Location:**\n- macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`\n- Linux: `~/.config/ClaudeCode/managed-mcp.json`\n- Windows: `%APPDATA%\\ClaudeCode\\managed-mcp.json`\n\n**Features:**\n- `allowedMcpServers` -- whitelist of permitted servers\n- `deniedMcpServers` -- blocklist of prohibited servers\n- Supports matching by server name, command, and URL patterns\n- Organization-wide MCP policies enforced before user configuration\n- Prevents unauthorized server connections\n\n**Example configuration:**\n\n```json\n{\n  \"allowedMcpServers\": [\n    {\n      \"serverName\": \"github\",\n      \"serverUrl\": \"https://api.github.com/mcp\"\n    },\n    {\n      \"serverName\": \"company-internal\",\n      \"serverCommand\": \"company-mcp-server\"\n    }\n  ],\n  \"deniedMcpServers\": [\n    {\n      \"serverName\": \"untrusted-*\"\n    },\n    {\n      \"serverUrl\": \"http://*\"\n    }\n  ]\n}\n```\n\n> **Note:** When both `allowedMcpServers` and `deniedMcpServers` match a server, the deny rule takes precedence.\n\n## Plugin-Provided MCP Servers\n\nPlugins can bundle their own MCP servers, making them available automatically when the plugin is installed. Plugin-provided MCP servers can be defined in two ways:\n\n1. **Standalone `.mcp.json`** -- Place a `.mcp.json` file in the plugin root directory\n2. **Inline in `plugin.json`** -- Define MCP servers directly within the plugin manifest\n\nUse the `${CLAUDE_PLUGIN_ROOT}` variable to reference paths relative to the plugin's installation directory:\n\n```json\n{\n  \"mcpServers\": {\n    \"plugin-tools\": {\n      \"command\": \"node\",\n      \"args\": [\"${CLAUDE_PLUGIN_ROOT}/dist/mcp-server.js\"],\n      \"env\": {\n        \"CONFIG_PATH\": \"${CLAUDE_PLUGIN_ROOT}/config.json\"\n      }\n    }\n  }\n}\n```\n\n## Subagent-Scoped MCP\n\nMCP servers can be defined inline within agent frontmatter using the `mcpServers:` key, scoping them to a specific subagent rather than the entire project. This is useful when an agent needs access to a particular MCP server that other agents in the workflow do not require.\n\n```yaml\n---\nmcpServers:\n  my-tool:\n    type: http\n    url: https://my-tool.example.com/mcp\n---\n\nYou are an agent with access to my-tool for specialized operations.\n```\n\nSubagent-scoped MCP servers are only available within that agent's execution context and are not shared with the parent or sibling agents.\n\n## MCP Output Limits\n\nClaude Code enforces limits on MCP tool output to prevent context overflow:\n\n| Limit | Threshold | Behavior |\n|-------|-----------|----------|\n| **Warning** | 10,000 tokens | A warning is displayed that the output is large |\n| **Default max** | 25,000 tokens | Output is truncated beyond this limit |\n| **Disk persistence** | 50,000 characters | Tool results exceeding 50K characters are persisted to disk |\n\nThe maximum output limit is configurable via the `MAX_MCP_OUTPUT_TOKENS` environment variable:\n\n```bash\n# Increase the max output to 50,000 tokens\nexport MAX_MCP_OUTPUT_TOKENS=50000\n```\n\n## Solving Context Bloat with Code Execution\n\nAs MCP adoption scales, connecting to dozens of servers with hundreds or thousands of tools creates a significant challenge: **context bloat**. This is arguably the biggest problem with MCP at scale, and Anthropic's engineering team has proposed an elegant solution — using code execution instead of direct tool calls.\n\n> **Source**: [Code Execution with MCP: Building More Efficient Agents](https://www.anthropic.com/engineering/code-execution-with-mcp) — Anthropic Engineering Blog\n\n### The Problem: Two Sources of Token Waste\n\n**1. Tool definitions overload the context window**\n\nMost MCP clients load all tool definitions upfront. When connected to thousands of tools, the model must process hundreds of thousands of tokens before it even reads the user's request.\n\n**2. Intermediate results consume additional tokens**\n\nEvery intermediate tool result passes through the model's context. Consider transferring a meeting transcript from Google Drive to Salesforce — the full transcript flows through context **twice**: once when reading it, and again when writing it to the destination. A 2-hour meeting transcript could mean 50,000+ extra tokens.\n\n```mermaid\ngraph LR\n    A[\"Model\"] -->|\"Tool Call: getDocument\"| B[\"MCP Server\"]\n    B -->|\"Full transcript (50K tokens)\"| A\n    A -->|\"Tool Call: updateRecord<br/>(re-sends full transcript)\"| B\n    B -->|\"Confirmation\"| A\n\n    style A fill:#ffcdd2,stroke:#333,color:#333\n    style B fill:#f3e5f5,stroke:#333,color:#333\n```\n\n### The Solution: MCP Tools as Code APIs\n\nInstead of passing tool definitions and results through the context window, the agent **writes code** that calls MCP tools as APIs. The code runs in a sandboxed execution environment, and only the final result returns to the model.\n\n```mermaid\ngraph LR\n    A[\"Model\"] -->|\"Writes code\"| B[\"Code Execution<br/>Environment\"]\n    B -->|\"Calls tools directly\"| C[\"MCP Servers\"]\n    C -->|\"Data stays in<br/>execution env\"| B\n    B -->|\"Only final result<br/>(minimal tokens)\"| A\n\n    style A fill:#c8e6c9,stroke:#333,color:#333\n    style B fill:#e1f5fe,stroke:#333,color:#333\n    style C fill:#f3e5f5,stroke:#333,color:#333\n```\n\n#### How It Works\n\nMCP tools are presented as a file tree of typed functions:\n\n```\nservers/\n├── google-drive/\n│   ├── getDocument.ts\n│   └── index.ts\n├── salesforce/\n│   ├── updateRecord.ts\n│   └── index.ts\n└── ...\n```\n\nEach tool file contains a typed wrapper:\n\n```typescript\n// ./servers/google-drive/getDocument.ts\nimport { callMCPTool } from \"../../../client.js\";\n\ninterface GetDocumentInput {\n  documentId: string;\n}\n\ninterface GetDocumentResponse {\n  content: string;\n}\n\nexport async function getDocument(\n  input: GetDocumentInput\n): Promise<GetDocumentResponse> {\n  return callMCPTool<GetDocumentResponse>(\n    'google_drive__get_document', input\n  );\n}\n```\n\nThe agent then writes code to orchestrate the tools:\n\n```typescript\nimport * as gdrive from './servers/google-drive';\nimport * as salesforce from './servers/salesforce';\n\n// Data flows directly between tools — never through the model\nconst transcript = (\n  await gdrive.getDocument({ documentId: 'abc123' })\n).content;\n\nawait salesforce.updateRecord({\n  objectType: 'SalesMeeting',\n  recordId: '00Q5f000001abcXYZ',\n  data: { Notes: transcript }\n});\n```\n\n**Result: Token usage drops from ~150,000 to ~2,000 — a 98.7% reduction.**\n\n### Key Benefits\n\n| Benefit | Description |\n|---------|-------------|\n| **Progressive Disclosure** | Agent browses the filesystem to load only the tool definitions it needs, instead of all tools upfront |\n| **Context-Efficient Results** | Data is filtered/transformed in the execution environment before returning to the model |\n| **Powerful Control Flow** | Loops, conditionals, and error handling run in code without round-tripping through the model |\n| **Privacy Preservation** | Intermediate data (PII, sensitive records) stays in the execution environment; never enters the model context |\n| **State Persistence** | Agents can save intermediate results to files and build reusable skill functions |\n\n#### Example: Filtering Large Datasets\n\n```typescript\n// Without code execution — all 10,000 rows flow through context\n// TOOL CALL: gdrive.getSheet(sheetId: 'abc123')\n//   -> returns 10,000 rows in context\n\n// With code execution — filter in the execution environment\nconst allRows = await gdrive.getSheet({ sheetId: 'abc123' });\nconst pendingOrders = allRows.filter(\n  row => row[\"Status\"] === 'pending'\n);\nconsole.log(`Found ${pendingOrders.length} pending orders`);\nconsole.log(pendingOrders.slice(0, 5)); // Only 5 rows reach the model\n```\n\n#### Example: Loop Without Round-Tripping\n\n```typescript\n// Poll for a deployment notification — runs entirely in code\nlet found = false;\nwhile (!found) {\n  const messages = await slack.getChannelHistory({\n    channel: 'C123456'\n  });\n  found = messages.some(\n    m => m.text.includes('deployment complete')\n  );\n  if (!found) await new Promise(r => setTimeout(r, 5000));\n}\nconsole.log('Deployment notification received');\n```\n\n### Trade-offs to Consider\n\nCode execution introduces its own complexity. Running agent-generated code requires:\n\n- A **secure sandboxed execution environment** with appropriate resource limits\n- **Monitoring and logging** of executed code\n- Additional **infrastructure overhead** compared to direct tool calls\n\nThe benefits — reduced token costs, lower latency, improved tool composition — should be weighed against these implementation costs. For agents with only a few MCP servers, direct tool calls may be simpler. For agents at scale (dozens of servers, hundreds of tools), code execution is a significant improvement.\n\n### MCPorter: A Runtime for MCP Tool Composition\n\n[MCPorter](https://github.com/steipete/mcporter) is a TypeScript runtime and CLI toolkit that makes calling MCP servers practical without boilerplate — and helps reduce context bloat through selective tool exposure and typed wrappers.\n\n**What it solves:** Instead of loading all tool definitions from all MCP servers upfront, MCPorter lets you discover, inspect, and call specific tools on demand — keeping your context lean.\n\n**Key features:**\n\n| Feature | Description |\n|---------|-------------|\n| **Zero-config discovery** | Auto-discovers MCP servers from Cursor, Claude, Codex, or local configs |\n| **Typed tool clients** | `mcporter emit-ts` generates `.d.ts` interfaces and ready-to-run wrappers |\n| **Composable API** | `createServerProxy()` exposes tools as camelCase methods with `.text()`, `.json()`, `.markdown()` helpers |\n| **CLI generation** | `mcporter generate-cli` converts any MCP server into a standalone CLI with `--include-tools` / `--exclude-tools` filtering |\n| **Parameter hiding** | Optional parameters stay hidden by default, reducing schema verbosity |\n\n**Installation:**\n\n```bash\nnpx mcporter list          # No install required — discover servers instantly\npnpm add mcporter          # Add to a project\nbrew install steipete/tap/mcporter  # macOS via Homebrew\n```\n\n**Example — composing tools in TypeScript:**\n\n```typescript\nimport { createRuntime, createServerProxy } from \"mcporter\";\n\nconst runtime = await createRuntime();\nconst gdrive = createServerProxy(runtime, \"google-drive\");\nconst salesforce = createServerProxy(runtime, \"salesforce\");\n\n// Data flows between tools without passing through the model context\nconst doc = await gdrive.getDocument({ documentId: \"abc123\" });\nawait salesforce.updateRecord({\n  objectType: \"SalesMeeting\",\n  recordId: \"00Q5f000001abcXYZ\",\n  data: { Notes: doc.text() }\n});\n```\n\n**Example — CLI tool call:**\n\n```bash\n# Call a specific tool directly\nnpx mcporter call linear.create_comment issueId:ENG-123 body:'Looks good!'\n\n# List available servers and tools\nnpx mcporter list\n```\n\nMCPorter complements the code-execution approach described above by providing the runtime infrastructure for calling MCP tools as typed APIs — making it straightforward to keep intermediate data out of the model context.\n\n## Best Practices\n\n### Security Considerations\n\n#### Do's ✅\n- Use environment variables for all credentials\n- Rotate tokens and API keys regularly (monthly recommended)\n- Use read-only tokens when possible\n- Limit MCP server access scope to minimum required\n- Monitor MCP server usage and access logs\n- Use OAuth for external services when available\n- Implement rate limiting on MCP requests\n- Test MCP connections before production use\n- Document all active MCP connections\n- Keep MCP server packages updated\n\n#### Don'ts ❌\n- Don't hardcode credentials in config files\n- Don't commit tokens or secrets to git\n- Don't share tokens in team chats or emails\n- Don't use personal tokens for team projects\n- Don't grant unnecessary permissions\n- Don't ignore authentication errors\n- Don't expose MCP endpoints publicly\n- Don't run MCP servers with root/admin privileges\n- Don't cache sensitive data in logs\n- Don't disable authentication mechanisms\n\n### Configuration Best Practices\n\n1. **Version Control**: Keep `.mcp.json` in git but use environment variables for secrets\n2. **Least Privilege**: Grant minimum permissions needed for each MCP server\n3. **Isolation**: Run different MCP servers in separate processes when possible\n4. **Monitoring**: Log all MCP requests and errors for audit trails\n5. **Testing**: Test all MCP configurations before deploying to production\n\n### Performance Tips\n\n- Cache frequently accessed data at the application level\n- Use MCP queries that are specific to reduce data transfer\n- Monitor response times for MCP operations\n- Consider rate limiting for external APIs\n- Use batching when performing multiple operations\n\n## Installation Instructions\n\n### Prerequisites\n- Node.js and npm installed\n- Claude Code CLI installed\n- API tokens/credentials for external services\n\n### Step-by-Step Setup\n\n1. **Add your first MCP server** using the CLI (example: GitHub):\n```bash\nclaude mcp add --transport stdio github -- npx @modelcontextprotocol/server-github\n```\n\n   Or create a `.mcp.json` file in your project root:\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n2. **Set environment variables:**\n```bash\nexport GITHUB_TOKEN=\"your_github_personal_access_token\"\n```\n\n3. **Test the connection:**\n```bash\nclaude /mcp\n```\n\n4. **Use MCP tools:**\n```bash\n/mcp__github__list_prs\n/mcp__github__create_issue \"Title\" \"Description\"\n```\n\n### Installation for Specific Services\n\n**GitHub MCP:**\n```bash\nnpm install -g @modelcontextprotocol/server-github\n```\n\n**Database MCP:**\n```bash\nnpm install -g @modelcontextprotocol/server-database\n```\n\n**Filesystem MCP:**\n```bash\nnpm install -g @modelcontextprotocol/server-filesystem\n```\n\n**Slack MCP:**\n```bash\nnpm install -g @modelcontextprotocol/server-slack\n```\n\n## Troubleshooting\n\n### MCP Server Not Found\n```bash\n# Verify MCP server is installed\nnpm list -g @modelcontextprotocol/server-github\n\n# Install if missing\nnpm install -g @modelcontextprotocol/server-github\n```\n\n### Authentication Failed\n```bash\n# Verify environment variable is set\necho $GITHUB_TOKEN\n\n# Re-export if needed\nexport GITHUB_TOKEN=\"your_token\"\n\n# Verify token has correct permissions\n# Check GitHub token scopes at: https://github.com/settings/tokens\n```\n\n### Connection Timeout\n- Check network connectivity: `ping api.github.com`\n- Verify API endpoint is accessible\n- Check rate limits on API\n- Try increasing timeout in config\n- Check for firewall or proxy issues\n\n### MCP Server Crashes\n- Check MCP server logs: `~/.claude/logs/`\n- Verify all environment variables are set\n- Ensure proper file permissions\n- Try reinstalling the MCP server package\n- Check for conflicting processes on the same port\n\n## Related Concepts\n\n### Memory vs MCP\n- **Memory**: Stores persistent, unchanging data (preferences, context, history)\n- **MCP**: Accesses live, changing data (APIs, databases, real-time services)\n\n### When to Use Each\n- **Use Memory** for: User preferences, conversation history, learned context\n- **Use MCP** for: Current GitHub issues, live database queries, real-time data\n\n### Integration with Other Claude Features\n- Combine MCP with Memory for rich context\n- Use MCP tools in prompts for better reasoning\n- Leverage multiple MCPs for complex workflows\n\n## Additional Resources\n\n- [Official MCP Documentation](https://code.claude.com/docs/en/mcp)\n- [MCP Protocol Specification](https://modelcontextprotocol.io/specification)\n- [MCP GitHub Repository](https://github.com/modelcontextprotocol/servers)\n- [Available MCP Servers](https://github.com/modelcontextprotocol/servers)\n- [MCPorter](https://github.com/steipete/mcporter) — TypeScript runtime & CLI for calling MCP servers without boilerplate\n- [Code Execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp) — Anthropic's engineering blog on solving context bloat\n- [Claude Code CLI Reference](https://code.claude.com/docs/en/cli-reference)\n- [Claude API Documentation](https://docs.anthropic.com)\n"
  },
  {
    "path": "05-mcp/database-mcp.json",
    "content": "{\n  \"mcpServers\": {\n    \"database\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-database\"],\n      \"env\": {\n        \"DATABASE_URL\": \"postgresql://user:pass@localhost/mydb\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "05-mcp/filesystem-mcp.json",
    "content": "{\n  \"mcpServers\": {\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-filesystem\", \"/home/user/projects\"]\n    }\n  }\n}\n"
  },
  {
    "path": "05-mcp/github-mcp.json",
    "content": "{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "05-mcp/multi-mcp.json",
    "content": "{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    },\n    \"database\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-database\"],\n      \"env\": {\n        \"DATABASE_URL\": \"${DATABASE_URL}\"\n      }\n    },\n    \"slack\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-slack\"],\n      \"env\": {\n        \"SLACK_TOKEN\": \"${SLACK_TOKEN}\"\n      }\n    },\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-filesystem\", \"/home/user/projects\"]\n    }\n  }\n}\n"
  },
  {
    "path": "06-hooks/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Hooks\n\nHooks are automated scripts that execute in response to specific events during Claude Code sessions. They enable automation, validation, permission management, and custom workflows.\n\n## Overview\n\nHooks are automated actions (shell commands, HTTP webhooks, LLM prompts, or subagent evaluations) that execute automatically when specific events occur in Claude Code. They receive JSON input and communicate results via exit codes and JSON output.\n\n**Key features:**\n- Event-driven automation\n- JSON-based input/output\n- Support for command, prompt, HTTP, and agent hook types\n- Pattern matching for tool-specific hooks\n\n## Configuration\n\nHooks are configured in settings files with a specific structure:\n\n- `~/.claude/settings.json` - User settings (all projects)\n- `.claude/settings.json` - Project settings (shareable, committed)\n- `.claude/settings.local.json` - Local project settings (not committed)\n- Managed policy - Organization-wide settings\n- Plugin `hooks/hooks.json` - Plugin-scoped hooks\n- Skill/Agent frontmatter - Component lifetime hooks\n\n### Basic Configuration Structure\n\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"ToolPattern\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"your-command-here\",\n            \"timeout\": 60\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Key fields:**\n\n| Field | Description | Example |\n|-------|-------------|---------|\n| `matcher` | Pattern to match tool names (case-sensitive) | `\"Write\"`, `\"Edit\\|Write\"`, `\"*\"` |\n| `hooks` | Array of hook definitions | `[{ \"type\": \"command\", ... }]` |\n| `type` | Hook type: `\"command\"` (bash), `\"prompt\"` (LLM), `\"http\"` (webhook), or `\"agent\"` (subagent) | `\"command\"` |\n| `command` | Shell command to execute | `\"$CLAUDE_PROJECT_DIR/.claude/hooks/format.sh\"` |\n| `timeout` | Optional timeout in seconds (default 60) | `30` |\n| `once` | If `true`, run the hook only once per session | `true` |\n\n### Matcher Patterns\n\n| Pattern | Description | Example |\n|---------|-------------|---------|\n| Exact string | Matches specific tool | `\"Write\"` |\n| Regex pattern | Matches multiple tools | `\"Edit\\|Write\"` |\n| Wildcard | Matches all tools | `\"*\"` or `\"\"` |\n| MCP tools | Server and tool pattern | `\"mcp__memory__.*\"` |\n\n## Hook Types\n\nClaude Code supports four hook types:\n\n### Command Hooks\n\nThe default hook type. Executes a shell command and communicates via JSON stdin/stdout and exit codes.\n\n```json\n{\n  \"type\": \"command\",\n  \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/validate.py\\\"\",\n  \"timeout\": 60\n}\n```\n\n### HTTP Hooks\n\n> Added in v2.1.63.\n\nRemote webhook endpoints that receive the same JSON input as command hooks. HTTP hooks POST JSON to the URL and receive a JSON response. HTTP hooks are routed through the sandbox when sandboxing is enabled. Environment variable interpolation in URLs requires an explicit `allowedEnvVars` list for security.\n\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [{\n      \"type\": \"http\",\n      \"url\": \"https://my-webhook.example.com/hook\",\n      \"matcher\": \"Write\"\n    }]\n  }\n}\n```\n\n**Key properties:**\n- `\"type\": \"http\"` -- identifies this as an HTTP hook\n- `\"url\"` -- the webhook endpoint URL\n- Routed through sandbox when sandbox is enabled\n- Requires explicit `allowedEnvVars` list for any environment variable interpolation in the URL\n\n### Prompt Hooks\n\nLLM-evaluated prompts where the hook content is a prompt that Claude evaluates. Primarily used with `Stop` and `SubagentStop` events for intelligent task completion checking.\n\n```json\n{\n  \"type\": \"prompt\",\n  \"prompt\": \"Evaluate if Claude completed all requested tasks.\",\n  \"timeout\": 30\n}\n```\n\nThe LLM evaluates the prompt and returns a structured decision (see [Prompt-Based Hooks](#prompt-based-hooks) for details).\n\n### Agent Hooks\n\nSubagent-based verification hooks that spawn a dedicated agent to evaluate conditions or perform complex checks. Unlike prompt hooks (single-turn LLM evaluation), agent hooks can use tools and perform multi-step reasoning.\n\n```json\n{\n  \"type\": \"agent\",\n  \"prompt\": \"Verify the code changes follow our architecture guidelines. Check the relevant design docs and compare.\",\n  \"timeout\": 120\n}\n```\n\n**Key properties:**\n- `\"type\": \"agent\"` -- identifies this as an agent hook\n- `\"prompt\"` -- the task description for the subagent\n- The agent can use tools (Read, Grep, Bash, etc.) to perform its evaluation\n- Returns a structured decision similar to prompt hooks\n\n## Hook Events\n\nClaude Code supports **25 hook events**:\n\n| Event | When Triggered | Matcher Input | Can Block | Common Use |\n|-------|---------------|---------------|-----------|------------|\n| **SessionStart** | Session begins/resumes/clear/compact | startup/resume/clear/compact | No | Environment setup |\n| **InstructionsLoaded** | After CLAUDE.md or rules file loaded | (none) | No | Modify/filter instructions |\n| **UserPromptSubmit** | User submits prompt | (none) | Yes | Validate prompts |\n| **PreToolUse** | Before tool execution | Tool name | Yes (allow/deny/ask) | Validate, modify inputs |\n| **PermissionRequest** | Permission dialog shown | Tool name | Yes | Auto-approve/deny |\n| **PostToolUse** | After tool succeeds | Tool name | No | Add context, feedback |\n| **PostToolUseFailure** | Tool execution fails | Tool name | No | Error handling, logging |\n| **Notification** | Notification sent | Notification type | No | Custom notifications |\n| **SubagentStart** | Subagent spawned | Agent type name | No | Subagent setup |\n| **SubagentStop** | Subagent finishes | Agent type name | Yes | Subagent validation |\n| **Stop** | Claude finishes responding | (none) | Yes | Task completion check |\n| **StopFailure** | API error ends turn | (none) | No | Error recovery, logging |\n| **TeammateIdle** | Agent team teammate idle | (none) | Yes | Teammate coordination |\n| **TaskCompleted** | Task marked complete | (none) | Yes | Post-task actions |\n| **TaskCreated** | Task created via TaskCreate | (none) | No | Task tracking, logging |\n| **ConfigChange** | Config file changes | (none) | Yes (except policy) | React to config updates |\n| **CwdChanged** | Working directory changes | (none) | No | Directory-specific setup |\n| **FileChanged** | Watched file changes | (none) | No | File monitoring, rebuild |\n| **PreCompact** | Before context compaction | manual/auto | No | Pre-compact actions |\n| **PostCompact** | After compaction completes | (none) | No | Post-compact actions |\n| **WorktreeCreate** | Worktree being created | (none) | Yes (path return) | Worktree initialization |\n| **WorktreeRemove** | Worktree being removed | (none) | No | Worktree cleanup |\n| **Elicitation** | MCP server requests user input | (none) | Yes | Input validation |\n| **ElicitationResult** | User responds to elicitation | (none) | Yes | Response processing |\n| **SessionEnd** | Session terminates | (none) | No | Cleanup, final logging |\n\n### PreToolUse\n\nRuns after Claude creates tool parameters and before processing. Use this to validate or modify tool inputs.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Common matchers:** `Task`, `Bash`, `Glob`, `Grep`, `Read`, `Edit`, `Write`, `WebFetch`, `WebSearch`\n\n**Output control:**\n- `permissionDecision`: `\"allow\"`, `\"deny\"`, or `\"ask\"`\n- `permissionDecisionReason`: Explanation for decision\n- `updatedInput`: Modified tool input parameters\n\n### PostToolUse\n\nRuns immediately after tool completion. Use for verification, logging, or providing context back to Claude.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Write|Edit\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"$CLAUDE_PROJECT_DIR/.claude/hooks/security-scan.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Output control:**\n- `\"block\"` decision prompts Claude with feedback\n- `additionalContext`: Context added for Claude\n\n### UserPromptSubmit\n\nRuns when user submits a prompt, before Claude processes it.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-prompt.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Output control:**\n- `decision`: `\"block\"` to prevent processing\n- `reason`: Explanation if blocked\n- `additionalContext`: Context added to prompt\n\n### Stop and SubagentStop\n\nRun when Claude finishes responding (Stop) or a subagent completes (SubagentStop). Supports prompt-based evaluation for intelligent task completion checking.\n\n**Additional input field:** Both `Stop` and `SubagentStop` hooks receive a `last_assistant_message` field in their JSON input, containing the final message from Claude or the subagent before stopping. This is useful for evaluating task completion.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"prompt\",\n            \"prompt\": \"Evaluate if Claude completed all requested tasks.\",\n            \"timeout\": 30\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### SubagentStart\n\nRuns when a subagent begins execution. The matcher input is the agent type name, allowing hooks to target specific subagent types.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"SubagentStart\": [\n      {\n        \"matcher\": \"code-review\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"$CLAUDE_PROJECT_DIR/.claude/hooks/subagent-init.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### SessionStart\n\nRuns when session starts or resumes. Can persist environment variables.\n\n**Matchers:** `startup`, `resume`, `clear`, `compact`\n\n**Special feature:** Use `CLAUDE_ENV_FILE` to persist environment variables (also available in `CwdChanged` and `FileChanged` hooks):\n\n```bash\n#!/bin/bash\nif [ -n \"$CLAUDE_ENV_FILE\" ]; then\n  echo 'export NODE_ENV=development' >> \"$CLAUDE_ENV_FILE\"\nfi\nexit 0\n```\n\n### SessionEnd\n\nRuns when session ends to perform cleanup or final logging. Cannot block termination.\n\n**Reason field values:**\n- `clear` - User cleared the session\n- `logout` - User logged out\n- `prompt_input_exit` - User exited via prompt input\n- `other` - Other reason\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"SessionEnd\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-cleanup.sh\\\"\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Notification Event\n\nUpdated matchers for notification events:\n- `permission_prompt` - Permission request notification\n- `idle_prompt` - Idle state notification\n- `auth_success` - Authentication success\n- `elicitation_dialog` - Dialog shown to user\n\n## Component-Scoped Hooks\n\nHooks can be attached to specific components (skills, agents, commands) in their frontmatter:\n\n**In SKILL.md, agent.md, or command.md:**\n\n```yaml\n---\nname: secure-operations\ndescription: Perform operations with security checks\nhooks:\n  PreToolUse:\n    - matcher: \"Bash\"\n      hooks:\n        - type: command\n          command: \"./scripts/check.sh\"\n          once: true  # Only run once per session\n---\n```\n\n**Supported events for component hooks:** `PreToolUse`, `PostToolUse`, `Stop`\n\nThis allows defining hooks directly in the component that uses them, keeping related code together.\n\n### Hooks in Subagent Frontmatter\n\nWhen a `Stop` hook is defined in a subagent's frontmatter, it is automatically converted to a `SubagentStop` hook scoped to that subagent. This ensures that the stop hook only fires when that specific subagent completes, rather than when the main session stops.\n\n```yaml\n---\nname: code-review-agent\ndescription: Automated code review subagent\nhooks:\n  Stop:\n    - hooks:\n        - type: prompt\n          prompt: \"Verify the code review is thorough and complete.\"\n  # The above Stop hook auto-converts to SubagentStop for this subagent\n---\n```\n\n## PermissionRequest Event\n\nHandles permission requests with custom output format:\n\n```json\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"PermissionRequest\",\n    \"decision\": {\n      \"behavior\": \"allow|deny\",\n      \"updatedInput\": {},\n      \"message\": \"Custom message\",\n      \"interrupt\": false\n    }\n  }\n}\n```\n\n## Hook Input and Output\n\n### JSON Input (via stdin)\n\nAll hooks receive JSON input via stdin:\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"/path/to/transcript.jsonl\",\n  \"cwd\": \"/current/working/directory\",\n  \"permission_mode\": \"default\",\n  \"hook_event_name\": \"PreToolUse\",\n  \"tool_name\": \"Write\",\n  \"tool_input\": {\n    \"file_path\": \"/path/to/file.js\",\n    \"content\": \"...\"\n  },\n  \"tool_use_id\": \"toolu_01ABC123...\",\n  \"agent_id\": \"agent-abc123\",\n  \"agent_type\": \"main\",\n  \"worktree\": \"/path/to/worktree\"\n}\n```\n\n**Common fields:**\n\n| Field | Description |\n|-------|-------------|\n| `session_id` | Unique session identifier |\n| `transcript_path` | Path to the conversation transcript file |\n| `cwd` | Current working directory |\n| `hook_event_name` | Name of the event that triggered the hook |\n| `agent_id` | Identifier of the agent running this hook |\n| `agent_type` | Type of agent (`\"main\"`, subagent type name, etc.) |\n| `worktree` | Path to the git worktree, if the agent is running in one |\n\n### Exit Codes\n\n| Exit Code | Meaning | Behavior |\n|-----------|---------|----------|\n| **0** | Success | Continue, parse JSON stdout |\n| **2** | Blocking error | Block operation, stderr shown as error |\n| **Other** | Non-blocking error | Continue, stderr shown in verbose mode |\n\n### JSON Output (stdout, exit code 0)\n\n```json\n{\n  \"continue\": true,\n  \"stopReason\": \"Optional message if stopping\",\n  \"suppressOutput\": false,\n  \"systemMessage\": \"Optional warning message\",\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"PreToolUse\",\n    \"permissionDecision\": \"allow\",\n    \"permissionDecisionReason\": \"File is in allowed directory\",\n    \"updatedInput\": {\n      \"file_path\": \"/modified/path.js\"\n    }\n  }\n}\n```\n\n## Environment Variables\n\n| Variable | Availability | Description |\n|----------|-------------|-------------|\n| `CLAUDE_PROJECT_DIR` | All hooks | Absolute path to project root |\n| `CLAUDE_ENV_FILE` | SessionStart, CwdChanged, FileChanged | File path for persisting env vars |\n| `CLAUDE_CODE_REMOTE` | All hooks | `\"true\"` if running in remote environments |\n| `${CLAUDE_PLUGIN_ROOT}` | Plugin hooks | Path to plugin directory |\n| `${CLAUDE_PLUGIN_DATA}` | Plugin hooks | Path to plugin data directory |\n| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | SessionEnd hooks | Configurable timeout in milliseconds for SessionEnd hooks (overrides default) |\n\n## Prompt-Based Hooks\n\nFor `Stop` and `SubagentStop` events, you can use LLM-based evaluation:\n\n```json\n{\n  \"hooks\": {\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"prompt\",\n            \"prompt\": \"Review if all tasks are complete. Return your decision.\",\n            \"timeout\": 30\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**LLM Response Schema:**\n```json\n{\n  \"decision\": \"approve\",\n  \"reason\": \"All tasks completed successfully\",\n  \"continue\": false,\n  \"stopReason\": \"Task complete\"\n}\n```\n\n## Examples\n\n### Example 1: Bash Command Validator (PreToolUse)\n\n**File:** `.claude/hooks/validate-bash.py`\n\n```python\n#!/usr/bin/env python3\nimport json\nimport sys\nimport re\n\nBLOCKED_PATTERNS = [\n    (r\"\\brm\\s+-rf\\s+/\", \"Blocking dangerous rm -rf / command\"),\n    (r\"\\bsudo\\s+rm\", \"Blocking sudo rm command\"),\n]\n\ndef main():\n    input_data = json.load(sys.stdin)\n\n    tool_name = input_data.get(\"tool_name\", \"\")\n    if tool_name != \"Bash\":\n        sys.exit(0)\n\n    command = input_data.get(\"tool_input\", {}).get(\"command\", \"\")\n\n    for pattern, message in BLOCKED_PATTERNS:\n        if re.search(pattern, command):\n            print(message, file=sys.stderr)\n            sys.exit(2)  # Exit 2 = blocking error\n\n    sys.exit(0)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py\\\"\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Example 2: Security Scanner (PostToolUse)\n\n**File:** `.claude/hooks/security-scan.py`\n\n```python\n#!/usr/bin/env python3\nimport json\nimport sys\nimport re\n\nSECRET_PATTERNS = [\n    (r\"password\\s*=\\s*['\\\"][^'\\\"]+['\\\"]\", \"Potential hardcoded password\"),\n    (r\"api[_-]?key\\s*=\\s*['\\\"][^'\\\"]+['\\\"]\", \"Potential hardcoded API key\"),\n]\n\ndef main():\n    input_data = json.load(sys.stdin)\n\n    tool_name = input_data.get(\"tool_name\", \"\")\n    if tool_name not in [\"Write\", \"Edit\"]:\n        sys.exit(0)\n\n    tool_input = input_data.get(\"tool_input\", {})\n    content = tool_input.get(\"content\", \"\") or tool_input.get(\"new_string\", \"\")\n    file_path = tool_input.get(\"file_path\", \"\")\n\n    warnings = []\n    for pattern, message in SECRET_PATTERNS:\n        if re.search(pattern, content, re.IGNORECASE):\n            warnings.append(message)\n\n    if warnings:\n        output = {\n            \"hookSpecificOutput\": {\n                \"hookEventName\": \"PostToolUse\",\n                \"additionalContext\": f\"Security warnings for {file_path}: \" + \"; \".join(warnings)\n            }\n        }\n        print(json.dumps(output))\n\n    sys.exit(0)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### Example 3: Auto-Format Code (PostToolUse)\n\n**File:** `.claude/hooks/format-code.sh`\n\n```bash\n#!/bin/bash\n\n# Read JSON from stdin\nINPUT=$(cat)\nTOOL_NAME=$(echo \"$INPUT\" | python3 -c \"import sys, json; print(json.load(sys.stdin).get('tool_name', ''))\")\nFILE_PATH=$(echo \"$INPUT\" | python3 -c \"import sys, json; print(json.load(sys.stdin).get('tool_input', {}).get('file_path', ''))\")\n\nif [ \"$TOOL_NAME\" != \"Write\" ] && [ \"$TOOL_NAME\" != \"Edit\" ]; then\n    exit 0\nfi\n\n# Format based on file extension\ncase \"$FILE_PATH\" in\n    *.js|*.jsx|*.ts|*.tsx|*.json)\n        command -v prettier &>/dev/null && prettier --write \"$FILE_PATH\" 2>/dev/null\n        ;;\n    *.py)\n        command -v black &>/dev/null && black \"$FILE_PATH\" 2>/dev/null\n        ;;\n    *.go)\n        command -v gofmt &>/dev/null && gofmt -w \"$FILE_PATH\" 2>/dev/null\n        ;;\nesac\n\nexit 0\n```\n\n### Example 4: Prompt Validator (UserPromptSubmit)\n\n**File:** `.claude/hooks/validate-prompt.py`\n\n```python\n#!/usr/bin/env python3\nimport json\nimport sys\nimport re\n\nBLOCKED_PATTERNS = [\n    (r\"delete\\s+(all\\s+)?database\", \"Dangerous: database deletion\"),\n    (r\"rm\\s+-rf\\s+/\", \"Dangerous: root deletion\"),\n]\n\ndef main():\n    input_data = json.load(sys.stdin)\n    prompt = input_data.get(\"user_prompt\", \"\") or input_data.get(\"prompt\", \"\")\n\n    for pattern, message in BLOCKED_PATTERNS:\n        if re.search(pattern, prompt, re.IGNORECASE):\n            output = {\n                \"decision\": \"block\",\n                \"reason\": f\"Blocked: {message}\"\n            }\n            print(json.dumps(output))\n            sys.exit(0)\n\n    sys.exit(0)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### Example 5: Intelligent Stop Hook (Prompt-Based)\n\n```json\n{\n  \"hooks\": {\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"prompt\",\n            \"prompt\": \"Review if Claude completed all requested tasks. Check: 1) Were all files created/modified? 2) Were there unresolved errors? If incomplete, explain what's missing.\",\n            \"timeout\": 30\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Example 6: Context Usage Tracker (Hook Pairs)\n\nTrack token consumption per request using `UserPromptSubmit` (pre-message) and `Stop` (post-response) hooks together.\n\n**File:** `.claude/hooks/context-tracker.py`\n\n```python\n#!/usr/bin/env python3\n\"\"\"\nContext Usage Tracker - Tracks token consumption per request.\n\nUses UserPromptSubmit as \"pre-message\" hook and Stop as \"post-response\" hook\nto calculate the delta in token usage for each request.\n\nToken Counting Methods:\n1. Character estimation (default): ~4 chars per token, no dependencies\n2. tiktoken (optional): More accurate (~90-95%), requires: pip install tiktoken\n\"\"\"\nimport json\nimport os\nimport sys\nimport tempfile\n\n# Configuration\nCONTEXT_LIMIT = 128000  # Claude's context window (adjust for your model)\nUSE_TIKTOKEN = False    # Set True if tiktoken is installed for better accuracy\n\n\ndef get_state_file(session_id: str) -> str:\n    \"\"\"Get temp file path for storing pre-message token count, isolated by session.\"\"\"\n    return os.path.join(tempfile.gettempdir(), f\"claude-context-{session_id}.json\")\n\n\ndef count_tokens(text: str) -> int:\n    \"\"\"\n    Count tokens in text.\n\n    Uses tiktoken with p50k_base encoding if available (~90-95% accuracy),\n    otherwise falls back to character estimation (~80-90% accuracy).\n    \"\"\"\n    if USE_TIKTOKEN:\n        try:\n            import tiktoken\n            enc = tiktoken.get_encoding(\"p50k_base\")\n            return len(enc.encode(text))\n        except ImportError:\n            pass  # Fall back to estimation\n\n    # Character-based estimation: ~4 characters per token for English\n    return len(text) // 4\n\n\ndef read_transcript(transcript_path: str) -> str:\n    \"\"\"Read and concatenate all content from transcript file.\"\"\"\n    if not transcript_path or not os.path.exists(transcript_path):\n        return \"\"\n\n    content = []\n    with open(transcript_path, \"r\") as f:\n        for line in f:\n            try:\n                entry = json.loads(line.strip())\n                # Extract text content from various message formats\n                if \"message\" in entry:\n                    msg = entry[\"message\"]\n                    if isinstance(msg.get(\"content\"), str):\n                        content.append(msg[\"content\"])\n                    elif isinstance(msg.get(\"content\"), list):\n                        for block in msg[\"content\"]:\n                            if isinstance(block, dict) and block.get(\"type\") == \"text\":\n                                content.append(block.get(\"text\", \"\"))\n            except json.JSONDecodeError:\n                continue\n\n    return \"\\n\".join(content)\n\n\ndef handle_user_prompt_submit(data: dict) -> None:\n    \"\"\"Pre-message hook: Save current token count before request.\"\"\"\n    session_id = data.get(\"session_id\", \"unknown\")\n    transcript_path = data.get(\"transcript_path\", \"\")\n\n    transcript_content = read_transcript(transcript_path)\n    current_tokens = count_tokens(transcript_content)\n\n    # Save to temp file for later comparison\n    state_file = get_state_file(session_id)\n    with open(state_file, \"w\") as f:\n        json.dump({\"pre_tokens\": current_tokens}, f)\n\n\ndef handle_stop(data: dict) -> None:\n    \"\"\"Post-response hook: Calculate and report token delta.\"\"\"\n    session_id = data.get(\"session_id\", \"unknown\")\n    transcript_path = data.get(\"transcript_path\", \"\")\n\n    transcript_content = read_transcript(transcript_path)\n    current_tokens = count_tokens(transcript_content)\n\n    # Load pre-message count\n    state_file = get_state_file(session_id)\n    pre_tokens = 0\n    if os.path.exists(state_file):\n        try:\n            with open(state_file, \"r\") as f:\n                state = json.load(f)\n                pre_tokens = state.get(\"pre_tokens\", 0)\n        except (json.JSONDecodeError, IOError):\n            pass\n\n    # Calculate delta\n    delta_tokens = current_tokens - pre_tokens\n    remaining = CONTEXT_LIMIT - current_tokens\n    percentage = (current_tokens / CONTEXT_LIMIT) * 100\n\n    # Report usage\n    method = \"tiktoken\" if USE_TIKTOKEN else \"estimated\"\n    print(f\"Context ({method}): ~{current_tokens:,} tokens ({percentage:.1f}% used, ~{remaining:,} remaining)\", file=sys.stderr)\n    if delta_tokens > 0:\n        print(f\"This request: ~{delta_tokens:,} tokens\", file=sys.stderr)\n\n\ndef main():\n    data = json.load(sys.stdin)\n    event = data.get(\"hook_event_name\", \"\")\n\n    if event == \"UserPromptSubmit\":\n        handle_user_prompt_submit(data)\n    elif event == \"Stop\":\n        handle_stop(data)\n\n    sys.exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/context-tracker.py\\\"\"\n          }\n        ]\n      }\n    ],\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/context-tracker.py\\\"\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**How it works:**\n1. `UserPromptSubmit` fires before your prompt is processed - saves current token count\n2. `Stop` fires after Claude responds - calculates delta and reports usage\n3. Each session is isolated via `session_id` in the temp filename\n\n**Token Counting Methods:**\n\n| Method | Accuracy | Dependencies | Speed |\n|--------|----------|--------------|-------|\n| Character estimation | ~80-90% | None | <1ms |\n| tiktoken (p50k_base) | ~90-95% | `pip install tiktoken` | <10ms |\n\n> **Note:** Anthropic hasn't released an official offline tokenizer. Both methods are approximations. The transcript includes user prompts, Claude's responses, and tool outputs, but NOT system prompts or internal context.\n\n### Example 7: Auto-Adapt Mode (PostToolUse)\n\nAutomatically learns from your tool approvals and updates `~/.claude/settings.json` permissions. Every time you accept a tool execution, the hook generalizes the command into a reusable permission rule — so you never have to approve the same type of command twice. Dangerous/destructive commands are **never** remembered.\n\nOn first run, it seeds your config with auto-mode-equivalent baseline permissions (read/write files, git operations, package managers, common CLI tools).\n\n**File:** `.claude/hooks/auto-adapt-mode.py`\n\n```python\n#!/usr/bin/env python3\n\"\"\"\nauto-adapt-mode: Learn from user's tool approvals and update Claude config.\n\nHook Type: PostToolUse\nEvent: Fires after a tool is successfully executed (meaning user approved it)\n\"\"\"\n\nimport json\nimport os\nimport sys\nimport re\nfrom pathlib import Path\n\nSETTINGS_PATH = Path.home() / \".claude\" / \"settings.json\"\nLOG_PATH = Path.home() / \".claude\" / \"auto-adapt-mode.log\"\n\n# Auto-mode baseline: safe, local, reversible operations\nAUTO_MODE_BASELINE = [\n    \"Read(*)\", \"Edit(*)\", \"Write(*)\", \"Glob(*)\", \"Grep(*)\",\n    \"Bash(git status:*)\", \"Bash(git log:*)\", \"Bash(git diff:*)\",\n    \"Bash(git add:*)\", \"Bash(git commit:*)\", \"Bash(git checkout:*)\",\n    \"Bash(npm install:*)\", \"Bash(npm test:*)\", \"Bash(npm run:*)\",\n    \"Bash(pip install:*)\", \"Bash(pytest:*)\",\n    \"Bash(ls:*)\", \"Bash(cat:*)\", \"Bash(find:*)\", \"Bash(mkdir:*)\",\n    \"Bash(cp:*)\", \"Bash(mv:*)\", \"Bash(chmod:*)\",\n    \"Bash(gh pr view:*)\", \"Bash(gh issue list:*)\",\n    \"Agent(*)\", \"Skill(*)\", \"WebSearch(*)\", \"WebFetch(*)\",\n    # ... (full list includes 70+ safe patterns)\n]\n\n# Commands that are NEVER auto-remembered\nDANGEROUS_PATTERNS = [\n    r\"rm\\s+(-[a-zA-Z]*r[a-zA-Z]*|--recursive)\",   # rm -rf\n    r\"git\\s+push\\s+(-[a-zA-Z]*f|--force)\",          # force push\n    r\"git\\s+reset\\s+--hard\",                         # hard reset\n    r\"DROP\\s+(TABLE|DATABASE)\",                       # SQL destructive\n    r\"curl\\s+.*\\|\\s*(bash|sh)\",                       # pipe to shell\n    r\"sudo\\b\",                                        # privilege escalation\n    r\"docker\\s+(rm|rmi|system\\s+prune)\",              # container destructive\n    r\"kubectl\\s+delete\",                              # k8s destructive\n    r\"terraform\\s+destroy\",                           # infra destructive\n    r\"npm\\s+publish\",                                 # irreversible publish\n    r\"deploy\\s+.*prod\",                               # production deploy\n    # ... (full list includes 25+ patterns)\n]\n\n\ndef is_dangerous_command(command: str) -> bool:\n    \"\"\"Check if a bash command matches any dangerous pattern.\"\"\"\n    return any(re.search(p, command, re.IGNORECASE) for p in DANGEROUS_PATTERNS)\n\n\ndef generalize_tool_permission(tool_name: str, tool_input: dict) -> str | None:\n    \"\"\"Convert a specific tool invocation into a generalized permission rule.\"\"\"\n    if tool_name == \"Bash\":\n        command = tool_input.get(\"command\", \"\")\n        if not command or is_dangerous_command(command):\n            return None\n        parts = command.strip().split()\n        base = parts[0]\n        # Compound commands: \"git push\" -> \"Bash(git push:*)\"\n        compound = [\"git\", \"npm\", \"npx\", \"pip\", \"cargo\", \"go\", \"gh\", \"python3\"]\n        if base in compound and len(parts) > 1:\n            sub = parts[1]\n            if sub.lower() in {\"rm\", \"delete\", \"destroy\", \"publish\"}:\n                return None\n            return f\"Bash({base} {sub}:*)\"\n        return f\"Bash({base}:*)\"\n    elif tool_name == \"Bash\":  # Never allow generic Bash(*)\n        return None\n    else:\n        return f\"{tool_name}(*)\"\n\n\ndef main():\n    try:\n        hook_input = json.load(sys.stdin)\n    except (json.JSONDecodeError, EOFError):\n        sys.exit(0)\n\n    tool_name = hook_input.get(\"tool_name\", \"\")\n    tool_input = hook_input.get(\"tool_input\", {})\n    if not tool_name:\n        sys.exit(0)\n\n    # Load settings, ensure baseline, add new rule if safe\n    settings = json.load(open(SETTINGS_PATH)) if SETTINGS_PATH.exists() else {}\n    allow = settings.setdefault(\"permissions\", {}).setdefault(\"allow\", [])\n\n    # Seed baseline on first run\n    marker = Path.home() / \".claude\" / \".auto-adapt-mode-initialized\"\n    if not marker.exists():\n        existing = set(allow)\n        for rule in AUTO_MODE_BASELINE:\n            if rule not in existing:\n                allow.append(rule)\n        marker.touch()\n\n    # Generalize and add the new rule\n    rule = generalize_tool_permission(tool_name, tool_input)\n    if rule and rule not in allow:\n        allow.append(rule)\n        with open(SETTINGS_PATH, \"w\") as f:\n            json.dump(settings, f, indent=2)\n            f.write(\"\\n\")\n\n    sys.exit(0)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/auto-adapt-mode.py\\\"\",\n            \"timeout\": 10\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**How it works:**\n1. `PostToolUse` fires after **every** successful tool execution (meaning you already approved it)\n2. The hook extracts the tool name and input, then generalizes it into a permission rule\n3. Compound commands like `git push origin main` become `Bash(git push:*)` — matching any `git push` variant\n4. The rule is added to `~/.claude/settings.json` → `permissions.allow` if not already present\n5. On first run, seeds ~70 auto-mode-equivalent baseline permissions\n\n**Safety guarantees:**\n- Dangerous commands (force push, rm -rf, sudo, DROP TABLE, etc.) are **never** remembered\n- Irreversible operations (npm publish, terraform destroy, prod deploys) are **always** blocked\n- Commands in the `deny` list are never overridden\n- The hook never blocks tool execution (always exits 0)\n- A log file at `~/.claude/auto-adapt-mode.log` tracks all decisions for auditing\n\n**Generalization examples:**\n\n| You approve | Rule added | Covers |\n|-------------|-----------|--------|\n| `git push origin main` | `Bash(git push:*)` | All git push variants |\n| `npm run build` | `Bash(npm run:*)` | All npm scripts |\n| `ls -la src/` | `Bash(ls:*)` | All ls invocations |\n| `rm -rf /tmp/test` | *(blocked)* | Never remembered |\n| `git push --force` | *(blocked)* | Never remembered |\n| `Write` tool | `Write(*)` | All file writes |\n\n> **Tip:** Delete `~/.claude/.auto-adapt-mode-initialized` to re-seed baseline permissions. Check `~/.claude/auto-adapt-mode.log` to audit what rules were added and which were blocked.\n\n## Plugin Hooks\n\nPlugins can include hooks in their `hooks/hooks.json` file:\n\n**File:** `plugins/hooks/hooks.json`\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Environment Variables in Plugin Hooks:**\n- `${CLAUDE_PLUGIN_ROOT}` - Path to the plugin directory\n- `${CLAUDE_PLUGIN_DATA}` - Path to the plugin data directory\n\nThis allows plugins to include custom validation and automation hooks.\n\n## MCP Tool Hooks\n\nMCP tools follow the pattern `mcp__<server>__<tool>`:\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"mcp__memory__.*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo '{\\\"systemMessage\\\": \\\"Memory operation logged\\\"}'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n## Security Considerations\n\n### Disclaimer\n\n**USE AT YOUR OWN RISK**: Hooks execute arbitrary shell commands. You are solely responsible for:\n- Commands you configure\n- File access/modification permissions\n- Potential data loss or system damage\n- Testing hooks in safe environments before production use\n\n### Security Notes\n\n- **Workspace trust required:** The `statusLine` and `fileSuggestion` hook output commands now require workspace trust acceptance before they take effect.\n- **HTTP hooks and environment variables:** HTTP hooks require an explicit `allowedEnvVars` list to use environment variable interpolation in URLs. This prevents accidental leakage of sensitive environment variables to remote endpoints.\n- **Managed settings hierarchy:** The `disableAllHooks` setting now respects the managed settings hierarchy, meaning organization-level settings can enforce hook disablement that individual users cannot override.\n\n### Best Practices\n\n| Do | Don't |\n|-----|-------|\n| Validate and sanitize all inputs | Trust input data blindly |\n| Quote shell variables: `\"$VAR\"` | Use unquoted: `$VAR` |\n| Block path traversal (`..`) | Allow arbitrary paths |\n| Use absolute paths with `$CLAUDE_PROJECT_DIR` | Hardcode paths |\n| Skip sensitive files (`.env`, `.git/`, keys) | Process all files |\n| Test hooks in isolation first | Deploy untested hooks |\n| Use explicit `allowedEnvVars` for HTTP hooks | Expose all env vars to webhooks |\n\n## Debugging\n\n### Enable Debug Mode\n\nRun Claude with debug flag for detailed hook logs:\n\n```bash\nclaude --debug\n```\n\n### Verbose Mode\n\nUse `Ctrl+O` in Claude Code to enable verbose mode and see hook execution progress.\n\n### Test Hooks Independently\n\n```bash\n# Test with sample JSON input\necho '{\"tool_name\": \"Bash\", \"tool_input\": {\"command\": \"ls -la\"}}' | python3 .claude/hooks/validate-bash.py\n\n# Check exit code\necho $?\n```\n\n## Complete Configuration Example\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py\\\"\",\n            \"timeout\": 10\n          }\n        ]\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Write|Edit\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"$CLAUDE_PROJECT_DIR/.claude/hooks/format-code.sh\\\"\",\n            \"timeout\": 30\n          },\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/security-scan.py\\\"\",\n            \"timeout\": 10\n          }\n        ]\n      }\n    ],\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-prompt.py\\\"\"\n          }\n        ]\n      }\n    ],\n    \"SessionStart\": [\n      {\n        \"matcher\": \"startup\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-init.sh\\\"\"\n          }\n        ]\n      }\n    ],\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"prompt\",\n            \"prompt\": \"Verify all tasks are complete before stopping.\",\n            \"timeout\": 30\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n## Hook Execution Details\n\n| Aspect | Behavior |\n|--------|----------|\n| **Timeout** | 60 seconds default, configurable per command |\n| **Parallelization** | All matching hooks run in parallel |\n| **Deduplication** | Identical hook commands deduplicated |\n| **Environment** | Runs in current directory with Claude Code's environment |\n\n## Troubleshooting\n\n### Hook Not Executing\n- Verify JSON configuration syntax is correct\n- Check matcher pattern matches the tool name\n- Ensure script exists and is executable: `chmod +x script.sh`\n- Run `claude --debug` to see hook execution logs\n- Verify hook reads JSON from stdin (not command args)\n\n### Hook Blocks Unexpectedly\n- Test hook with sample JSON: `echo '{\"tool_name\": \"Write\", ...}' | ./hook.py`\n- Check exit code: should be 0 for allow, 2 for block\n- Check stderr output (shown on exit code 2)\n\n### JSON Parsing Errors\n- Always read from stdin, not command arguments\n- Use proper JSON parsing (not string manipulation)\n- Handle missing fields gracefully\n\n## Installation\n\n### Step 1: Create Hooks Directory\n```bash\nmkdir -p ~/.claude/hooks\n```\n\n### Step 2: Copy Example Hooks\n```bash\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n```\n\n### Step 3: Configure in Settings\nEdit `~/.claude/settings.json` or `.claude/settings.json` with the hook configuration shown above.\n\n## Related Concepts\n\n- **[Checkpoints and Rewind](../08-checkpoints/)** - Save and restore conversation state\n- **[Slash Commands](../01-slash-commands/)** - Create custom slash commands\n- **[Skills](../03-skills/)** - Reusable autonomous capabilities\n- **[Subagents](../04-subagents/)** - Delegated task execution\n- **[Plugins](../07-plugins/)** - Bundled extension packages\n- **[Advanced Features](../09-advanced-features/)** - Explore advanced Claude Code capabilities\n\n## Additional Resources\n\n- **[Official Hooks Documentation](https://code.claude.com/docs/en/hooks)** - Complete hooks reference\n- **[CLI Reference](https://code.claude.com/docs/en/cli-reference)** - Command-line interface documentation\n- **[Memory Guide](../02-memory/)** - Persistent context configuration\n"
  },
  {
    "path": "06-hooks/auto-adapt-mode.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nauto-adapt-mode: Learn from user's tool approvals and update Claude config.\n\nHook Type: PostToolUse\nEvent: Fires after a tool is successfully executed (meaning user approved it)\n\nBehavior:\n- When user approves a tool/command, generalize it into a permission rule\n- Add the generalized rule to ~/.claude/settings.json permissions.allow\n- NEVER remember dangerous/destructive commands (rm -rf, force-push, DROP, etc.)\n- On first run, seeds the config with auto-mode-equivalent baseline permissions\n\nUsage in settings.json:\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3 \\\"$CLAUDE_PROJECT_DIR/06-hooks/auto-adapt-mode.py\\\"\",\n            \"timeout\": 10\n          }\n        ]\n      }\n    ]\n  }\n}\n\"\"\"\n\nimport json\nimport os\nimport sys\nimport re\nfrom pathlib import Path\n\n# ──────────────────────────────────────────────────────────────────────────────\n# Constants\n# ──────────────────────────────────────────────────────────────────────────────\n\nSETTINGS_PATH = Path.home() / \".claude\" / \"settings.json\"\nLOG_PATH = Path.home() / \".claude\" / \"auto-adapt-mode.log\"\n\n# Auto-mode baseline permissions (equivalent to Claude Code's auto-mode defaults)\n# These are safe, local, reversible operations that auto-mode allows without prompting\nAUTO_MODE_BASELINE = [\n    # File operations (read/write in working directory)\n    \"Read(*)\",\n    \"Edit(*)\",\n    \"Write(*)\",\n    \"Glob(*)\",\n    \"Grep(*)\",\n    # Git read operations\n    \"Bash(git status:*)\",\n    \"Bash(git log:*)\",\n    \"Bash(git diff:*)\",\n    \"Bash(git branch:*)\",\n    \"Bash(git show:*)\",\n    \"Bash(git rev-parse:*)\",\n    \"Bash(git remote -v:*)\",\n    \"Bash(git fetch:*)\",\n    \"Bash(git stash list:*)\",\n    # Git write operations (local, reversible)\n    \"Bash(git add:*)\",\n    \"Bash(git commit:*)\",\n    \"Bash(git checkout:*)\",\n    \"Bash(git switch:*)\",\n    \"Bash(git merge:*)\",\n    \"Bash(git rebase:*)\",\n    \"Bash(git stash:*)\",\n    \"Bash(git tag:*)\",\n    \"Bash(git worktree:*)\",\n    # Package managers (install from manifests)\n    \"Bash(npm install:*)\",\n    \"Bash(npm ci:*)\",\n    \"Bash(npm test:*)\",\n    \"Bash(npm run:*)\",\n    \"Bash(npx:*)\",\n    \"Bash(pip install:*)\",\n    \"Bash(pip3 install:*)\",\n    \"Bash(cargo build:*)\",\n    \"Bash(cargo test:*)\",\n    \"Bash(go build:*)\",\n    \"Bash(go test:*)\",\n    \"Bash(go mod:*)\",\n    # Build and test\n    \"Bash(make:*)\",\n    \"Bash(cmake:*)\",\n    \"Bash(pytest:*)\",\n    \"Bash(python3 -m pytest:*)\",\n    # Common safe commands\n    \"Bash(ls:*)\",\n    \"Bash(pwd:*)\",\n    \"Bash(which:*)\",\n    \"Bash(echo:*)\",\n    \"Bash(cat:*)\",\n    \"Bash(head:*)\",\n    \"Bash(tail:*)\",\n    \"Bash(wc:*)\",\n    \"Bash(sort:*)\",\n    \"Bash(uniq:*)\",\n    \"Bash(find:*)\",\n    \"Bash(dirname:*)\",\n    \"Bash(basename:*)\",\n    \"Bash(realpath:*)\",\n    \"Bash(mkdir:*)\",\n    \"Bash(touch:*)\",\n    \"Bash(cp:*)\",\n    \"Bash(mv:*)\",\n    \"Bash(chmod:*)\",\n    \"Bash(date:*)\",\n    \"Bash(env:*)\",\n    \"Bash(printenv:*)\",\n    # File inspection\n    \"Bash(file:*)\",\n    \"Bash(stat:*)\",\n    \"Bash(diff:*)\",\n    \"Bash(md5sum:*)\",\n    \"Bash(sha256sum:*)\",\n    # GitHub CLI (read operations)\n    \"Bash(gh pr view:*)\",\n    \"Bash(gh pr list:*)\",\n    \"Bash(gh issue view:*)\",\n    \"Bash(gh issue list:*)\",\n    \"Bash(gh repo view:*)\",\n    # Agents and tools\n    \"Agent(*)\",\n    \"Skill(*)\",\n    \"WebSearch(*)\",\n    \"WebFetch(*)\",\n    \"NotebookEdit(*)\",\n    \"TaskCreate(*)\",\n    \"TaskUpdate(*)\",\n]\n\n# ──────────────────────────────────────────────────────────────────────────────\n# Dangerous patterns: commands/tools that should NEVER be auto-remembered\n# These are irreversible, destructive, or affect shared/production systems\n# ──────────────────────────────────────────────────────────────────────────────\n\nDANGEROUS_PATTERNS = [\n    # Destructive file operations\n    r\"rm\\s+(-[a-zA-Z]*r[a-zA-Z]*|--recursive)\",  # rm -rf, rm -r\n    r\"rm\\s+(-[a-zA-Z]*f[a-zA-Z]*)\",               # rm -f (force delete)\n    r\"rmdir\",\n    r\"shred\\b\",\n    r\"dd\\s+if=\",                                    # disk overwrite\n    r\"mkfs\\b\",                                      # format filesystem\n    r\"format\\b\",\n\n    # Git destructive operations\n    r\"git\\s+push\\s+(-[a-zA-Z]*f|--force)\",          # force push\n    r\"git\\s+push\\s+--force-with-lease\",\n    r\"git\\s+reset\\s+--hard\",                         # hard reset\n    r\"git\\s+clean\\s+(-[a-zA-Z]*f|--force)\",          # clean force\n    r\"git\\s+checkout\\s+\\.\",                           # discard all changes\n    r\"git\\s+restore\\s+\\.\",\n    r\"git\\s+branch\\s+(-[a-zA-Z]*D|-d\\s+main|-d\\s+master)\",  # delete branches\n    r\"git\\s+push\\s+.*:.*main\",                       # delete remote main\n    r\"git\\s+push\\s+.*:.*master\",\n\n    # Database destructive operations\n    r\"DROP\\s+(TABLE|DATABASE|SCHEMA|INDEX)\",\n    r\"TRUNCATE\\b\",\n    r\"DELETE\\s+FROM\\s+(?!.*WHERE)\",                  # DELETE without WHERE\n    r\"ALTER\\s+TABLE\\s+.*DROP\",\n\n    # System-level dangerous operations\n    r\"sudo\\b\",\n    r\"chmod\\s+777\",\n    r\"chown\\s+-R\\s+root\",\n\n    # Network exfiltration / remote execution\n    r\"curl\\s+.*\\|\\s*(bash|sh|zsh)\",                  # pipe to shell\n    r\"wget\\s+.*\\|\\s*(bash|sh|zsh)\",\n    r\"curl\\s+.*--upload-file\",\n    r\"curl\\s+.*-T\\s+\",                               # upload\n    r\"scp\\b(?!.*localhost)\",                          # remote copy (not local)\n    r\"rsync\\b.*[^/]:\",                                # remote rsync\n\n    # Container/infra destructive\n    r\"docker\\s+(rm|rmi|system\\s+prune)\",\n    r\"kubectl\\s+delete\",\n    r\"terraform\\s+destroy\",\n\n    # Package publishing (irreversible)\n    r\"npm\\s+publish\",\n    r\"pip\\s+upload\",\n    r\"cargo\\s+publish\",\n\n    # Environment/secret exposure\n    r\"printenv\\s+.*SECRET\",\n    r\"printenv\\s+.*PASSWORD\",\n    r\"printenv\\s+.*TOKEN\",\n    r\"echo\\s+\\$.*SECRET\",\n    r\"echo\\s+\\$.*PASSWORD\",\n\n    # Process killing\n    r\"kill\\s+-9\",\n    r\"killall\\b\",\n    r\"pkill\\b\",\n\n    # Production deployment\n    r\"deploy\\s+.*prod\",\n    r\"migrate\\s+.*prod\",\n]\n\n# Tools that should never be auto-allowed (non-Bash)\nDANGEROUS_TOOLS = {\n    \"Bash\",  # Generic Bash(*) wildcard is dangerous — we allow specific commands only\n}\n\n\n# ──────────────────────────────────────────────────────────────────────────────\n# Helper functions\n# ──────────────────────────────────────────────────────────────────────────────\n\ndef log(message: str):\n    \"\"\"Append a log entry for debugging.\"\"\"\n    try:\n        with open(LOG_PATH, \"a\") as f:\n            from datetime import datetime\n            f.write(f\"[{datetime.now().isoformat()}] {message}\\n\")\n    except Exception:\n        pass\n\n\ndef is_dangerous_command(command: str) -> bool:\n    \"\"\"Check if a bash command matches any dangerous pattern.\"\"\"\n    for pattern in DANGEROUS_PATTERNS:\n        if re.search(pattern, command, re.IGNORECASE):\n            return True\n    return False\n\n\ndef generalize_tool_permission(tool_name: str, tool_input: dict) -> str | None:\n    \"\"\"\n    Convert a specific tool invocation into a generalized permission rule.\n\n    Returns None if the tool/command should not be remembered.\n    \"\"\"\n    if tool_name == \"Bash\":\n        command = tool_input.get(\"command\", \"\")\n        if not command:\n            return None\n\n        # Never remember dangerous commands\n        if is_dangerous_command(command):\n            log(f\"BLOCKED dangerous: {command}\")\n            return None\n\n        # Extract the base command (first word or first two words for git/npm/etc.)\n        parts = command.strip().split()\n        if not parts:\n            return None\n\n        base = parts[0]\n\n        # For compound commands (git push, npm run, gh pr create, etc.)\n        # generalize to \"base subcommand:*\"\n        compound_prefixes = [\n            \"git\", \"npm\", \"npx\", \"pip\", \"pip3\", \"cargo\", \"go\",\n            \"docker\", \"kubectl\", \"gh\", \"python3\", \"python\", \"node\",\n            \"make\", \"cmake\", \"pytest\", \"ruby\", \"java\", \"javac\",\n        ]\n\n        if base in compound_prefixes and len(parts) > 1:\n            sub = parts[1]\n            # Don't generalize dangerous subcommands even if pattern didn't catch them\n            danger_subs = {\"rm\", \"delete\", \"destroy\", \"prune\", \"publish\"}\n            if sub.lower() in danger_subs:\n                log(f\"BLOCKED dangerous sub: {base} {sub}\")\n                return None\n            return f\"Bash({base} {sub}:*)\"\n\n        # For simple commands, generalize with wildcard args\n        return f\"Bash({base}:*)\"\n\n    elif tool_name in DANGEROUS_TOOLS:\n        return None\n\n    else:\n        # Non-Bash tools: allow with wildcard\n        # These are Claude Code built-in tools (Read, Write, Edit, etc.)\n        # Most are already in the baseline, but learn new ones\n        return f\"{tool_name}(*)\"\n\n\ndef load_settings() -> dict:\n    \"\"\"Load the current settings.json.\"\"\"\n    if SETTINGS_PATH.exists():\n        with open(SETTINGS_PATH, \"r\") as f:\n            return json.load(f)\n    return {}\n\n\ndef save_settings(settings: dict):\n    \"\"\"Save settings.json with formatting.\"\"\"\n    SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)\n    with open(SETTINGS_PATH, \"w\") as f:\n        json.dump(settings, f, indent=2)\n        f.write(\"\\n\")\n\n\ndef ensure_baseline(settings: dict) -> bool:\n    \"\"\"\n    Ensure auto-mode baseline permissions are seeded into settings.\n    Returns True if any changes were made.\n    \"\"\"\n    permissions = settings.setdefault(\"permissions\", {})\n    allow = permissions.setdefault(\"allow\", [])\n\n    # Track what's already there (normalized for comparison)\n    existing = set(allow)\n    added = []\n\n    for rule in AUTO_MODE_BASELINE:\n        if rule not in existing:\n            allow.append(rule)\n            existing.add(rule)\n            added.append(rule)\n\n    if added:\n        log(f\"Seeded {len(added)} baseline rules\")\n        return True\n    return False\n\n\ndef add_permission(settings: dict, rule: str) -> bool:\n    \"\"\"\n    Add a permission rule if it doesn't already exist or isn't covered.\n    Returns True if the rule was added.\n    \"\"\"\n    permissions = settings.setdefault(\"permissions\", {})\n    allow = permissions.setdefault(\"allow\", [])\n    deny = permissions.get(\"deny\", [])\n\n    # Don't add if already in deny list\n    if rule in deny:\n        log(f\"SKIPPED (in deny list): {rule}\")\n        return False\n\n    # Don't add if already exists\n    if rule in allow:\n        return False\n\n    # Check if a more general rule already covers this\n    # e.g., \"Bash(git:*)\" covers \"Bash(git status:*)\"\n    for existing in allow:\n        if existing.endswith(\"(*)\"):\n            tool_prefix = existing[:-3]\n            if rule.startswith(tool_prefix + \"(\"):\n                return False  # Already covered by wildcard\n\n    allow.append(rule)\n    log(f\"ADDED: {rule}\")\n    return True\n\n\n# ──────────────────────────────────────────────────────────────────────────────\n# Main hook logic\n# ──────────────────────────────────────────────────────────────────────────────\n\ndef main():\n    # Read hook input from stdin\n    try:\n        hook_input = json.load(sys.stdin)\n    except (json.JSONDecodeError, EOFError):\n        sys.exit(0)  # Non-blocking: don't interfere if input is malformed\n\n    tool_name = hook_input.get(\"tool_name\", \"\")\n    tool_input = hook_input.get(\"tool_input\", {})\n\n    if not tool_name:\n        sys.exit(0)\n\n    # Load current settings\n    settings = load_settings()\n\n    changed = False\n\n    # Ensure baseline permissions on first meaningful invocation\n    marker_file = Path.home() / \".claude\" / \".auto-adapt-mode-initialized\"\n    if not marker_file.exists():\n        changed = ensure_baseline(settings)\n        marker_file.touch()\n        log(\"Baseline initialized\")\n\n    # Generalize the tool invocation into a permission rule\n    rule = generalize_tool_permission(tool_name, tool_input)\n\n    if rule:\n        if add_permission(settings, rule):\n            changed = True\n\n    # Save if anything changed\n    if changed:\n        save_settings(settings)\n\n    # Always succeed — never block tool execution\n    sys.exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "06-hooks/context-tracker-tiktoken.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nContext Usage Tracker (tiktoken version) - Tracks token consumption per request.\n\nUses UserPromptSubmit as \"pre-message\" hook and Stop as \"post-response\" hook\nto calculate the delta in token usage for each request.\n\nThis version uses tiktoken with p50k_base encoding for ~90-95% accuracy.\nRequires: pip install tiktoken\n\nFor a zero-dependency version, see context-tracker.py.\n\nUsage:\n    Configure both hooks to use the same script:\n    - UserPromptSubmit: saves current token count\n    - Stop: calculates delta and reports usage\n\"\"\"\nimport json\nimport os\nimport sys\nimport tempfile\n\ntry:\n    import tiktoken\n\n    TIKTOKEN_AVAILABLE = True\nexcept ImportError:\n    TIKTOKEN_AVAILABLE = False\n    print(\n        \"Warning: tiktoken not installed. Install with: pip install tiktoken\",\n        file=sys.stderr,\n    )\n\n# Configuration\nCONTEXT_LIMIT = 128000  # Claude's context window (adjust for your model)\n\n\ndef get_state_file(session_id: str) -> str:\n    \"\"\"Get temp file path for storing pre-message token count, isolated by session.\"\"\"\n    return os.path.join(tempfile.gettempdir(), f\"claude-context-{session_id}.json\")\n\n\ndef count_tokens(text: str) -> int:\n    \"\"\"\n    Count tokens using tiktoken with p50k_base encoding.\n\n    This provides ~90-95% accuracy compared to Claude's actual tokenizer.\n    Falls back to character estimation if tiktoken is not available.\n\n    Note: Anthropic hasn't released an official offline tokenizer.\n    tiktoken with p50k_base is a reasonable approximation since both\n    Claude and GPT models use BPE (byte-pair encoding).\n    \"\"\"\n    if TIKTOKEN_AVAILABLE:\n        enc = tiktoken.get_encoding(\"p50k_base\")\n        return len(enc.encode(text))\n    else:\n        # Fallback to character estimation (~4 chars per token)\n        return len(text) // 4\n\n\ndef read_transcript(transcript_path: str) -> str:\n    \"\"\"Read and concatenate all content from transcript file.\"\"\"\n    if not transcript_path or not os.path.exists(transcript_path):\n        return \"\"\n\n    content = []\n    with open(transcript_path, \"r\") as f:\n        for line in f:\n            try:\n                entry = json.loads(line.strip())\n                # Extract text content from various message formats\n                if \"message\" in entry:\n                    msg = entry[\"message\"]\n                    if isinstance(msg.get(\"content\"), str):\n                        content.append(msg[\"content\"])\n                    elif isinstance(msg.get(\"content\"), list):\n                        for block in msg[\"content\"]:\n                            if isinstance(block, dict) and block.get(\"type\") == \"text\":\n                                content.append(block.get(\"text\", \"\"))\n            except json.JSONDecodeError:\n                continue\n\n    return \"\\n\".join(content)\n\n\ndef handle_user_prompt_submit(data: dict) -> None:\n    \"\"\"Pre-message hook: Save current token count before request.\"\"\"\n    session_id = data.get(\"session_id\", \"unknown\")\n    transcript_path = data.get(\"transcript_path\", \"\")\n\n    transcript_content = read_transcript(transcript_path)\n    current_tokens = count_tokens(transcript_content)\n\n    # Save to temp file for later comparison\n    state_file = get_state_file(session_id)\n    with open(state_file, \"w\") as f:\n        json.dump({\"pre_tokens\": current_tokens}, f)\n\n\ndef handle_stop(data: dict) -> None:\n    \"\"\"Post-response hook: Calculate and report token delta.\"\"\"\n    session_id = data.get(\"session_id\", \"unknown\")\n    transcript_path = data.get(\"transcript_path\", \"\")\n\n    transcript_content = read_transcript(transcript_path)\n    current_tokens = count_tokens(transcript_content)\n\n    # Load pre-message count\n    state_file = get_state_file(session_id)\n    pre_tokens = 0\n    if os.path.exists(state_file):\n        try:\n            with open(state_file, \"r\") as f:\n                state = json.load(f)\n                pre_tokens = state.get(\"pre_tokens\", 0)\n        except (json.JSONDecodeError, IOError):\n            pass\n\n    # Calculate delta\n    delta_tokens = current_tokens - pre_tokens\n    remaining = CONTEXT_LIMIT - current_tokens\n    percentage = (current_tokens / CONTEXT_LIMIT) * 100\n\n    # Report usage (stderr so it doesn't interfere with hook output)\n    method = \"tiktoken\" if TIKTOKEN_AVAILABLE else \"estimated\"\n    print(\n        f\"Context ({method}): ~{current_tokens:,} tokens \"\n        f\"({percentage:.1f}% used, ~{remaining:,} remaining)\",\n        file=sys.stderr,\n    )\n    if delta_tokens > 0:\n        print(f\"This request: ~{delta_tokens:,} tokens\", file=sys.stderr)\n\n\ndef main():\n    data = json.load(sys.stdin)\n    event = data.get(\"hook_event_name\", \"\")\n\n    if event == \"UserPromptSubmit\":\n        handle_user_prompt_submit(data)\n    elif event == \"Stop\":\n        handle_stop(data)\n\n    sys.exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "06-hooks/context-tracker.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nContext Usage Tracker - Tracks token consumption per request.\n\nUses UserPromptSubmit as \"pre-message\" hook and Stop as \"post-response\" hook\nto calculate the delta in token usage for each request.\n\nThis version uses character-based estimation (no dependencies).\nFor better accuracy, see context-tracker-tiktoken.py.\n\nUsage:\n    Configure both hooks to use the same script:\n    - UserPromptSubmit: saves current token count\n    - Stop: calculates delta and reports usage\n\"\"\"\nimport json\nimport os\nimport sys\nimport tempfile\n\n# Configuration\nCONTEXT_LIMIT = 128000  # Claude's context window (adjust for your model)\n\n\ndef get_state_file(session_id: str) -> str:\n    \"\"\"Get temp file path for storing pre-message token count, isolated by session.\"\"\"\n    return os.path.join(tempfile.gettempdir(), f\"claude-context-{session_id}.json\")\n\n\ndef count_tokens_estimate(text: str) -> int:\n    \"\"\"\n    Estimate token count using character-based approximation.\n\n    Uses ~4 characters per token ratio, which provides ~80-90% accuracy\n    for English text. Less accurate for code and non-English text.\n    \"\"\"\n    return len(text) // 4\n\n\ndef read_transcript(transcript_path: str) -> str:\n    \"\"\"Read and concatenate all content from transcript file.\"\"\"\n    if not transcript_path or not os.path.exists(transcript_path):\n        return \"\"\n\n    content = []\n    with open(transcript_path, \"r\") as f:\n        for line in f:\n            try:\n                entry = json.loads(line.strip())\n                # Extract text content from various message formats\n                if \"message\" in entry:\n                    msg = entry[\"message\"]\n                    if isinstance(msg.get(\"content\"), str):\n                        content.append(msg[\"content\"])\n                    elif isinstance(msg.get(\"content\"), list):\n                        for block in msg[\"content\"]:\n                            if isinstance(block, dict) and block.get(\"type\") == \"text\":\n                                content.append(block.get(\"text\", \"\"))\n            except json.JSONDecodeError:\n                continue\n\n    return \"\\n\".join(content)\n\n\ndef handle_user_prompt_submit(data: dict) -> None:\n    \"\"\"Pre-message hook: Save current token count before request.\"\"\"\n    session_id = data.get(\"session_id\", \"unknown\")\n    transcript_path = data.get(\"transcript_path\", \"\")\n\n    transcript_content = read_transcript(transcript_path)\n    current_tokens = count_tokens_estimate(transcript_content)\n\n    # Save to temp file for later comparison\n    state_file = get_state_file(session_id)\n    with open(state_file, \"w\") as f:\n        json.dump({\"pre_tokens\": current_tokens}, f)\n\n\ndef handle_stop(data: dict) -> None:\n    \"\"\"Post-response hook: Calculate and report token delta.\"\"\"\n    session_id = data.get(\"session_id\", \"unknown\")\n    transcript_path = data.get(\"transcript_path\", \"\")\n\n    transcript_content = read_transcript(transcript_path)\n    current_tokens = count_tokens_estimate(transcript_content)\n\n    # Load pre-message count\n    state_file = get_state_file(session_id)\n    pre_tokens = 0\n    if os.path.exists(state_file):\n        try:\n            with open(state_file, \"r\") as f:\n                state = json.load(f)\n                pre_tokens = state.get(\"pre_tokens\", 0)\n        except (json.JSONDecodeError, IOError):\n            pass\n\n    # Calculate delta\n    delta_tokens = current_tokens - pre_tokens\n    remaining = CONTEXT_LIMIT - current_tokens\n    percentage = (current_tokens / CONTEXT_LIMIT) * 100\n\n    # Report usage (stderr so it doesn't interfere with hook output)\n    print(\n        f\"Context (estimated): ~{current_tokens:,} tokens \"\n        f\"({percentage:.1f}% used, ~{remaining:,} remaining)\",\n        file=sys.stderr,\n    )\n    if delta_tokens > 0:\n        print(f\"This request: ~{delta_tokens:,} tokens\", file=sys.stderr)\n\n\ndef main():\n    data = json.load(sys.stdin)\n    event = data.get(\"hook_event_name\", \"\")\n\n    if event == \"UserPromptSubmit\":\n        handle_user_prompt_submit(data)\n    elif event == \"Stop\":\n        handle_stop(data)\n\n    sys.exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "06-hooks/format-code.sh",
    "content": "#!/bin/bash\n# Auto-format code before writing\n# Hook: PreToolUse:Write\n\nFILE=$1\n\nif [ -z \"$FILE\" ]; then\n  echo \"Usage: $0 <file_path>\"\n  exit 1\nfi\n\n# Detect file type and format accordingly\ncase \"$FILE\" in\n  *.js|*.jsx|*.ts|*.tsx)\n    if command -v prettier &> /dev/null; then\n      echo \"Formatting JavaScript/TypeScript file: $FILE\"\n      prettier --write \"$FILE\"\n    fi\n    ;;\n  *.py)\n    if command -v black &> /dev/null; then\n      echo \"Formatting Python file: $FILE\"\n      black \"$FILE\"\n    fi\n    ;;\n  *.go)\n    if command -v gofmt &> /dev/null; then\n      echo \"Formatting Go file: $FILE\"\n      gofmt -w \"$FILE\"\n    fi\n    ;;\n  *.rs)\n    if command -v rustfmt &> /dev/null; then\n      echo \"Formatting Rust file: $FILE\"\n      rustfmt \"$FILE\"\n    fi\n    ;;\n  *.java)\n    if command -v google-java-format &> /dev/null; then\n      echo \"Formatting Java file: $FILE\"\n      google-java-format -i \"$FILE\"\n    fi\n    ;;\nesac\n\nexit 0\n"
  },
  {
    "path": "06-hooks/log-bash.sh",
    "content": "#!/bin/bash\n# Log all bash commands\n# Hook: PostToolUse:Bash\n\nCOMMAND=\"$1\"\nTIMESTAMP=$(date \"+%Y-%m-%d %H:%M:%S\")\nLOGFILE=\"$HOME/.claude/bash-commands.log\"\n\n# Create log directory if it doesn't exist\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n\n# Log the command\necho \"[$TIMESTAMP] $COMMAND\" >> \"$LOGFILE\"\n\n# Optional: Log to system log as well\n# logger -t \"claude-bash\" \"$COMMAND\"\n\nexit 0\n"
  },
  {
    "path": "06-hooks/notify-team.sh",
    "content": "#!/bin/bash\n# Send notifications on events\n# Hook: PostPush\n\nREPO_NAME=$(basename $(git rev-parse --show-toplevel 2>/dev/null) 2>/dev/null)\nCOMMIT_MSG=$(git log -1 --pretty=%B 2>/dev/null)\nAUTHOR=$(git log -1 --pretty=%an 2>/dev/null)\nBRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)\n\necho \"📢 Sending notification to team...\"\n\n# Slack webhook example (replace with your webhook URL)\nSLACK_WEBHOOK=\"${SLACK_WEBHOOK_URL:-}\"\n\nif [ -n \"$SLACK_WEBHOOK\" ]; then\n  curl -X POST \"$SLACK_WEBHOOK\" \\\n    -H 'Content-Type: application/json' \\\n    -d \"{\n      \\\"text\\\": \\\"New push to *$REPO_NAME*\\\",\n      \\\"attachments\\\": [{\n        \\\"color\\\": \\\"good\\\",\n        \\\"fields\\\": [\n          {\\\"title\\\": \\\"Branch\\\", \\\"value\\\": \\\"$BRANCH\\\", \\\"short\\\": true},\n          {\\\"title\\\": \\\"Author\\\", \\\"value\\\": \\\"$AUTHOR\\\", \\\"short\\\": true},\n          {\\\"title\\\": \\\"Commit\\\", \\\"value\\\": \\\"$COMMIT_MSG\\\"}\n        ]\n      }]\n    }\" \\\n    --silent --output /dev/null\n\n  echo \"✅ Slack notification sent\"\nfi\n\n# Discord webhook example (replace with your webhook URL)\nDISCORD_WEBHOOK=\"${DISCORD_WEBHOOK_URL:-}\"\n\nif [ -n \"$DISCORD_WEBHOOK\" ]; then\n  curl -X POST \"$DISCORD_WEBHOOK\" \\\n    -H 'Content-Type: application/json' \\\n    -d \"{\n      \\\"content\\\": \\\"**New push to $REPO_NAME**\\\",\n      \\\"embeds\\\": [{\n        \\\"title\\\": \\\"$COMMIT_MSG\\\",\n        \\\"color\\\": 3066993,\n        \\\"fields\\\": [\n          {\\\"name\\\": \\\"Branch\\\", \\\"value\\\": \\\"$BRANCH\\\", \\\"inline\\\": true},\n          {\\\"name\\\": \\\"Author\\\", \\\"value\\\": \\\"$AUTHOR\\\", \\\"inline\\\": true}\n        ]\n      }]\n    }\" \\\n    --silent --output /dev/null\n\n  echo \"✅ Discord notification sent\"\nfi\n\n# Email notification example\nEMAIL_TO=\"${TEAM_EMAIL:-}\"\n\nif [ -n \"$EMAIL_TO\" ]; then\n  echo \"New push to $REPO_NAME by $AUTHOR\" | \\\n    mail -s \"Git Push: $BRANCH\" \"$EMAIL_TO\"\n\n  echo \"✅ Email notification sent\"\nfi\n\nexit 0\n"
  },
  {
    "path": "06-hooks/pre-commit.sh",
    "content": "#!/bin/bash\n# Run tests before commit\n# Hook: PreToolUse (matcher: Bash) - checks if the command is a git commit\n# Note: There is no \"PreCommit\" hook event. Use PreToolUse with a Bash matcher\n# and inspect the command to detect git commit operations.\n\necho \"🧪 Running tests before commit...\"\n\n# Check if package.json exists (Node.js project)\nif [ -f \"package.json\" ]; then\n  if grep -q \"\\\"test\\\":\" package.json; then\n    npm test\n    if [ $? -ne 0 ]; then\n      echo \"❌ Tests failed! Commit blocked.\"\n      exit 1\n    fi\n  fi\nfi\n\n# Check if pytest is available (Python project)\nif [ -f \"pytest.ini\" ] || [ -f \"setup.py\" ]; then\n  if command -v pytest &> /dev/null; then\n    pytest\n    if [ $? -ne 0 ]; then\n      echo \"❌ Tests failed! Commit blocked.\"\n      exit 1\n    fi\n  fi\nfi\n\n# Check if go.mod exists (Go project)\nif [ -f \"go.mod\" ]; then\n  go test ./...\n  if [ $? -ne 0 ]; then\n    echo \"❌ Tests failed! Commit blocked.\"\n    exit 1\n  fi\nfi\n\n# Check if Cargo.toml exists (Rust project)\nif [ -f \"Cargo.toml\" ]; then\n  cargo test\n  if [ $? -ne 0 ]; then\n    echo \"❌ Tests failed! Commit blocked.\"\n    exit 1\n  fi\nfi\n\necho \"✅ All tests passed! Proceeding with commit.\"\nexit 0\n"
  },
  {
    "path": "06-hooks/security-scan.sh",
    "content": "#!/bin/bash\n# Security scan on file write\n# Hook: PostToolUse:Write\n\nFILE=$1\n\nif [ -z \"$FILE\" ]; then\n  echo \"Usage: $0 <file_path>\"\n  exit 0\nfi\n\necho \"🔒 Running security scan on: $FILE\"\n\nISSUES_FOUND=0\n\n# Check for hardcoded passwords\nif grep -qE \"(password|passwd|pwd)\\s*=\\s*['\\\"][^'\\\"]+['\\\"]\" \"$FILE\"; then\n  echo \"⚠️  WARNING: Potential hardcoded password detected in $FILE\"\n  ISSUES_FOUND=1\nfi\n\n# Check for hardcoded API keys\nif grep -qE \"(api[_-]?key|apikey|access[_-]?token)\\s*=\\s*['\\\"][^'\\\"]+['\\\"]\" \"$FILE\"; then\n  echo \"⚠️  WARNING: Potential hardcoded API key detected in $FILE\"\n  ISSUES_FOUND=1\nfi\n\n# Check for hardcoded secrets\nif grep -qE \"(secret|token)\\s*=\\s*['\\\"][^'\\\"]+['\\\"]\" \"$FILE\"; then\n  echo \"⚠️  WARNING: Potential hardcoded secret detected in $FILE\"\n  ISSUES_FOUND=1\nfi\n\n# Check for private keys\nif grep -q \"BEGIN.*PRIVATE KEY\" \"$FILE\"; then\n  echo \"⚠️  WARNING: Private key detected in $FILE\"\n  ISSUES_FOUND=1\nfi\n\n# Check for AWS keys\nif grep -qE \"AKIA[0-9A-Z]{16}\" \"$FILE\"; then\n  echo \"⚠️  WARNING: AWS access key detected in $FILE\"\n  ISSUES_FOUND=1\nfi\n\n# Scan with semgrep if available\nif command -v semgrep &> /dev/null; then\n  semgrep --config=auto \"$FILE\" --quiet 2>/dev/null\nfi\n\n# Scan with trufflehog if available\nif command -v trufflehog &> /dev/null; then\n  trufflehog filesystem \"$FILE\" --only-verified --quiet 2>/dev/null\nfi\n\nif [ $ISSUES_FOUND -eq 0 ]; then\n  echo \"✅ No security issues found\"\nfi\n\n# Don't block the operation, just warn\nexit 0\n"
  },
  {
    "path": "06-hooks/validate-prompt.sh",
    "content": "#!/bin/bash\n# Validate user prompts\n# Hook: UserPromptSubmit\n\n# Read prompt from stdin\nPROMPT=$(cat)\n\necho \"🔍 Validating prompt...\"\n\n# Check for dangerous operations\nDANGEROUS_PATTERNS=(\n  \"rm -rf /\"\n  \"delete database\"\n  \"drop database\"\n  \"format disk\"\n  \"dd if=\"\n)\n\nfor pattern in \"${DANGEROUS_PATTERNS[@]}\"; do\n  if echo \"$PROMPT\" | grep -qi \"$pattern\"; then\n    echo \"❌ Blocked: Dangerous operation detected: $pattern\"\n    exit 1\n  fi\ndone\n\n# Check for production deployments\nif echo \"$PROMPT\" | grep -qiE \"(deploy|push).*production\"; then\n  if [ ! -f \".deployment-approved\" ]; then\n    echo \"❌ Blocked: Production deployment requires approval\"\n    echo \"Create .deployment-approved file to proceed\"\n    exit 1\n  fi\nfi\n\n# Check for required context in certain operations\nif echo \"$PROMPT\" | grep -qi \"refactor\"; then\n  if [ ! -f \"tests/\" ] && [ ! -f \"test/\" ]; then\n    echo \"⚠️  Warning: Refactoring without tests may be risky\"\n  fi\nfi\n\necho \"✅ Prompt validation passed\"\nexit 0\n"
  },
  {
    "path": "07-plugins/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Claude Code Plugins\n\nThis folder contains complete plugin examples that bundle multiple Claude Code features into cohesive, installable packages.\n\n## Overview\n\nClaude 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.\n\n## Plugin Architecture\n\n```mermaid\ngraph TB\n    A[\"Plugin\"]\n    B[\"Slash Commands\"]\n    C[\"Subagents\"]\n    D[\"MCP Servers\"]\n    E[\"Hooks\"]\n    F[\"Configuration\"]\n\n    A -->|bundles| B\n    A -->|bundles| C\n    A -->|bundles| D\n    A -->|bundles| E\n    A -->|bundles| F\n```\n\n## Plugin Loading Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Plugin as Plugin Marketplace\n    participant Install as Installation\n    participant SlashCmds as Slash Commands\n    participant Subagents\n    participant MCPServers as MCP Servers\n    participant Hooks\n    participant Tools as Configured Tools\n\n    User->>Claude: /plugin install pr-review\n    Claude->>Plugin: Download plugin manifest\n    Plugin-->>Claude: Return plugin definition\n    Claude->>Install: Extract components\n    Install->>SlashCmds: Configure\n    Install->>Subagents: Configure\n    Install->>MCPServers: Configure\n    Install->>Hooks: Configure\n    SlashCmds-->>Tools: Ready to use\n    Subagents-->>Tools: Ready to use\n    MCPServers-->>Tools: Ready to use\n    Hooks-->>Tools: Ready to use\n    Tools-->>Claude: Plugin installed ✅\n```\n\n## Plugin Types & Distribution\n\n| Type | Scope | Shared | Authority | Examples |\n|------|-------|--------|-----------|----------|\n| Official | Global | All users | Anthropic | PR Review, Security Guidance |\n| Community | Public | All users | Community | DevOps, Data Science |\n| Organization | Internal | Team members | Company | Internal standards, tools |\n| Personal | Individual | Single user | Developer | Custom workflows |\n\n## Plugin Definition Structure\n\nPlugin manifest uses JSON format in `.claude-plugin/plugin.json`:\n\n```json\n{\n  \"name\": \"my-first-plugin\",\n  \"description\": \"A greeting plugin\",\n  \"version\": \"1.0.0\",\n  \"author\": {\n    \"name\": \"Your Name\"\n  },\n  \"homepage\": \"https://example.com\",\n  \"repository\": \"https://github.com/user/repo\",\n  \"license\": \"MIT\"\n}\n```\n\n## Plugin Structure Example\n\n```\nmy-plugin/\n├── .claude-plugin/\n│   └── plugin.json       # Manifest (name, description, version, author)\n├── commands/             # Skills as Markdown files\n│   ├── task-1.md\n│   ├── task-2.md\n│   └── workflows/\n├── agents/               # Custom agent definitions\n│   ├── specialist-1.md\n│   ├── specialist-2.md\n│   └── configs/\n├── skills/               # Agent Skills with SKILL.md files\n│   ├── skill-1.md\n│   └── skill-2.md\n├── hooks/                # Event handlers in hooks.json\n│   └── hooks.json\n├── .mcp.json             # MCP server configurations\n├── .lsp.json             # LSP server configurations\n├── settings.json         # Default settings\n├── templates/\n│   └── issue-template.md\n├── scripts/\n│   ├── helper-1.sh\n│   └── helper-2.py\n├── docs/\n│   ├── README.md\n│   └── USAGE.md\n└── tests/\n    └── plugin.test.js\n```\n\n### LSP server configuration\n\nPlugins can include Language Server Protocol (LSP) support for real-time code intelligence. LSP servers provide diagnostics, code navigation, and symbol information as you work.\n\n**Configuration locations**:\n- `.lsp.json` file in the plugin root directory\n- Inline `lsp` key in `plugin.json`\n\n#### Field reference\n\n| Field | Required | Description |\n|-------|----------|-------------|\n| `command` | Yes | LSP server binary (must be in PATH) |\n| `extensionToLanguage` | Yes | Maps file extensions to language IDs |\n| `args` | No | Command-line arguments for the server |\n| `transport` | No | Communication method: `stdio` (default) or `socket` |\n| `env` | No | Environment variables for the server process |\n| `initializationOptions` | No | Options sent during LSP initialization |\n| `settings` | No | Workspace configuration passed to the server |\n| `workspaceFolder` | No | Override the workspace folder path |\n| `startupTimeout` | No | Maximum time (ms) to wait for server startup |\n| `shutdownTimeout` | No | Maximum time (ms) for graceful shutdown |\n| `restartOnCrash` | No | Automatically restart if the server crashes |\n| `maxRestarts` | No | Maximum restart attempts before giving up |\n\n#### Example configurations\n\n**Go (gopls)**:\n\n```json\n{\n  \"go\": {\n    \"command\": \"gopls\",\n    \"args\": [\"serve\"],\n    \"extensionToLanguage\": {\n      \".go\": \"go\"\n    }\n  }\n}\n```\n\n**Python (pyright)**:\n\n```json\n{\n  \"python\": {\n    \"command\": \"pyright-langserver\",\n    \"args\": [\"--stdio\"],\n    \"extensionToLanguage\": {\n      \".py\": \"python\",\n      \".pyi\": \"python\"\n    }\n  }\n}\n```\n\n**TypeScript**:\n\n```json\n{\n  \"typescript\": {\n    \"command\": \"typescript-language-server\",\n    \"args\": [\"--stdio\"],\n    \"extensionToLanguage\": {\n      \".ts\": \"typescript\",\n      \".tsx\": \"typescriptreact\",\n      \".js\": \"javascript\",\n      \".jsx\": \"javascriptreact\"\n    }\n  }\n}\n```\n\n#### Available LSP plugins\n\nThe official marketplace includes pre-configured LSP plugins:\n\n| Plugin | Language | Server Binary | Install Command |\n|--------|----------|---------------|----------------|\n| `pyright-lsp` | Python | `pyright-langserver` | `pip install pyright` |\n| `typescript-lsp` | TypeScript/JavaScript | `typescript-language-server` | `npm install -g typescript-language-server typescript` |\n| `rust-lsp` | Rust | `rust-analyzer` | Install via `rustup component add rust-analyzer` |\n\n#### LSP capabilities\n\nOnce configured, LSP servers provide:\n\n- **Instant diagnostics** — errors and warnings appear immediately after edits\n- **Code navigation** — go to definition, find references, implementations\n- **Hover information** — type signatures and documentation on hover\n- **Symbol listing** — browse symbols in the current file or workspace\n\n## Plugin Options (v2.1.83+)\n\nPlugins can declare user-configurable options in the manifest via `userConfig`. Values marked `sensitive: true` are stored in the system keychain rather than plain-text settings files:\n\n```json\n{\n  \"name\": \"my-plugin\",\n  \"version\": \"1.0.0\",\n  \"userConfig\": {\n    \"apiKey\": {\n      \"description\": \"API key for the service\",\n      \"sensitive\": true\n    },\n    \"region\": {\n      \"description\": \"Deployment region\",\n      \"default\": \"us-east-1\"\n    }\n  }\n}\n```\n\n## Persistent Plugin Data (`${CLAUDE_PLUGIN_DATA}`) (v2.1.78+)\n\nPlugins have access to a persistent state directory via the `${CLAUDE_PLUGIN_DATA}` environment variable. This directory is unique per plugin and survives across sessions, making it suitable for caches, databases, and other persistent state:\n\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"command\": \"node ${CLAUDE_PLUGIN_DATA}/track-usage.js\"\n      }\n    ]\n  }\n}\n```\n\nThe directory is created automatically when the plugin is installed. Files stored here persist until the plugin is uninstalled.\n\n## Inline Plugin via Settings (`source: 'settings'`) (v2.1.80+)\n\nPlugins can be defined inline in settings files as marketplace entries using the `source: 'settings'` field. This allows embedding a plugin definition directly without requiring a separate repository or marketplace:\n\n```json\n{\n  \"pluginMarketplaces\": [\n    {\n      \"name\": \"inline-tools\",\n      \"source\": \"settings\",\n      \"plugins\": [\n        {\n          \"name\": \"quick-lint\",\n          \"source\": \"./local-plugins/quick-lint\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n## Plugin Settings\n\nPlugins can ship a `settings.json` file to provide default configuration. This currently supports the `agent` key, which sets the main thread agent for the plugin:\n\n```json\n{\n  \"agent\": \"agents/specialist-1.md\"\n}\n```\n\nWhen a plugin includes `settings.json`, its defaults are applied on installation. Users can override these settings in their own project or user configuration.\n\n## Standalone vs Plugin Approach\n\n| Approach | Command Names | Configuration | Best For |\n|----------|---------------|---|---|\n| **Standalone** | `/hello` | Manual setup in CLAUDE.md | Personal, project-specific |\n| **Plugins** | `/plugin-name:hello` | Automated via plugin.json | Sharing, distribution, team use |\n\nUse **standalone slash commands** for quick personal workflows. Use **plugins** when you want to bundle multiple features, share with a team, or publish for distribution.\n\n## Practical Examples\n\n### Example 1: PR Review Plugin\n\n**File:** `.claude-plugin/plugin.json`\n\n```json\n{\n  \"name\": \"pr-review\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Complete PR review workflow with security, testing, and docs\",\n  \"author\": {\n    \"name\": \"Anthropic\"\n  },\n  \"repository\": \"https://github.com/anthropic/pr-review\",\n  \"license\": \"MIT\"\n}\n```\n\n**File:** `commands/review-pr.md`\n\n```markdown\n---\nname: Review PR\ndescription: Start comprehensive PR review with security and testing checks\n---\n\n# PR Review\n\nThis command initiates a complete pull request review including:\n\n1. Security analysis\n2. Test coverage verification\n3. Documentation updates\n4. Code quality checks\n5. Performance impact assessment\n```\n\n**File:** `agents/security-reviewer.md`\n\n```yaml\n---\nname: security-reviewer\ndescription: Security-focused code review\ntools: read, grep, diff\n---\n\n# Security Reviewer\n\nSpecializes in finding security vulnerabilities:\n- Authentication/authorization issues\n- Data exposure\n- Injection attacks\n- Secure configuration\n```\n\n**Installation:**\n\n```bash\n/plugin install pr-review\n\n# Result:\n# ✅ 3 slash commands installed\n# ✅ 3 subagents configured\n# ✅ 2 MCP servers connected\n# ✅ 4 hooks registered\n# ✅ Ready to use!\n```\n\n### Example 2: DevOps Plugin\n\n**Components:**\n\n```\ndevops-automation/\n├── commands/\n│   ├── deploy.md\n│   ├── rollback.md\n│   ├── status.md\n│   └── incident.md\n├── agents/\n│   ├── deployment-specialist.md\n│   ├── incident-commander.md\n│   └── alert-analyzer.md\n├── mcp/\n│   ├── github-config.json\n│   ├── kubernetes-config.json\n│   └── prometheus-config.json\n├── hooks/\n│   ├── pre-deploy.js\n│   ├── post-deploy.js\n│   └── on-error.js\n└── scripts/\n    ├── deploy.sh\n    ├── rollback.sh\n    └── health-check.sh\n```\n\n### Example 3: Documentation Plugin\n\n**Bundled Components:**\n\n```\ndocumentation/\n├── commands/\n│   ├── generate-api-docs.md\n│   ├── generate-readme.md\n│   ├── sync-docs.md\n│   └── validate-docs.md\n├── agents/\n│   ├── api-documenter.md\n│   ├── code-commentator.md\n│   └── example-generator.md\n├── mcp/\n│   ├── github-docs-config.json\n│   └── slack-announce-config.json\n└── templates/\n    ├── api-endpoint.md\n    ├── function-docs.md\n    └── adr-template.md\n```\n\n## Plugin Marketplace\n\nThe official Anthropic-managed plugin directory is `anthropics/claude-plugins-official`. Enterprise admins can also create private plugin marketplaces for internal distribution.\n\n```mermaid\ngraph TB\n    A[\"Plugin Marketplace\"]\n    B[\"Official<br/>anthropics/claude-plugins-official\"]\n    C[\"Community<br/>Marketplace\"]\n    D[\"Enterprise<br/>Private Registry\"]\n\n    A --> B\n    A --> C\n    A --> D\n\n    B -->|Categories| B1[\"Development\"]\n    B -->|Categories| B2[\"DevOps\"]\n    B -->|Categories| B3[\"Documentation\"]\n\n    C -->|Search| C1[\"DevOps Automation\"]\n    C -->|Search| C2[\"Mobile Dev\"]\n    C -->|Search| C3[\"Data Science\"]\n\n    D -->|Internal| D1[\"Company Standards\"]\n    D -->|Internal| D2[\"Legacy Systems\"]\n    D -->|Internal| D3[\"Compliance\"]\n\n    style A fill:#e1f5fe,stroke:#333,color:#333\n    style B fill:#e8f5e9,stroke:#333,color:#333\n    style C fill:#f3e5f5,stroke:#333,color:#333\n    style D fill:#fff3e0,stroke:#333,color:#333\n```\n\n### Marketplace Configuration\n\nEnterprise and advanced users can control marketplace behavior through settings:\n\n| Setting | Description |\n|---------|-------------|\n| `extraKnownMarketplaces` | Add additional marketplace sources beyond the defaults |\n| `strictKnownMarketplaces` | Control which marketplaces users are allowed to add |\n| `deniedPlugins` | Admin-managed blocklist to prevent specific plugins from being installed |\n\n### Additional Marketplace Features\n\n- **Default git timeout**: Increased from 30s to 120s for large plugin repositories\n- **Custom npm registries**: Plugins can specify custom npm registry URLs for dependency resolution\n- **Version pinning**: Lock plugins to specific versions for reproducible environments\n\n### Marketplace definition schema\n\nPlugin marketplaces are defined in `.claude-plugin/marketplace.json`:\n\n```json\n{\n  \"name\": \"my-team-plugins\",\n  \"owner\": \"my-org\",\n  \"plugins\": [\n    {\n      \"name\": \"code-standards\",\n      \"source\": \"./plugins/code-standards\",\n      \"description\": \"Enforce team coding standards\",\n      \"version\": \"1.2.0\",\n      \"author\": \"platform-team\"\n    },\n    {\n      \"name\": \"deploy-helper\",\n      \"source\": {\n        \"source\": \"github\",\n        \"repo\": \"my-org/deploy-helper\",\n        \"ref\": \"v2.0.0\"\n      },\n      \"description\": \"Deployment automation workflows\"\n    }\n  ]\n}\n```\n\n| Field | Required | Description |\n|-------|----------|-------------|\n| `name` | Yes | Marketplace name in kebab-case |\n| `owner` | Yes | Organization or user who maintains the marketplace |\n| `plugins` | Yes | Array of plugin entries |\n| `plugins[].name` | Yes | Plugin name (kebab-case) |\n| `plugins[].source` | Yes | Plugin source (path string or source object) |\n| `plugins[].description` | No | Brief plugin description |\n| `plugins[].version` | No | Semantic version string |\n| `plugins[].author` | No | Plugin author name |\n\n### Plugin source types\n\nPlugins can be sourced from multiple locations:\n\n| Source | Syntax | Example |\n|--------|--------|---------|\n| **Relative path** | String path | `\"./plugins/my-plugin\"` |\n| **GitHub** | `{ \"source\": \"github\", \"repo\": \"owner/repo\" }` | `{ \"source\": \"github\", \"repo\": \"acme/lint-plugin\", \"ref\": \"v1.0\" }` |\n| **Git URL** | `{ \"source\": \"url\", \"url\": \"...\" }` | `{ \"source\": \"url\", \"url\": \"https://git.internal/plugin.git\" }` |\n| **Git subdirectory** | `{ \"source\": \"git-subdir\", \"url\": \"...\", \"path\": \"...\" }` | `{ \"source\": \"git-subdir\", \"url\": \"https://github.com/org/monorepo.git\", \"path\": \"packages/plugin\" }` |\n| **npm** | `{ \"source\": \"npm\", \"package\": \"...\" }` | `{ \"source\": \"npm\", \"package\": \"@acme/claude-plugin\", \"version\": \"^2.0\" }` |\n| **pip** | `{ \"source\": \"pip\", \"package\": \"...\" }` | `{ \"source\": \"pip\", \"package\": \"claude-data-plugin\", \"version\": \">=1.0\" }` |\n\nGitHub and git sources support optional `ref` (branch/tag) and `sha` (commit hash) fields for version pinning.\n\n### Distribution methods\n\n**GitHub (recommended)**:\n```bash\n# Users add your marketplace\n/plugin marketplace add owner/repo-name\n```\n\n**Other git services** (full URL required):\n```bash\n/plugin marketplace add https://gitlab.com/org/marketplace-repo.git\n```\n\n**Private repositories**: Supported via git credential helpers or environment tokens. Users must have read access to the repository.\n\n**Official marketplace submission**: Submit plugins to the Anthropic-curated marketplace for broader distribution.\n\n### Strict mode\n\nControl how marketplace definitions interact with local `plugin.json` files:\n\n| Setting | Behavior |\n|---------|----------|\n| `strict: true` (default) | Local `plugin.json` is authoritative; marketplace entry supplements it |\n| `strict: false` | Marketplace entry is the entire plugin definition |\n\n**Organization restrictions** with `strictKnownMarketplaces`:\n\n| Value | Effect |\n|-------|--------|\n| Not set | No restrictions — users can add any marketplace |\n| Empty array `[]` | Lockdown — no marketplaces allowed |\n| Array of patterns | Allowlist — only matching marketplaces can be added |\n\n```json\n{\n  \"strictKnownMarketplaces\": [\n    \"my-org/*\",\n    \"github.com/trusted-vendor/*\"\n  ]\n}\n```\n\n> **Warning**: In strict mode with `strictKnownMarketplaces`, users can only install plugins from allowlisted marketplaces. This is useful for enterprise environments requiring controlled plugin distribution.\n\n## Plugin Installation & Lifecycle\n\n```mermaid\ngraph LR\n    A[\"Discover\"] -->|Browse| B[\"Marketplace\"]\n    B -->|Select| C[\"Plugin Page\"]\n    C -->|View| D[\"Components\"]\n    D -->|Install| E[\"/plugin install\"]\n    E -->|Extract| F[\"Configure\"]\n    F -->|Activate| G[\"Use\"]\n    G -->|Check| H[\"Update\"]\n    H -->|Available| G\n    G -->|Done| I[\"Disable\"]\n    I -->|Later| J[\"Enable\"]\n    J -->|Back| G\n```\n\n## Plugin Features Comparison\n\n| Feature | Slash Command | Skill | Subagent | Plugin |\n|---------|---------------|-------|----------|--------|\n| **Installation** | Manual copy | Manual copy | Manual config | One command |\n| **Setup Time** | 5 minutes | 10 minutes | 15 minutes | 2 minutes |\n| **Bundling** | Single file | Single file | Single file | Multiple |\n| **Versioning** | Manual | Manual | Manual | Automatic |\n| **Team Sharing** | Copy file | Copy file | Copy file | Install ID |\n| **Updates** | Manual | Manual | Manual | Auto-available |\n| **Dependencies** | None | None | None | May include |\n| **Marketplace** | No | No | No | Yes |\n| **Distribution** | Repository | Repository | Repository | Marketplace |\n\n## Plugin CLI Commands\n\nAll plugin operations are available as CLI commands:\n\n```bash\nclaude plugin install <name>@<marketplace>   # Install from a marketplace\nclaude plugin uninstall <name>               # Remove a plugin\nclaude plugin list                           # List installed plugins\nclaude plugin enable <name>                  # Enable a disabled plugin\nclaude plugin disable <name>                 # Disable a plugin\nclaude plugin validate                       # Validate plugin structure\n```\n\n## Installation Methods\n\n### From Marketplace\n```bash\n/plugin install plugin-name\n# or from CLI:\nclaude plugin install plugin-name@marketplace-name\n```\n\n### Enable / Disable (with auto-detected scope)\n```bash\n/plugin enable plugin-name\n/plugin disable plugin-name\n```\n\n### Local Plugin (for development)\n```bash\n# CLI flag for local testing (repeatable for multiple plugins)\nclaude --plugin-dir ./path/to/plugin\nclaude --plugin-dir ./plugin-a --plugin-dir ./plugin-b\n```\n\n### From Git Repository\n```bash\n/plugin install github:username/repo\n```\n\n## When to Create a Plugin\n\n```mermaid\ngraph TD\n    A[\"Should I create a plugin?\"]\n    A -->|Need multiple components| B{\"Multiple commands<br/>or subagents<br/>or MCPs?\"}\n    B -->|Yes| C[\"✅ Create Plugin\"]\n    B -->|No| D[\"Use Individual Feature\"]\n    A -->|Team workflow| E{\"Share with<br/>team?\"}\n    E -->|Yes| C\n    E -->|No| F[\"Keep as Local Setup\"]\n    A -->|Complex setup| G{\"Needs auto<br/>configuration?\"}\n    G -->|Yes| C\n    G -->|No| D\n```\n\n### Plugin Use Cases\n\n| Use Case | Recommendation | Why |\n|----------|-----------------|-----|\n| **Team Onboarding** | ✅ Use Plugin | Instant setup, all configurations |\n| **Framework Setup** | ✅ Use Plugin | Bundles framework-specific commands |\n| **Enterprise Standards** | ✅ Use Plugin | Central distribution, version control |\n| **Quick Task Automation** | ❌ Use Command | Overkill complexity |\n| **Single Domain Expertise** | ❌ Use Skill | Too heavy, use skill instead |\n| **Specialized Analysis** | ❌ Use Subagent | Create manually or use skill |\n| **Live Data Access** | ❌ Use MCP | Standalone, don't bundle |\n\n## Testing a Plugin\n\nBefore publishing, test your plugin locally using the `--plugin-dir` CLI flag (repeatable for multiple plugins):\n\n```bash\nclaude --plugin-dir ./my-plugin\nclaude --plugin-dir ./my-plugin --plugin-dir ./another-plugin\n```\n\nThis launches Claude Code with your plugin loaded, allowing you to:\n- Verify all slash commands are available\n- Test subagents and agents function correctly\n- Confirm MCP servers connect properly\n- Validate hook execution\n- Check LSP server configurations\n- Check for any configuration errors\n\n## Hot-Reload\n\nPlugins support hot-reload during development. When you modify plugin files, Claude Code can detect changes automatically. You can also force a reload with:\n\n```bash\n/reload-plugins\n```\n\nThis re-reads all plugin manifests, commands, agents, skills, hooks, and MCP/LSP configurations without restarting the session.\n\n## Managed Settings for Plugins\n\nAdministrators can control plugin behavior across an organization using managed settings:\n\n| Setting | Description |\n|---------|-------------|\n| `enabledPlugins` | Allowlist of plugins that are enabled by default |\n| `deniedPlugins` | Blocklist of plugins that cannot be installed |\n| `extraKnownMarketplaces` | Add additional marketplace sources beyond the defaults |\n| `strictKnownMarketplaces` | Restrict which marketplaces users are allowed to add |\n| `allowedChannelPlugins` | Control which plugins are permitted per release channel |\n\nThese settings can be applied at the organization level via managed configuration files and take precedence over user-level settings.\n\n## Plugin Security\n\nPlugin subagents run in a restricted sandbox. The following frontmatter keys are **not allowed** in plugin subagent definitions:\n\n- `hooks` -- Subagents cannot register event handlers\n- `mcpServers` -- Subagents cannot configure MCP servers\n- `permissionMode` -- Subagents cannot override the permission model\n\nThis ensures that plugins cannot escalate privileges or modify the host environment beyond their declared scope.\n\n## Publishing a Plugin\n\n**Steps to publish:**\n\n1. Create plugin structure with all components\n2. Write `.claude-plugin/plugin.json` manifest\n3. Create `README.md` with documentation\n4. Test locally with `claude --plugin-dir ./my-plugin`\n5. Submit to plugin marketplace\n6. Get reviewed and approved\n7. Published on marketplace\n8. Users can install with one command\n\n**Example submission:**\n\n```markdown\n# PR Review Plugin\n\n## Description\nComplete PR review workflow with security, testing, and documentation checks.\n\n## What's Included\n- 3 slash commands for different review types\n- 3 specialized subagents\n- GitHub and CodeQL MCP integration\n- Automated security scanning hooks\n\n## Installation\n```bash\n/plugin install pr-review\n```\n\n## Features\n✅ Security analysis\n✅ Test coverage checking\n✅ Documentation verification\n✅ Code quality assessment\n✅ Performance impact analysis\n\n## Usage\n```bash\n/review-pr\n/check-security\n/check-tests\n```\n\n## Requirements\n- Claude Code 1.0+\n- GitHub access\n- CodeQL (optional)\n```\n\n## Plugin vs Manual Configuration\n\n**Manual Setup (2+ hours):**\n- Install slash commands one by one\n- Create subagents individually\n- Configure MCPs separately\n- Set up hooks manually\n- Document everything\n- Share with team (hope they configure correctly)\n\n**With Plugin (2 minutes):**\n```bash\n/plugin install pr-review\n# ✅ Everything installed and configured\n# ✅ Ready to use immediately\n# ✅ Team can reproduce exact setup\n```\n\n## Best Practices\n\n### Do's ✅\n- Use clear, descriptive plugin names\n- Include comprehensive README\n- Version your plugin properly (semver)\n- Test all components together\n- Document requirements clearly\n- Provide usage examples\n- Include error handling\n- Tag appropriately for discovery\n- Maintain backward compatibility\n- Keep plugins focused and cohesive\n- Include comprehensive tests\n- Document all dependencies\n\n### Don'ts ❌\n- Don't bundle unrelated features\n- Don't hardcode credentials\n- Don't skip testing\n- Don't forget documentation\n- Don't create redundant plugins\n- Don't ignore versioning\n- Don't overcomplicate component dependencies\n- Don't forget to handle errors gracefully\n\n## Installation Instructions\n\n### Installing from Marketplace\n\n1. **Browse available plugins:**\n   ```bash\n   /plugin list\n   ```\n\n2. **View plugin details:**\n   ```bash\n   /plugin info plugin-name\n   ```\n\n3. **Install a plugin:**\n   ```bash\n   /plugin install plugin-name\n   ```\n\n### Installing from Local Path\n\n```bash\n/plugin install ./path/to/plugin-directory\n```\n\n### Installing from GitHub\n\n```bash\n/plugin install github:username/repo\n```\n\n### Listing Installed Plugins\n\n```bash\n/plugin list --installed\n```\n\n### Updating a Plugin\n\n```bash\n/plugin update plugin-name\n```\n\n### Disabling/Enabling a Plugin\n\n```bash\n# Temporarily disable\n/plugin disable plugin-name\n\n# Re-enable\n/plugin enable plugin-name\n```\n\n### Uninstalling a Plugin\n\n```bash\n/plugin uninstall plugin-name\n```\n\n## Related Concepts\n\nThe following Claude Code features work together with plugins:\n\n- **[Slash Commands](../01-slash-commands/)** - Individual commands bundled in plugins\n- **[Memory](../02-memory/)** - Persistent context for plugins\n- **[Skills](../03-skills/)** - Domain expertise that can be wrapped into plugins\n- **[Subagents](../04-subagents/)** - Specialized agents included as plugin components\n- **[MCP Servers](../05-mcp/)** - Model Context Protocol integrations bundled in plugins\n- **[Hooks](../06-hooks/)** - Event handlers that trigger plugin workflows\n\n## Complete Example Workflow\n\n### PR Review Plugin Full Workflow\n\n```\n1. User: /review-pr\n\n2. Plugin executes:\n   ├── pre-review.js hook validates git repo\n   ├── GitHub MCP fetches PR data\n   ├── security-reviewer subagent analyzes security\n   ├── test-checker subagent verifies coverage\n   └── performance-analyzer subagent checks performance\n\n3. Results synthesized and presented:\n   ✅ Security: No critical issues\n   ⚠️  Testing: Coverage 65% (recommend 80%+)\n   ✅ Performance: No significant impact\n   📝 12 recommendations provided\n```\n\n## Troubleshooting\n\n### Plugin Won't Install\n- Check Claude Code version compatibility: `/version`\n- Verify `plugin.json` syntax with a JSON validator\n- Check internet connection (for remote plugins)\n- Review permissions: `ls -la plugin/`\n\n### Components Not Loading\n- Verify paths in `plugin.json` match actual directory structure\n- Check file permissions: `chmod +x scripts/`\n- Review component file syntax\n- Check logs: `/plugin debug plugin-name`\n\n### MCP Connection Failed\n- Verify environment variables are set correctly\n- Check MCP server installation and health\n- Test MCP connection independently with `/mcp test`\n- Review MCP configuration in `mcp/` directory\n\n### Commands Not Available After Install\n- Ensure plugin was installed successfully: `/plugin list --installed`\n- Check if plugin is enabled: `/plugin status plugin-name`\n- Restart Claude Code: `exit` and reopen\n- Check for naming conflicts with existing commands\n\n### Hook Execution Issues\n- Verify hook files have correct permissions\n- Check hook syntax and event names\n- Review hook logs for error details\n- Test hooks manually if possible\n\n## Additional Resources\n\n- [Official Plugins Documentation](https://code.claude.com/docs/en/plugins)\n- [Discover Plugins](https://code.claude.com/docs/en/discover-plugins)\n- [Plugin Marketplaces](https://code.claude.com/docs/en/plugin-marketplaces)\n- [Plugins Reference](https://code.claude.com/docs/en/plugins-reference)\n- [MCP Server Reference](https://modelcontextprotocol.io/)\n- [Subagent Configuration Guide](../04-subagents/README.md)\n- [Hook System Reference](../06-hooks/README.md)\n"
  },
  {
    "path": "07-plugins/devops-automation/.claude-plugin/plugin.json",
    "content": "{\n  \"name\": \"devops-automation\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Complete DevOps automation for deployment, monitoring, and incident response\",\n  \"author\": {\n    \"name\": \"Community\"\n  },\n  \"license\": \"MIT\"\n}\n"
  },
  {
    "path": "07-plugins/devops-automation/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# DevOps Automation Plugin\n\nComplete DevOps automation for deployment, monitoring, and incident response.\n\n## Features\n\n✅ Automated deployments\n✅ Rollback procedures\n✅ System health monitoring\n✅ Incident response workflows\n✅ Kubernetes integration\n\n## Installation\n\n```bash\n/plugin install devops-automation\n```\n\n## What's Included\n\n### Slash Commands\n- `/deploy` - Deploy to production or staging\n- `/rollback` - Rollback to previous version\n- `/status` - Check system health\n- `/incident` - Handle production incidents\n\n### Subagents\n- `deployment-specialist` - Deployment operations\n- `incident-commander` - Incident coordination\n- `alert-analyzer` - System health analysis\n\n### MCP Servers\n- Kubernetes integration\n\n### Scripts\n- `deploy.sh` - Deployment automation\n- `rollback.sh` - Rollback automation\n- `health-check.sh` - Health check utilities\n\n### Hooks\n- `pre-deploy.js` - Pre-deployment validation\n- `post-deploy.js` - Post-deployment tasks\n\n## Usage\n\n### Deploy to Staging\n```\n/deploy staging\n```\n\n### Deploy to Production\n```\n/deploy production\n```\n\n### Rollback\n```\n/rollback production\n```\n\n### Check Status\n```\n/status\n```\n\n### Handle Incident\n```\n/incident\n```\n\n## Requirements\n\n- Claude Code 1.0+\n- Kubernetes CLI (kubectl)\n- Cluster access configured\n\n## Configuration\n\nSet up your Kubernetes config:\n```bash\nexport KUBECONFIG=~/.kube/config\n```\n\n## Example Workflow\n\n```\nUser: /deploy production\n\nClaude:\n1. Runs pre-deploy hook (validates kubectl, cluster connection)\n2. Delegates to deployment-specialist subagent\n3. Runs deploy.sh script\n4. Monitors deployment progress via Kubernetes MCP\n5. Runs post-deploy hook (waits for pods, smoke tests)\n6. Provides deployment summary\n\nResult:\n✅ Deployment complete\n📦 Version: v2.1.0\n🚀 Pods: 3/3 ready\n⏱️  Time: 2m 34s\n```\n"
  },
  {
    "path": "07-plugins/devops-automation/agents/alert-analyzer.md",
    "content": "---\nname: alert-analyzer\ndescription: Analyzes monitoring alerts and system metrics\ntools: read, grep, bash\n---\n\n# Alert Analyzer\n\nAnalyzes system health and alerts:\n- Alert correlation\n- Trend analysis\n- Root cause identification\n- Metric visualization\n- Proactive issue detection\n"
  },
  {
    "path": "07-plugins/devops-automation/agents/deployment-specialist.md",
    "content": "---\nname: deployment-specialist\ndescription: Handles all deployment operations\ntools: read, write, bash, grep\n---\n\n# Deployment Specialist\n\nExpert in deployment operations:\n- Blue-green deployments\n- Canary releases\n- Rollback procedures\n- Health checks\n- Database migrations\n"
  },
  {
    "path": "07-plugins/devops-automation/agents/incident-commander.md",
    "content": "---\nname: incident-commander\ndescription: Coordinates incident response\ntools: read, write, bash, grep\n---\n\n# Incident Commander\n\nManages incident response:\n- Severity assessment\n- Team coordination\n- Status updates\n- Resolution tracking\n- Post-mortem facilitation\n"
  },
  {
    "path": "07-plugins/devops-automation/commands/deploy.md",
    "content": "---\nname: Deploy\ndescription: Deploy application to production or staging\n---\n\n# Deploy Application\n\nExecute deployment workflow:\n\n1. Run pre-deployment checks\n2. Build application\n3. Run tests\n4. Deploy to target environment\n5. Run health checks\n6. Notify team on Slack\n"
  },
  {
    "path": "07-plugins/devops-automation/commands/incident.md",
    "content": "---\nname: Incident Response\ndescription: Handle production incidents with structured response\n---\n\n# Incident Response\n\nStructured incident response workflow:\n\n1. Create incident record\n2. Assess severity and impact\n3. Notify on-call team\n4. Gather diagnostic information\n5. Coordinate response efforts\n6. Document resolution\n7. Schedule post-mortem\n"
  },
  {
    "path": "07-plugins/devops-automation/commands/rollback.md",
    "content": "---\nname: Rollback\ndescription: Rollback to previous deployment\n---\n\n# Rollback Deployment\n\nRollback to previous stable version:\n\n1. Identify previous deployment\n2. Verify rollback target is healthy\n3. Execute rollback procedure\n4. Run health checks\n5. Notify team\n"
  },
  {
    "path": "07-plugins/devops-automation/commands/status.md",
    "content": "---\nname: System Status\ndescription: Check overall system health and status\n---\n\n# System Status Check\n\nCheck system health across all services:\n\n1. Query Kubernetes pod status\n2. Check database connections\n3. Monitor API response times\n4. Review error rates\n5. Check resource utilization\n6. Report overall health\n"
  },
  {
    "path": "07-plugins/devops-automation/hooks/post-deploy.js",
    "content": "#!/usr/bin/env node\n\n/**\n * Post-deployment hook\n * Runs after deployment completes\n */\n\nasync function postDeploy() {\n  console.log('Running post-deployment tasks...');\n\n  const { execSync } = require('child_process');\n\n  // Wait for pods to be ready\n  console.log('Waiting for pods to be ready...');\n  try {\n    execSync('kubectl wait --for=condition=ready pod -l app=myapp --timeout=300s', {\n      stdio: 'inherit'\n    });\n  } catch (error) {\n    console.error('❌ Pods failed to become ready');\n    process.exit(1);\n  }\n\n  // Run smoke tests\n  console.log('Running smoke tests...');\n  // Add your smoke test commands here\n\n  console.log('✅ Post-deployment tasks complete');\n}\n\npostDeploy().catch(error => {\n  console.error('Post-deploy hook failed:', error);\n  process.exit(1);\n});\n"
  },
  {
    "path": "07-plugins/devops-automation/hooks/pre-deploy.js",
    "content": "#!/usr/bin/env node\n\n/**\n * Pre-deployment hook\n * Validates environment and prerequisites before deployment\n */\n\nasync function preDeploy() {\n  console.log('Running pre-deployment checks...');\n\n  const { execSync } = require('child_process');\n\n  // Check if kubectl is installed\n  try {\n    execSync('which kubectl', { stdio: 'pipe' });\n  } catch (error) {\n    console.error('❌ kubectl not found. Please install Kubernetes CLI.');\n    process.exit(1);\n  }\n\n  // Check if connected to cluster\n  try {\n    execSync('kubectl cluster-info', { stdio: 'pipe' });\n  } catch (error) {\n    console.error('❌ Not connected to Kubernetes cluster');\n    process.exit(1);\n  }\n\n  console.log('✅ Pre-deployment checks passed');\n}\n\npreDeploy().catch(error => {\n  console.error('Pre-deploy hook failed:', error);\n  process.exit(1);\n});\n"
  },
  {
    "path": "07-plugins/devops-automation/mcp/kubernetes-config.json",
    "content": "{\n  \"mcpServers\": {\n    \"kubernetes\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-kubernetes\"],\n      \"env\": {\n        \"KUBECONFIG\": \"${KUBECONFIG}\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "07-plugins/devops-automation/scripts/deploy.sh",
    "content": "#!/bin/bash\nset -e\n\necho \"🚀 Starting deployment...\"\n\n# Load environment\nENV=${1:-staging}\necho \"📦 Target environment: $ENV\"\n\n# Pre-deployment checks\necho \"✓ Running pre-deployment checks...\"\nnpm run lint\nnpm test\n\n# Build\necho \"🔨 Building application...\"\nnpm run build\n\n# Deploy\necho \"🚢 Deploying to $ENV...\"\nkubectl apply -f k8s/$ENV/\n\n# Health check\necho \"🏥 Running health checks...\"\nsleep 10\ncurl -f http://api.$ENV.example.com/health\n\necho \"✅ Deployment complete!\"\n"
  },
  {
    "path": "07-plugins/devops-automation/scripts/health-check.sh",
    "content": "#!/bin/bash\n\necho \"🏥 System Health Check\"\necho \"====================\"\n\nENV=${1:-production}\n\n# Check API\necho -n \"API: \"\nif curl -sf http://api.$ENV.example.com/health > /dev/null; then\n  echo \"✅ Healthy\"\nelse\n  echo \"❌ Unhealthy\"\nfi\n\n# Check Database\necho -n \"Database: \"\nif pg_isready -h db.$ENV.example.com > /dev/null 2>&1; then\n  echo \"✅ Healthy\"\nelse\n  echo \"❌ Unhealthy\"\nfi\n\n# Check Pods\necho -n \"Kubernetes Pods: \"\nPODS_READY=$(kubectl get pods -n $ENV --no-headers | grep \"Running\" | wc -l)\nPODS_TOTAL=$(kubectl get pods -n $ENV --no-headers | wc -l)\necho \"$PODS_READY/$PODS_TOTAL ready\"\n\necho \"====================\"\n"
  },
  {
    "path": "07-plugins/devops-automation/scripts/rollback.sh",
    "content": "#!/bin/bash\nset -e\n\necho \"⏪ Starting rollback...\"\n\nENV=${1:-staging}\necho \"📦 Target environment: $ENV\"\n\n# Get previous deployment\nPREVIOUS=$(kubectl rollout history deployment/app -n $ENV | tail -2 | head -1 | awk '{print $1}')\necho \"🔄 Rolling back to revision: $PREVIOUS\"\n\n# Execute rollback\nkubectl rollout undo deployment/app -n $ENV\n\n# Wait for rollback\necho \"⏳ Waiting for rollback to complete...\"\nkubectl rollout status deployment/app -n $ENV\n\n# Health check\necho \"🏥 Running health checks...\"\nsleep 5\ncurl -f http://api.$ENV.example.com/health\n\necho \"✅ Rollback complete!\"\n"
  },
  {
    "path": "07-plugins/documentation/.claude-plugin/plugin.json",
    "content": "{\n  \"name\": \"documentation\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Comprehensive documentation generation and maintenance\",\n  \"author\": {\n    \"name\": \"Community\"\n  },\n  \"license\": \"MIT\"\n}\n"
  },
  {
    "path": "07-plugins/documentation/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Documentation Plugin\n\nComprehensive documentation generation and maintenance for your project.\n\n## Features\n\n✅ API documentation generation\n✅ README creation and updates\n✅ Documentation synchronization\n✅ Code comment improvements\n✅ Example generation\n\n## Installation\n\n```bash\n/plugin install documentation\n```\n\n## What's Included\n\n### Slash Commands\n- `/generate-api-docs` - Generate API documentation\n- `/generate-readme` - Create or update README\n- `/sync-docs` - Sync docs with code changes\n- `/validate-docs` - Validate documentation\n\n### Subagents\n- `api-documenter` - API documentation specialist\n- `code-commentator` - Code comment improvements\n- `example-generator` - Code example creation\n\n### Templates\n- `api-endpoint.md` - API endpoint documentation template\n- `function-docs.md` - Function documentation template\n- `adr-template.md` - Architecture Decision Record template\n\n### MCP Servers\n- GitHub integration for documentation syncing\n\n## Usage\n\n### Generate API Documentation\n```\n/generate-api-docs\n```\n\n### Create README\n```\n/generate-readme\n```\n\n### Sync Documentation\n```\n/sync-docs\n```\n\n### Validate Documentation\n```\n/validate-docs\n```\n\n## Requirements\n\n- Claude Code 1.0+\n- GitHub access (optional)\n\n## Example Workflow\n\n```\nUser: /generate-api-docs\n\nClaude:\n1. Scans all API endpoints in /src/api/\n2. Delegates to api-documenter subagent\n3. Extracts function signatures and JSDoc\n4. Organizes by module/endpoint\n5. Uses api-endpoint.md template\n6. Generates comprehensive markdown docs\n7. Includes curl, JavaScript, and Python examples\n\nResult:\n✅ API documentation generated\n📄 Files created:\n   - docs/api/users.md\n   - docs/api/auth.md\n   - docs/api/products.md\n📊 Coverage: 23/23 endpoints documented\n```\n\n## Templates Usage\n\n### API Endpoint Template\nUse for documenting REST API endpoints with full examples.\n\n### Function Documentation Template\nUse for documenting individual functions/methods.\n\n### ADR Template\nUse for documenting architectural decisions.\n\n## Configuration\n\nSet up GitHub token for documentation syncing:\n```bash\nexport GITHUB_TOKEN=\"your_github_token\"\n```\n\n## Best Practices\n\n- Keep documentation close to code\n- Update docs with code changes\n- Include practical examples\n- Validate regularly\n- Use templates for consistency\n"
  },
  {
    "path": "07-plugins/documentation/agents/api-documenter.md",
    "content": "---\nname: api-documenter\ndescription: API documentation specialist\ntools: read, write, grep\n---\n\n# API Documenter\n\nCreates comprehensive API documentation:\n- Endpoint documentation\n- Parameter descriptions\n- Response schemas\n- Code examples (curl, JS, Python)\n- Error codes\n"
  },
  {
    "path": "07-plugins/documentation/agents/code-commentator.md",
    "content": "---\nname: code-commentator\ndescription: Code comment and inline documentation specialist\ntools: read, write, edit\n---\n\n# Code Commentator\n\nImproves code documentation:\n- JSDoc/docstring comments\n- Inline explanations\n- Parameter descriptions\n- Return type documentation\n- Usage examples\n"
  },
  {
    "path": "07-plugins/documentation/agents/example-generator.md",
    "content": "---\nname: example-generator\ndescription: Code example and tutorial specialist\ntools: read, write\n---\n\n# Example Generator\n\nCreates practical code examples:\n- Getting started guides\n- Common use cases\n- Integration examples\n- Best practices\n- Troubleshooting scenarios\n"
  },
  {
    "path": "07-plugins/documentation/commands/generate-api-docs.md",
    "content": "---\nname: Generate API Documentation\ndescription: Generate comprehensive API documentation from source code\n---\n\n# API Documentation Generator\n\nGenerate complete API documentation:\n\n1. Scan API endpoints\n2. Extract function signatures and JSDoc\n3. Organize by module/endpoint\n4. Create markdown with examples\n5. Include request/response schemas\n6. Add error documentation\n"
  },
  {
    "path": "07-plugins/documentation/commands/generate-readme.md",
    "content": "---\nname: Generate README\ndescription: Create or update project README\n---\n\n# README Generator\n\nGenerate comprehensive README:\n\n1. Project overview and description\n2. Installation instructions\n3. Usage examples\n4. API documentation links\n5. Contributing guidelines\n6. License information\n"
  },
  {
    "path": "07-plugins/documentation/commands/sync-docs.md",
    "content": "---\nname: Sync Documentation\ndescription: Sync documentation with code changes\n---\n\n# Documentation Sync\n\nSynchronize documentation with codebase:\n\n1. Detect code changes\n2. Identify outdated documentation\n3. Update affected docs\n4. Verify examples still work\n5. Update version numbers\n"
  },
  {
    "path": "07-plugins/documentation/commands/validate-docs.md",
    "content": "---\nname: Validate Documentation\ndescription: Validate documentation for completeness and accuracy\n---\n\n# Documentation Validation\n\nValidate documentation quality:\n\n1. Check for broken links\n2. Verify code examples\n3. Ensure completeness\n4. Check formatting\n5. Validate against actual code\n"
  },
  {
    "path": "07-plugins/documentation/mcp/github-docs-config.json",
    "content": "{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "07-plugins/documentation/templates/adr-template.md",
    "content": "# ADR [Number]: [Title]\n\n## Status\n[Proposed | Accepted | Deprecated | Superseded]\n\n## Context\nWhat is the issue that we're seeing that is motivating this decision or change?\n\n## Decision\nWhat is the change that we're proposing and/or doing?\n\n## Consequences\nWhat becomes easier or more difficult to do because of this change?\n\n### Positive\n- Benefit 1\n- Benefit 2\n\n### Negative\n- Drawback 1\n- Drawback 2\n\n### Neutral\n- Consideration 1\n- Consideration 2\n\n## Alternatives Considered\nWhat other options were considered and why were they not chosen?\n\n### Alternative 1\nDescription and reason for not choosing.\n\n### Alternative 2\nDescription and reason for not choosing.\n\n## References\n- Related ADRs\n- External documentation\n- Discussion links\n"
  },
  {
    "path": "07-plugins/documentation/templates/api-endpoint.md",
    "content": "# [METHOD] /api/v1/[endpoint]\n\n## Description\nBrief explanation of what this endpoint does.\n\n## Authentication\nRequired authentication method (e.g., Bearer token).\n\n## Parameters\n\n### Path Parameters\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| id | string | Yes | Resource ID |\n\n### Query Parameters\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| page | integer | No | Page number (default: 1) |\n| limit | integer | No | Items per page (default: 20) |\n\n### Request Body\n```json\n{\n  \"field\": \"value\"\n}\n```\n\n## Responses\n\n### 200 OK\n```json\n{\n  \"success\": true,\n  \"data\": {\n    \"id\": \"123\",\n    \"name\": \"Example\"\n  }\n}\n```\n\n### 400 Bad Request\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"Invalid input\"\n  }\n}\n```\n\n### 404 Not Found\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"NOT_FOUND\",\n    \"message\": \"Resource not found\"\n  }\n}\n```\n\n## Examples\n\n### cURL\n```bash\ncurl -X GET \"https://api.example.com/api/v1/endpoint\" \\\n  -H \"Authorization: Bearer YOUR_TOKEN\" \\\n  -H \"Content-Type: application/json\"\n```\n\n### JavaScript\n```javascript\nconst response = await fetch('/api/v1/endpoint', {\n  headers: {\n    'Authorization': 'Bearer token',\n    'Content-Type': 'application/json'\n  }\n});\nconst data = await response.json();\n```\n\n### Python\n```python\nimport requests\n\nresponse = requests.get(\n    'https://api.example.com/api/v1/endpoint',\n    headers={'Authorization': 'Bearer token'}\n)\ndata = response.json()\n```\n\n## Rate Limits\n- 1000 requests per hour for authenticated users\n- 100 requests per hour for public endpoints\n\n## Related Endpoints\n- [GET /api/v1/related](#)\n- [POST /api/v1/related](#)\n"
  },
  {
    "path": "07-plugins/documentation/templates/function-docs.md",
    "content": "# Function: `functionName`\n\n## Description\nBrief description of what the function does.\n\n## Signature\n```typescript\nfunction functionName(param1: Type1, param2: Type2): ReturnType\n```\n\n## Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| param1 | Type1 | Yes | Description of param1 |\n| param2 | Type2 | No | Description of param2 |\n\n## Returns\n**Type**: `ReturnType`\n\nDescription of what is returned.\n\n## Throws\n- `Error`: When invalid input is provided\n- `TypeError`: When wrong type is passed\n\n## Examples\n\n### Basic Usage\n```typescript\nconst result = functionName('value1', 'value2');\nconsole.log(result);\n```\n\n### Advanced Usage\n```typescript\nconst result = functionName(\n  complexParam1,\n  { option: true }\n);\n```\n\n## Notes\n- Additional notes or warnings\n- Performance considerations\n- Best practices\n\n## See Also\n- [Related Function](#)\n- [API Documentation](#)\n"
  },
  {
    "path": "07-plugins/pr-review/.claude-plugin/plugin.json",
    "content": "{\n  \"name\": \"pr-review\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Complete PR review workflow with security, testing, and docs\",\n  \"author\": {\n    \"name\": \"Anthropic\"\n  },\n  \"license\": \"MIT\"\n}\n"
  },
  {
    "path": "07-plugins/pr-review/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# PR Review Plugin\n\nComplete PR review workflow with security, testing, and documentation checks.\n\n## Features\n\n✅ Security analysis\n✅ Test coverage checking\n✅ Documentation verification\n✅ Code quality assessment\n✅ Performance impact analysis\n\n## Installation\n\n```bash\n/plugin install pr-review\n```\n\n## What's Included\n\n### Slash Commands\n- `/review-pr` - Comprehensive PR review\n- `/check-security` - Security-focused review\n- `/check-tests` - Test coverage analysis\n\n### Subagents\n- `security-reviewer` - Security vulnerability detection\n- `test-checker` - Test coverage analysis\n- `performance-analyzer` - Performance impact evaluation\n\n### MCP Servers\n- GitHub integration for PR data\n\n### Hooks\n- `pre-review.js` - Pre-review validation\n\n## Usage\n\n### Basic PR Review\n```\n/review-pr\n```\n\n### Security Check Only\n```\n/check-security\n```\n\n### Test Coverage Check\n```\n/check-tests\n```\n\n## Requirements\n\n- Claude Code 1.0+\n- GitHub access\n- Git repository\n\n## Configuration\n\nSet up your GitHub token:\n```bash\nexport GITHUB_TOKEN=\"your_github_token\"\n```\n\n## Example Workflow\n\n```\nUser: /review-pr\n\nClaude:\n1. Runs pre-review hook (validates git repo)\n2. Fetches PR data via GitHub MCP\n3. Delegates security review to security-reviewer subagent\n4. Delegates testing to test-checker subagent\n5. Delegates performance to performance-analyzer subagent\n6. Synthesizes all findings\n7. Provides comprehensive review report\n\nResult:\n✅ Security: No critical issues found\n⚠️  Testing: Coverage is 65%, recommend 80%+\n✅ Performance: No significant impact\n📝 Recommendations: Add tests for edge cases\n```\n"
  },
  {
    "path": "07-plugins/pr-review/agents/performance-analyzer.md",
    "content": "---\nname: performance-analyzer\ndescription: Performance impact analysis\ntools: read, grep, bash\n---\n\n# Performance Analyzer\n\nEvaluates performance impact of changes:\n- Algorithm complexity\n- Database query efficiency\n- Memory usage\n- Caching opportunities\n"
  },
  {
    "path": "07-plugins/pr-review/agents/security-reviewer.md",
    "content": "---\nname: security-reviewer\ndescription: Security-focused code review\ntools: read, grep, diff\n---\n\n# Security Reviewer\n\nSpecializes in finding security vulnerabilities:\n- Authentication/authorization issues\n- Data exposure\n- Injection attacks\n- Secure configuration\n"
  },
  {
    "path": "07-plugins/pr-review/agents/test-checker.md",
    "content": "---\nname: test-checker\ndescription: Test coverage and quality analysis\ntools: read, bash, grep\n---\n\n# Test Checker\n\nAnalyzes test coverage and quality:\n- Coverage percentage\n- Missing test cases\n- Test quality assessment\n- Edge case identification\n"
  },
  {
    "path": "07-plugins/pr-review/commands/check-security.md",
    "content": "---\nname: Security Check\ndescription: Run security-focused code review\n---\n\n# Security Check\n\nPerform focused security analysis on code changes:\n\n1. Authentication/authorization checks\n2. Data exposure risks\n3. Injection vulnerabilities\n4. Cryptographic weaknesses\n5. Sensitive data in logs\n"
  },
  {
    "path": "07-plugins/pr-review/commands/check-tests.md",
    "content": "---\nname: Test Coverage Check\ndescription: Verify test coverage and quality\n---\n\n# Test Coverage Check\n\nAnalyze test coverage and quality:\n\n1. Check test coverage percentage\n2. Identify untested code paths\n3. Review test quality\n4. Suggest missing test cases\n5. Verify edge cases are covered\n"
  },
  {
    "path": "07-plugins/pr-review/commands/review-pr.md",
    "content": "---\nname: Review PR\ndescription: Start comprehensive PR review with security and testing checks\n---\n\n# PR Review\n\nThis command initiates a complete pull request review including:\n\n1. Security analysis\n2. Test coverage verification\n3. Documentation updates\n4. Code quality checks\n5. Performance impact assessment\n"
  },
  {
    "path": "07-plugins/pr-review/hooks/pre-review.js",
    "content": "#!/usr/bin/env node\n\n/**\n * Pre-review hook\n * Runs before starting PR review to ensure prerequisites are met\n */\n\nasync function preReview() {\n  console.log('Running pre-review checks...');\n\n  // Check if git repository\n  const { execSync } = require('child_process');\n  try {\n    execSync('git rev-parse --git-dir', { stdio: 'pipe' });\n  } catch (error) {\n    console.error('❌ Not a git repository');\n    process.exit(1);\n  }\n\n  // Check for uncommitted changes\n  try {\n    const status = execSync('git status --porcelain', { encoding: 'utf-8' });\n    if (status.trim()) {\n      console.warn('⚠️  Warning: Uncommitted changes detected');\n    }\n  } catch (error) {\n    console.error('❌ Failed to check git status');\n    process.exit(1);\n  }\n\n  console.log('✅ Pre-review checks passed');\n}\n\npreReview().catch(error => {\n  console.error('Pre-review hook failed:', error);\n  process.exit(1);\n});\n"
  },
  {
    "path": "07-plugins/pr-review/mcp/github-config.json",
    "content": "{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "08-checkpoints/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Checkpoints and Rewind\n\nCheckpoints 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.\n\n## Overview\n\nCheckpoints 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:\n- All messages exchanged\n- File modifications made\n- Tool usage history\n- Session context\n\nCheckpoints are invaluable when exploring different approaches, recovering from mistakes, or comparing alternative solutions.\n\n## Key Concepts\n\n| Concept | Description |\n|---------|-------------|\n| **Checkpoint** | Snapshot of conversation state including messages, files, and context |\n| **Rewind** | Return to a previous checkpoint, discarding subsequent changes |\n| **Branch Point** | Checkpoint from which multiple approaches are explored |\n\n## Accessing Checkpoints\n\nYou can access and manage checkpoints in two primary ways:\n\n### Using Keyboard Shortcut\nPress `Esc` twice (`Esc` + `Esc`) to open the checkpoint interface and browse saved checkpoints.\n\n### Using Slash Command\nUse the `/rewind` command (alias: `/checkpoint`) for quick access:\n\n```bash\n# Open rewind interface\n/rewind\n\n# Or use the alias\n/checkpoint\n```\n\n## Rewind Options\n\nWhen you rewind, you are presented with a menu of five options:\n\n1. **Restore code and conversation** -- Revert both files and messages to that checkpoint\n2. **Restore conversation** -- Rewind messages only, keep your current code as-is\n3. **Restore code** -- Revert file changes only, keep the full conversation history\n4. **Summarize from here** -- Compress the conversation from this point forward into an AI-generated summary instead of discarding it. The original messages are preserved in the transcript. You can optionally provide instructions to focus the summary on specific topics.\n5. **Never mind** -- Cancel and return to the current state\n\n## Automatic Checkpoints\n\nClaude Code automatically creates checkpoints for you:\n\n- **Every user prompt** - A new checkpoint is created with each user input\n- **Persistent** - Checkpoints persist across sessions\n- **Auto-cleaned** - Checkpoints are automatically cleaned up after 30 days\n\nThis means you can always rewind to any previous point in your conversation, from a few minutes ago to days before.\n\n## Use Cases\n\n| Scenario | Workflow |\n|----------|----------|\n| **Exploring Approaches** | Save → Try A → Save → Rewind → Try B → Compare |\n| **Safe Refactoring** | Save → Refactor → Test → If fail: Rewind |\n| **A/B Testing** | Save → Design A → Save → Rewind → Design B → Compare |\n| **Mistake Recovery** | Notice issue → Rewind to last good state |\n\n## Using Checkpoints\n\n### Viewing and Rewinding\n\nPress `Esc` twice or use `/rewind` to open the checkpoint browser. You'll see a list of all available checkpoints with timestamps. Select any checkpoint to rewind to that state.\n\n### Checkpoint Details\n\nEach checkpoint shows:\n- Timestamp of when it was created\n- Files that were modified\n- Number of messages in the conversation\n- Tools that were used\n\n## Practical Examples\n\n### Example 1: Exploring Different Approaches\n\n```\nUser: Let's add a caching layer to the API\n\nClaude: I'll add Redis caching to your API endpoints...\n[Makes changes at checkpoint A]\n\nUser: Actually, let's try in-memory caching instead\n\nClaude: I'll rewind to explore a different approach...\n[User presses Esc+Esc and rewinds to checkpoint A]\n[Implements in-memory caching at checkpoint B]\n\nUser: Now I can compare both approaches\n```\n\n### Example 2: Recovering from Mistakes\n\n```\nUser: Refactor the authentication module to use JWT\n\nClaude: I'll refactor the authentication module...\n[Makes extensive changes]\n\nUser: Wait, that broke the OAuth integration. Let's go back.\n\nClaude: I'll help you rewind to before the refactoring...\n[User presses Esc+Esc and selects the checkpoint before the refactor]\n\nUser: Let's try a more conservative approach this time\n```\n\n### Example 3: Safe Experimentation\n\n```\nUser: Let's try rewriting this in a functional style\n[Creates checkpoint before experiment]\n\nClaude: [Makes experimental changes]\n\nUser: The tests are failing. Let's rewind.\n[User presses Esc+Esc and rewinds to the checkpoint]\n\nClaude: I've rewound the changes. Let's try a different approach.\n```\n\n### Example 4: Branching Approaches\n\n```\nUser: I want to compare two database designs\n[Takes note of checkpoint - call it \"Start\"]\n\nClaude: I'll create the first design...\n[Implements Schema A]\n\nUser: Now let me go back and try the second approach\n[User presses Esc+Esc and rewinds to \"Start\"]\n\nClaude: Now I'll implement Schema B...\n[Implements Schema B]\n\nUser: Great! Now I have both schemas to choose from\n```\n\n## Checkpoint Retention\n\nClaude Code automatically manages your checkpoints:\n\n- Checkpoints are created automatically with every user prompt\n- Old checkpoints are retained for up to 30 days\n- Checkpoints are cleaned up automatically to prevent unlimited storage growth\n\n## Workflow Patterns\n\n### Branching Strategy for Exploration\n\nWhen exploring multiple approaches:\n\n```\n1. Start with initial implementation → Checkpoint A\n2. Try Approach 1 → Checkpoint B\n3. Rewind to Checkpoint A\n4. Try Approach 2 → Checkpoint C\n5. Compare results from B and C\n6. Choose best approach and continue\n```\n\n### Safe Refactoring Pattern\n\nWhen making significant changes:\n\n```\n1. Current state → Checkpoint (auto)\n2. Start refactoring\n3. Run tests\n4. If tests pass → Continue working\n5. If tests fail → Rewind and try different approach\n```\n\n## Best Practices\n\nSince checkpoints are created automatically, you can focus on your work without worrying about manually saving state. However, keep these practices in mind:\n\n### Using Checkpoints Effectively\n\n✅ **Do:**\n- Review available checkpoints before rewinding\n- Use rewind when you want to explore different directions\n- Keep checkpoints to compare different approaches\n- Understand what each rewind option does (restore code and conversation, restore conversation, restore code, or summarize)\n\n❌ **Don't:**\n- Rely on checkpoints alone for code preservation\n- Expect checkpoints to track external file system changes\n- Use checkpoints as a substitute for git commits\n\n## Configuration\n\nYou can toggle automatic checkpoints in your settings:\n\n```json\n{\n  \"autoCheckpoint\": true\n}\n```\n\n- `autoCheckpoint`: Enable or disable automatic checkpoint creation on every user prompt (default: `true`)\n\n## Limitations\n\nCheckpoints have the following limitations:\n\n- **Bash command changes NOT tracked** - Operations like `rm`, `mv`, `cp` on the filesystem are not captured in checkpoints\n- **External changes NOT tracked** - Changes made outside Claude Code (in your editor, terminal, etc.) are not captured\n- **Not a replacement for version control** - Use git for permanent, auditable changes to your codebase\n\n## Troubleshooting\n\n### Missing Checkpoints\n\n**Problem**: Expected checkpoint not found\n\n**Solution**:\n- Check if checkpoints were cleared\n- Verify that `autoCheckpoint` is enabled in your settings\n- Check disk space\n\n### Rewind Failed\n\n**Problem**: Cannot rewind to checkpoint\n\n**Solution**:\n- Ensure no uncommitted changes conflict\n- Check if checkpoint is corrupted\n- Try rewinding to a different checkpoint\n\n## Integration with Git\n\nCheckpoints complement (but don't replace) git:\n\n| Feature | Git | Checkpoints |\n|---------|-----|-------------|\n| Scope | File system | Conversation + files |\n| Persistence | Permanent | Session-based |\n| Granularity | Commits | Any point |\n| Speed | Slower | Instant |\n| Sharing | Yes | Limited |\n\nUse both together:\n1. Use checkpoints for rapid experimentation\n2. Use git commits for finalized changes\n3. Create checkpoint before git operations\n4. Commit successful checkpoint states to git\n\n## Quick Start Guide\n\n### Basic Workflow\n\n1. **Work normally** - Claude Code creates checkpoints automatically\n2. **Want to go back?** - Press `Esc` twice or use `/rewind`\n3. **Choose checkpoint** - Select from the list to rewind\n4. **Select what to restore** - Choose from restore code and conversation, restore conversation, restore code, summarize from here, or cancel\n5. **Continue working** - You're back at that point\n\n### Keyboard Shortcuts\n\n- **`Esc` + `Esc`** - Open checkpoint browser\n- **`/rewind`** - Alternative way to access checkpoints\n- **`/checkpoint`** - Alias for `/rewind`\n\n## Knowing When to Rewind: Context Monitoring\n\nCheckpoints let you go back — but how do you know *when* you should? As your conversation grows, Claude's context window fills up and model quality silently degrades. You might be shipping code from a half-blind model without realizing it.\n\n**[cc-context-stats](https://github.com/luongnv89/cc-context-stats)** solves this by adding real-time **context zones** to your Claude Code status bar. It tracks where you are in the context window — from **Plan** (green, safe to plan and code) through **Code** (yellow, avoid starting new plans) to **Dump** (orange, finish up and rewind). When you see the zone shift, you know it's time to checkpoint and start fresh instead of pushing through with degraded output.\n\n## Related Concepts\n\n- **[Advanced Features](../09-advanced-features/)** - Planning mode and other advanced capabilities\n- **[Memory Management](../02-memory/)** - Managing conversation history and context\n- **[Slash Commands](../01-slash-commands/)** - User-invoked shortcuts\n- **[Hooks](../06-hooks/)** - Event-driven automation\n- **[Plugins](../07-plugins/)** - Bundled extension packages\n\n## Additional Resources\n\n- [Official Checkpointing Documentation](https://code.claude.com/docs/en/checkpointing)\n- [Advanced Features Guide](../09-advanced-features/) - Extended thinking and other capabilities\n\n## Summary\n\nCheckpoints are an automatic feature in Claude Code that lets you safely explore different approaches without fear of losing work. Every user prompt creates a new checkpoint automatically, so you can rewind to any previous point in your session.\n\nKey benefits:\n- Experiment fearlessly with multiple approaches\n- Quickly recover from mistakes\n- Compare different solutions side-by-side\n- Integrate safely with version control systems\n\nRemember: checkpoints are not a replacement for git. Use checkpoints for rapid experimentation and git for permanent code changes.\n"
  },
  {
    "path": "08-checkpoints/checkpoint-examples.md",
    "content": "# Checkpoint Examples\n\nReal-world examples of using checkpoints effectively in Claude Code.\n\nNote: Checkpoints are created automatically with every user prompt. You do not need to manually save them. To rewind, press `Esc` twice (`Esc+Esc`) or use `/rewind` to open the checkpoint browser.\n\n## Example 1: Database Migration\n\n### Scenario\nYou need to migrate from MySQL to PostgreSQL but want to explore both a direct migration and a gradual dual-write approach.\n\n### Workflow\n\n```\nUser: Let's implement a direct migration from MySQL to PostgreSQL\n      [Checkpoint A created automatically]\n\nClaude: I'll implement the direct migration...\n[Changes database driver, updates queries, modifies schema]\n\nUser: Run the tests\n      [Checkpoint B created automatically]\n\nClaude: Running tests...\n❌ 15 tests failing - connection pool issues\n\nUser: This approach has issues. Let's try the dual-write pattern instead.\n[User presses Esc+Esc, selects Checkpoint A, chooses \"Restore code and conversation\"]\n\nUser: Now implement a dual-write pattern where we write to both databases\n\nClaude: I'll implement dual-write migration...\n[Implements dual-write layer, gradual migration strategy]\n\nUser: Run the tests\n\nClaude: Running tests...\n✅ All tests passing\n\nUser: The dual-write approach is clearly safer. Let's commit this.\n```\n\n## Example 2: Performance Optimization\n\n### Scenario\nMultiple performance optimization strategies to try.\n\n### Workflow\n\n```\nUser: Let's optimize the API response time. Current: 450ms\n      [Checkpoint \"Baseline\" created automatically]\n\nClaude: I'll add database query caching...\n[Implements Redis caching]\n\nUser: Run performance tests\n\nClaude: Results: 280ms average response time (38% improvement)\n\nUser: Let me try a different approach.\n[User presses Esc+Esc, selects \"Baseline\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Try database query optimization instead\n\nClaude: I'll optimize database queries...\n[Adds indexes, optimizes N+1 queries]\n\nUser: Run performance tests\n\nClaude: Results: 180ms average response time (60% improvement)\n\nUser: Let me also try a third approach.\n[User presses Esc+Esc, selects \"Baseline\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Try response compression and CDN\n\nClaude: I'll add compression and CDN...\n[Implements gzip, sets up CDN]\n\nUser: Run performance tests\n\nClaude: Results: 320ms average response time (29% improvement)\n\nUser: Query optimization was the best. Let me go back and combine it with caching.\n[User presses Esc+Esc, selects the checkpoint after query optimization, chooses \"Restore code and conversation\"]\n\nUser: Now add Redis caching on top of these optimized queries\n\nClaude: [Adds Redis caching on top of optimized queries]\n\nUser: Run performance tests\n\nClaude: Results: 95ms average response time (79% improvement) 🎉\n\nUser: Perfect! This is the winner. Let's commit this.\n```\n\n## Example 3: UI/UX Iteration\n\n### Scenario\nTrying different layouts for a dashboard.\n\n### Workflow\n\n```\nUser: Let's redesign the dashboard with a sidebar layout\n      [Checkpoint \"Start\" created automatically]\n\nClaude: [Implements sidebar layout]\n\nUser: Show me a screenshot\n\nClaude: [Shows screenshot]\n\nUser: The sidebar feels cramped. Let's try a top navigation instead.\n[User presses Esc+Esc, selects \"Start\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Try a top navigation layout\n\nClaude: [Implements top navigation]\n\nUser: Show me a screenshot\n\nClaude: [Shows screenshot]\n\nUser: Better, but let's try a card-based grid layout\n[User presses Esc+Esc, selects \"Start\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Try a card-based grid layout\n\nClaude: [Implements card grid]\n\nUser: Show me a screenshot\n\nClaude: [Shows screenshot]\n\nUser: This is great! But can we combine the top nav with the card grid?\n[User presses Esc+Esc, selects the checkpoint after the card grid, chooses \"Restore code and conversation\"]\n\nUser: Add top navigation to the card grid layout\n\nClaude: [Adds top navigation to card grid]\n\nUser: Perfect! This is the final design.\n```\n\n## Example 4: Debugging Session\n\n### Scenario\nHunting down a tricky bug with multiple hypotheses.\n\n### Workflow\n\n```\nUser: There's a memory leak in the application\n      [Checkpoint \"Before debugging\" created automatically]\n\nClaude: Let me investigate...\n[Analyzes code]\n\nUser: I think it's in the event listeners. Let's fix those.\n\nClaude: [Fixes event listener cleanup]\n\nUser: Run memory profiler\n\nClaude: Still leaking memory - event listeners weren't the issue\n\nUser: Let me go back and try a different hypothesis.\n[User presses Esc+Esc, selects \"Before debugging\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Maybe it's the database connections?\n\nClaude: [Implements connection pooling fixes]\n\nUser: Run memory profiler\n\nClaude: Still leaking - not the connections either\n\nUser: Let me go back and try another angle.\n[User presses Esc+Esc, selects \"Before debugging\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Let's check for circular references\n\nClaude: [Finds and fixes circular references in cache]\n\nUser: Run memory profiler\n\nClaude: ✅ Memory leak fixed! The circular references in the caching layer were the culprit.\n\nUser: Excellent! Let's commit this fix.\n```\n\n## Example 5: API Design Evolution\n\n### Scenario\nDesigning a REST API with multiple iterations.\n\n### Workflow\n\n```\nUser: Create a REST API for our blog platform\n      [Checkpoint \"Before API design\" created automatically]\n\nClaude: [Creates basic CRUD API]\n\nUser: This is too simple. Let's add pagination and filtering\n\nClaude: [Adds pagination and filtering]\n\nUser: We need better resource relationships\n\nClaude: [Implements HATEOAS links]\n\nUser: Actually, let's try GraphQL instead of REST\n[User presses Esc+Esc, selects \"Before API design\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Implement a GraphQL API for our blog platform instead\n\nClaude: [Implements GraphQL API]\n\nUser: I think REST is better for our use case.\n[User presses Esc+Esc, selects the checkpoint after HATEOAS, chooses \"Restore code and conversation\"]\n\nUser: Let's finalize the REST approach.\n```\n\n## Example 6: Configuration Management\n\n### Scenario\nTesting different configuration approaches.\n\n### Workflow\n\n```\nUser: Move configuration to environment variables\n      [Checkpoint \"Original config\" created automatically]\n\nClaude: [Implements env var configuration]\n\nUser: Test in development\n\nClaude: Works locally but deployment issues in production\n\nUser: Let me try a different approach.\n[User presses Esc+Esc, selects \"Original config\" checkpoint, chooses \"Restore code and conversation\"]\n\nUser: Try a config file approach with validation\n\nClaude: [Implements YAML config with JSON schema validation]\n\nUser: Test in development\n\nClaude: ✅ Works well, good validation errors\n\nUser: Can we also support env vars for sensitive values?\n\nClaude: [Adds env var override for secrets]\n\nUser: Test deployment\n\nClaude: ✅ All environments working correctly\n\nUser: Perfect! This is production-ready.\n```\n\n## Example 7: Test Strategy\n\n### Scenario\nImplementing comprehensive testing.\n\n### Workflow\n\n```\nUser: Add unit tests for the auth module\n      [Checkpoint created automatically]\n\nClaude: [Adds Jest unit tests]\n\nUser: Run tests\n\nClaude: 45 tests passing, 78% coverage\n\nUser: Add integration tests too\n\nClaude: [Adds integration tests]\n\nUser: Run tests\n\nClaude: 89 tests passing, 92% coverage, but tests are slow (3 minutes)\n\nUser: The tests are too slow. Let's optimize.\n\nClaude: [Optimizes test setup, adds parallel execution]\n\nUser: Run tests\n\nClaude: 89 tests passing, 92% coverage, 35 seconds ✅\n\nUser: Great! Now add E2E tests for critical paths\n\nClaude: [Adds Playwright E2E tests]\n\nUser: Run all tests\n\nClaude: 112 tests passing, 94% coverage, 2 minutes\n\nUser: Perfect balance of coverage and speed!\n```\n\n## Example 8: Using Summarize from Checkpoint\n\n### Scenario\nAfter a long debugging session, you want to condense the conversation while preserving context.\n\n### Workflow\n\n```\nUser: [After 20+ messages of debugging and exploration]\n\n[User presses Esc+Esc, selects an early checkpoint, chooses \"Summarize from here\"]\n[Optionally provides instructions: \"Focus on what we tried and what worked\"]\n\nClaude: [Generates a summary of the conversation from that point forward]\n[Original messages are preserved in the transcript]\n[The summary replaces the visible conversation, reducing context window usage]\n\nUser: Now let's continue with the approach that worked.\n```\n\n## Key Takeaways\n\n1. **Checkpoints are automatic**: Every user prompt creates a checkpoint -- no manual saving needed\n2. **Use Esc+Esc or /rewind**: These are the two ways to access the checkpoint browser\n3. **Choose the right restore option**: Restore code, conversation, both, or summarize depending on your needs\n4. **Don't fear experimentation**: Checkpoints make it safe to try radical changes\n5. **Combine with git**: Use checkpoints for exploration, git for finalized work\n6. **Summarize long sessions**: Use \"Summarize from here\" to keep conversations manageable\n"
  },
  {
    "path": "09-advanced-features/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Advanced Features\n\nComprehensive guide to Claude Code's advanced capabilities including planning mode, extended thinking, auto mode, background tasks, permission modes, print mode (non-interactive), session management, interactive features, channels, voice dictation, remote control, web sessions, desktop app, task list, prompt suggestions, git worktrees, sandboxing, managed settings, and configuration.\n\n## Table of Contents\n\n1. [Overview](#overview)\n2. [Planning Mode](#planning-mode)\n3. [Extended Thinking](#extended-thinking)\n4. [Auto Mode](#auto-mode)\n5. [Background Tasks](#background-tasks)\n6. [Scheduled Tasks](#scheduled-tasks)\n7. [Permission Modes](#permission-modes)\n8. [Headless Mode](#headless-mode)\n9. [Session Management](#session-management)\n10. [Interactive Features](#interactive-features)\n11. [Voice Dictation](#voice-dictation)\n12. [Channels](#channels)\n13. [Chrome Integration](#chrome-integration)\n14. [Remote Control](#remote-control)\n15. [Web Sessions](#web-sessions)\n16. [Desktop App](#desktop-app)\n17. [Task List](#task-list)\n18. [Prompt Suggestions](#prompt-suggestions)\n19. [Git Worktrees](#git-worktrees)\n20. [Sandboxing](#sandboxing)\n21. [Managed Settings (Enterprise)](#managed-settings-enterprise)\n22. [Configuration and Settings](#configuration-and-settings)\n23. [Best Practices](#best-practices)\n24. [Related Concepts](#related-concepts)\n\n---\n\n## Overview\n\nAdvanced 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.\n\n**Key advanced features include:**\n- **Planning Mode**: Create detailed implementation plans before coding\n- **Extended Thinking**: Deep reasoning for complex problems\n- **Auto Mode**: Background safety classifier reviews each action before execution (Research Preview)\n- **Background Tasks**: Run long operations without blocking the conversation\n- **Permission Modes**: Control what Claude can do (`default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`)\n- **Print Mode**: Run Claude Code non-interactively for automation and CI/CD (`claude -p`)\n- **Session Management**: Manage multiple work sessions\n- **Interactive Features**: Keyboard shortcuts, multi-line input, and command history\n- **Voice Dictation**: Push-to-talk voice input with 20-language STT support\n- **Channels**: MCP servers push messages into running sessions (Research Preview)\n- **Remote Control**: Control Claude Code from Claude.ai or the Claude app\n- **Web Sessions**: Run Claude Code in the browser at claude.ai/code\n- **Desktop App**: Standalone app for visual diff review and multiple sessions\n- **Task List**: Persistent task tracking across context compactions\n- **Prompt Suggestions**: Smart command suggestions based on context\n- **Git Worktrees**: Isolated worktree branches for parallel work\n- **Sandboxing**: OS-level filesystem and network isolation\n- **Managed Settings**: Enterprise deployment via plist, Registry, or managed files\n- **Configuration**: Customize behavior with JSON configuration files\n\n---\n\n## Planning Mode\n\nPlanning mode allows Claude to think through complex tasks before implementing them, creating a detailed plan that you can review and approve.\n\n### What is Planning Mode?\n\nPlanning mode is a two-phase approach:\n1. **Planning Phase**: Claude analyzes the task and creates a detailed implementation plan\n2. **Implementation Phase**: After approval, Claude executes the plan\n\n### When to Use Planning Mode\n\n✅ Use planning mode for:\n- Complex multi-file refactoring\n- New feature implementations\n- Architectural changes\n- Database migrations\n- Major API redesigns\n\n❌ Don't use planning mode for:\n- Simple bug fixes\n- Formatting changes\n- Single-file edits\n- Quick queries\n\n### Activating Planning Mode\n\n**Slash command**:\n```bash\n/plan Implement user authentication system\n```\n\n**CLI flag**:\n```bash\nclaude --permission-mode plan\n```\n\n**Set as default**:\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"plan\"\n  }\n}\n```\n\n**Keyboard shortcut**:\n- `Shift + Tab` - Toggle permission modes (including plan)\n- `Alt + M` - Toggle permission modes (Windows/Linux)\n\n### Benefits of Planning Mode\n\n- **Structured implementation approach**: Detailed breakdown of implementation steps\n- **Review and approval**: Approve or adjust the plan before execution\n- **Risk identification**: Identify potential issues before implementation\n- **Clear phases**: Organized implementation phases and milestones\n\n### Example: Feature Implementation\n\n```\nUser: /plan Add a real-time notification system\n\nClaude: I'll create a plan for implementing real-time notifications.\n\n## Implementation Plan\n\n### Phase 1: Infrastructure Setup\n1. Install WebSocket libraries (socket.io)\n2. Set up WebSocket server\n3. Configure connection management\n\n### Phase 2: Backend Implementation\n4. Create notification service\n5. Implement notification queue\n6. Add database schema for notifications\n7. Create API endpoints\n\n### Phase 3: Frontend Integration\n8. Set up WebSocket client\n9. Create notification UI components\n10. Implement notification state management\n11. Add notification permissions\n\n### Phase 4: Testing & Deployment\n12. Write unit tests\n13. Write integration tests\n14. Update documentation\n15. Deploy to staging\n\nEstimated time: 3-4 hours\nFiles to modify: 12\nNew files to create: 8\n\nReady to proceed? (yes/no/modify plan)\n\nUser: yes\n\nClaude: [Begins implementation following the plan]\n```\n\n### Plan Modifications\n\n```\nUser: Modify the plan - skip the queue for now, we'll add it later\n\nClaude: Updated plan:\n[Shows modified plan with queue removed]\n\nUser: Looks good, proceed\n\nClaude: [Implements modified plan]\n```\n\n### Planning Mode Configuration\n\nPlanning mode is activated via the CLI flag or slash command:\n\n```bash\n# Activate plan mode via CLI\nclaude --permission-mode plan\n\n# Or use the /plan slash command inside the REPL\n/plan Implement user authentication system\n```\n\n**Model alias for planning**: Use `opusplan` as a model alias to use Opus for planning and Sonnet for execution:\n\n```bash\nclaude --model opusplan \"design and implement the new API\"\n```\n\n**Edit plan externally**: Press `Ctrl+G` to open the current plan in your external editor for detailed modifications.\n\n---\n\n## Extended Thinking\n\nExtended thinking allows Claude to spend more time reasoning about complex problems before providing a solution.\n\n### What is Extended Thinking?\n\nExtended thinking is a deliberate, step-by-step reasoning process where Claude:\n- Breaks down complex problems\n- Considers multiple approaches\n- Evaluates trade-offs\n- Reasons through edge cases\n\n### Activating Extended Thinking\n\n**Keyboard shortcut**:\n- `Option + T` (macOS) / `Alt + T` (Windows/Linux) - Toggle extended thinking\n\n**Automatic activation**:\n- Enabled by default for all models (Opus 4.6, Sonnet 4.6, Haiku 4.5)\n- Opus 4.6: Adaptive reasoning with effort levels: `low` (○), `medium` (◐), `high` (●), `max` (Opus 4.6 only)\n- Other models: Fixed budget up to 31,999 tokens\n\n**Configuration methods**:\n- Toggle: `Alt+T` / `Option+T`, or via `/config`\n- View reasoning: `Ctrl+O` (verbose mode)\n- Set effort: `/effort` command or `--effort` flag\n\n**Custom budget**:\n```bash\nexport MAX_THINKING_TOKENS=1024\n```\n\n**Effort level** (Opus 4.6 only):\n```bash\nexport CLAUDE_CODE_EFFORT_LEVEL=high   # low (○), medium (◐), high (●), or max (Opus 4.6 only)\n```\n\n**CLI flag**:\n```bash\nclaude --effort high \"complex architectural review\"\n```\n\n**Slash command**:\n```\n/effort high\n```\n\n> **Note:** The keyword \"ultrathink\" in prompts activates deep reasoning mode. Effort levels `low`, `medium`, `high`, and `max` (Opus 4.6 only) control how much reasoning Claude performs.\n\n### Benefits of Extended Thinking\n\n- **Deep reasoning**: Spend more time thinking about complex problems\n- **Better architectural decisions**: Make informed choices with comprehensive evaluation\n- **Consideration of edge cases**: Think through potential issues and scenarios\n- **Thorough analysis**: Structured approach to complex problem-solving\n\n### Example: Architectural Decision\n\n```\nUser: /think Should we use microservices or a monolith for our e-commerce platform?\n\nClaude: Let me think through this architectural decision carefully...\n\n<extended_thinking>\n## Context Analysis\n- Team size: 5 developers\n- Expected traffic: 10k daily users initially\n- Need to scale to 100k+ users\n- Limited DevOps resources\n- 6-month timeline to MVP\n\n## Approach 1: Microservices\nPros:\n+ Independent scaling\n+ Technology flexibility\n+ Team independence\n+ Fault isolation\n\nCons:\n- Operational complexity\n- Network overhead\n- Distributed tracing needed\n- Requires DevOps expertise\n- Slower initial development\n\n## Approach 2: Monolith\nPros:\n+ Simpler deployment\n+ Faster initial development\n+ Easier debugging\n+ Lower operational overhead\n+ Single codebase\n\nCons:\n- Scaling challenges later\n- All-or-nothing deployments\n- Technology lock-in\n- Potential for tight coupling\n\n## Decision Factors\n1. Team size (5 devs) → Favors monolith\n2. DevOps resources (limited) → Favors monolith\n3. Timeline (6 months) → Favors monolith\n4. Future scale (100k users) → Achievable with monolith + caching\n5. Complexity budget → Limited\n\n## Recommendation\nStart with a **modular monolith**:\n- Single deployment unit\n- Clear module boundaries\n- Clean interfaces between modules\n- Prepare for future extraction to microservices if needed\n\nThis gives you:\n✓ Fast initial development\n✓ Low operational complexity\n✓ Option to extract services later\n✓ Clear architecture\n\nMigration path: When you reach 50k+ users or specific modules need independent scaling, extract those modules into microservices.\n</extended_thinking>\n\n**Recommendation**: Implement a modular monolith with clean module boundaries.\n\nThis approach balances your current constraints (team size, timeline, DevOps resources) with future scalability needs. You can migrate specific modules to microservices later when there's a clear business need.\n```\n\n### Extended Thinking Configuration\n\nExtended thinking is controlled via environment variables, keyboard shortcuts, and CLI flags:\n\n```bash\n# Set thinking token budget\nexport MAX_THINKING_TOKENS=16000\n\n# Set effort level (Opus 4.6 only): low (○), medium (◐), high (●), or max (Opus 4.6 only)\nexport CLAUDE_CODE_EFFORT_LEVEL=high\n```\n\nToggle during a session with `Alt+T` / `Option+T`, set effort with `/effort`, or configure via `/config`.\n\n---\n\n## Auto Mode\n\nAuto Mode is a Research Preview permission mode (March 2026) that uses a background safety classifier to review each action before execution. It allows Claude to work autonomously while blocking dangerous operations.\n\n### Requirements\n\n- **Plan**: Team plan (Enterprise and API rolling out)\n- **Model**: Claude Sonnet 4.6 or Opus 4.6\n- **Classifier**: Runs on Claude Sonnet 4.6 (adds extra token cost)\n\n### Enabling Auto Mode\n\n```bash\n# Unlock auto mode with CLI flag\nclaude --enable-auto-mode\n\n# Then cycle to it with Shift+Tab in the REPL\n```\n\nOr set it as the default permission mode:\n\n```bash\nclaude --permission-mode auto\n```\n\nSetting via config:\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"auto\"\n  }\n}\n```\n\n### How the Classifier Works\n\nThe background classifier evaluates each action using the following decision order:\n\n1. **Allow/deny rules** -- Explicit permission rules are checked first\n2. **Read-only/edits auto-approved** -- File reads and edits pass automatically\n3. **Classifier** -- The background classifier reviews the action\n4. **Fallback** -- Falls back to prompting after 3 consecutive or 20 total blocks\n\n### Default Blocked Actions\n\nAuto mode blocks the following by default:\n\n| Blocked Action | Example |\n|----------------|---------|\n| Pipe-to-shell installs | `curl \\| bash` |\n| Sending sensitive data externally | API keys, credentials over network |\n| Production deploys | Deploy commands targeting production |\n| Mass deletion | `rm -rf` on large directories |\n| IAM changes | Permission and role modifications |\n| Force push to main | `git push --force origin main` |\n\n### Default Allowed Actions\n\n| Allowed Action | Example |\n|----------------|---------|\n| Local file operations | Read, write, edit project files |\n| Declared dependency installs | `npm install`, `pip install` from manifest |\n| Read-only HTTP | `curl` for fetching documentation |\n| Pushing to current branch | `git push origin feature-branch` |\n\n### Configuring Auto Mode\n\n**Print default rules as JSON**:\n```bash\nclaude auto-mode defaults\n```\n\n**Configure trusted infrastructure** via the `autoMode.environment` managed setting for enterprise deployments. This allows administrators to define trusted CI/CD environments, deployment targets, and infrastructure patterns.\n\n### Fallback Behavior\n\nWhen the classifier is uncertain, auto mode falls back to prompting the user:\n- After **3 consecutive** classifier blocks\n- After **20 total** classifier blocks in a session\n\nThis ensures the user always retains control when the classifier cannot confidently approve an action.\n\n---\n\n## Background Tasks\n\nBackground tasks allow long-running operations to execute without blocking your conversation.\n\n### What Are Background Tasks?\n\nBackground tasks run asynchronously while you continue working:\n- Long test suites\n- Build processes\n- Database migrations\n- Deployment scripts\n- Analysis tools\n\n**Basic Usage:**\n```bash\nUser: Run tests in background\n\nClaude: Started task bg-1234\n\n/task list           # Show all tasks\n/task status bg-1234 # Check progress\n/task show bg-1234   # View output\n/task cancel bg-1234 # Cancel task\n```\n\n### Starting Background Tasks\n\n```\nUser: Run the full test suite in the background\n\nClaude: Starting tests in background (task-id: bg-1234)\nYou can continue working while tests run.\n\n[You can continue the conversation]\n\nUser: Meanwhile, let's refactor the auth module\n\nClaude: [Works on auth module while tests run in background]\n\n[Later, when tests complete]\n\nClaude: 📢 Background task bg-1234 completed:\n✅ 245 tests passed\n❌ 3 tests failed\nView results: /task show bg-1234\n```\n\n### Managing Background Tasks\n\n**List active tasks**:\n```\nUser: /task list\n\nActive background tasks:\n1. [bg-1234] Running tests (50% complete, 2min remaining)\n2. [bg-1235] Building Docker image (25% complete, 8min remaining)\n3. [bg-1236] Deploying to staging (90% complete, 30sec remaining)\n```\n\n**Check task status**:\n```\nUser: /task status bg-1234\n\nTask bg-1234: Running tests\nStatus: In progress\nProgress: 120/245 tests (49%)\nStarted: 2025-11-08 10:30:15\nEstimated completion: 2025-11-08 10:34:22\n```\n\n**View task output**:\n```\nUser: /task show bg-1234\n\n[Shows live output from the test run]\n```\n\n**Cancel task**:\n```\nUser: /task cancel bg-1234\n\nCancelled background task bg-1234\n```\n\n### Example: Parallel Development\n\n```\nUser: Run the build in the background\n\nClaude: Starting build... (task-id: bg-5001)\n\nUser: Also run the linter in background\n\nClaude: Starting linter... (task-id: bg-5002)\n\nUser: While those run, let's implement the new API endpoint\n\nClaude: [Implements API endpoint while build and linter run]\n\n[10 minutes later]\n\nClaude: 📢 Build completed successfully (bg-5001)\n📢 Linter found 12 issues (bg-5002)\n\nUser: Show me the linter issues\n\nClaude: [Shows linter output from bg-5002]\n```\n\n### Configuration\n\n```json\n{\n  \"backgroundTasks\": {\n    \"enabled\": true,\n    \"maxConcurrentTasks\": 5,\n    \"notifyOnCompletion\": true,\n    \"autoCleanup\": true,\n    \"logOutput\": true\n  }\n}\n```\n\n---\n\n## Scheduled Tasks\n\nScheduled Tasks let you run prompts automatically on a recurring schedule or as one-time reminders. Tasks are session-scoped — they run while Claude Code is active and are cleared when the session ends. Available since v2.1.72+.\n\n### The `/loop` command\n\n```bash\n# Explicit interval\n/loop 5m check if the deployment finished\n\n# Natural language\n/loop check build status every 30 minutes\n```\n\nStandard 5-field cron expressions are also supported for precise scheduling.\n\n### One-time reminders\n\nSet reminders that fire once at a specific time:\n\n```\nremind me at 3pm to push the release branch\nin 45 minutes, run the integration tests\n```\n\n### Managing scheduled tasks\n\n| Tool | Description |\n|------|-------------|\n| `CronCreate` | Create a new scheduled task |\n| `CronList` | List all active scheduled tasks |\n| `CronDelete` | Remove a scheduled task |\n\n**Limits and behavior**:\n- Up to **50 scheduled tasks** per session\n- Session-scoped — cleared when the session ends\n- Recurring tasks auto-expire after **3 days**\n- Tasks only fire while Claude Code is running — no catch-up for missed fires\n\n### Behavior details\n\n| Aspect | Detail |\n|--------|--------|\n| **Recurring jitter** | Up to 10% of the interval (max 15 minutes) |\n| **One-shot jitter** | Up to 90 seconds on :00/:30 boundaries |\n| **Missed fires** | No catch-up — skipped if Claude Code was not running |\n| **Persistence** | Not persisted across restarts |\n\n### Cloud Scheduled Tasks\n\nUse `/schedule` to create Cloud scheduled tasks that run on Anthropic infrastructure:\n\n```\n/schedule daily at 9am run the test suite and report failures\n```\n\nCloud scheduled tasks persist across restarts and do not require Claude Code to be running locally.\n\n### Disabling scheduled tasks\n\n```bash\nexport CLAUDE_CODE_DISABLE_CRON=1\n```\n\n### Example: monitoring a deployment\n\n```\n/loop 5m check the deployment status of the staging environment.\n        If the deploy succeeded, notify me and stop looping.\n        If it failed, show the error logs.\n```\n\n> **Tip**: Scheduled tasks are session-scoped. For persistent automation that survives restarts, use CI/CD pipelines, GitHub Actions, or Desktop App scheduled tasks instead.\n\n---\n\n## Permission Modes\n\nPermission modes control what actions Claude can take without explicit approval.\n\n### Available Permission Modes\n\n| Mode | Behavior |\n|---|---|\n| `default` | Read files only; prompts for all other actions |\n| `acceptEdits` | Read and edit files; prompts for commands |\n| `plan` | Read files only (research mode, no edits) |\n| `auto` | All actions with background safety classifier checks (Research Preview) |\n| `bypassPermissions` | All actions, no permission checks (dangerous) |\n| `dontAsk` | Only pre-approved tools execute; all others denied |\n\nCycle through modes with `Shift+Tab` in the CLI. Set a default with the `--permission-mode` flag or the `permissions.defaultMode` setting.\n\n### Activation Methods\n\n**Keyboard shortcut**:\n```bash\nShift + Tab  # Cycle through all 6 modes\n```\n\n**Slash command**:\n```bash\n/plan                  # Enter plan mode\n```\n\n**CLI flag**:\n```bash\nclaude --permission-mode plan\nclaude --permission-mode auto\n```\n\n**Setting**:\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"auto\"\n  }\n}\n```\n\n### Permission Mode Examples\n\n#### Default Mode\nClaude asks for confirmation on significant actions:\n\n```\nUser: Fix the bug in auth.ts\n\nClaude: I need to modify src/auth.ts to fix the bug.\nThe change will update the password validation logic.\n\nApprove this change? (yes/no/show)\n```\n\n#### Plan Mode\nReview implementation plan before execution:\n\n```\nUser: /plan Implement user authentication system\n\nClaude: I'll create a plan for implementing authentication.\n\n## Implementation Plan\n[Detailed plan with phases and steps]\n\nReady to proceed? (yes/no/modify)\n```\n\n#### Accept Edits Mode\nAutomatically accept file modifications:\n\n```\nUser: acceptEdits\nUser: Fix the bug in auth.ts\n\nClaude: [Makes changes without asking]\n```\n\n### Use Cases\n\n**Code Review**:\n```\nUser: claude --permission-mode plan\nUser: Review this PR and suggest improvements\n\nClaude: [Reads code, provides feedback, but cannot modify]\n```\n\n**Pair Programming**:\n```\nUser: claude --permission-mode default\nUser: Let's implement the feature together\n\nClaude: [Asks for approval before each change]\n```\n\n**Automated Tasks**:\n```\nUser: claude --permission-mode acceptEdits\nUser: Fix all linting issues in the codebase\n\nClaude: [Auto-accepts file edits without asking]\n```\n\n---\n\n## Headless Mode\n\nPrint mode (`claude -p`) allows Claude Code to run without interactive input, perfect for automation and CI/CD. This is the non-interactive mode, replacing the older `--headless` flag.\n\n### What is Print Mode?\n\nPrint mode enables:\n- Automated script execution\n- CI/CD integration\n- Batch processing\n- Scheduled tasks\n\n### Running in Print Mode (Non-Interactive)\n\n```bash\n# Run specific task\nclaude -p \"Run all tests\"\n\n# Process piped content\ncat error.log | claude -p \"Analyze these errors\"\n\n# CI/CD integration (GitHub Actions)\n- name: AI Code Review\n  run: claude -p \"Review PR\"\n```\n\n### Additional Print Mode Usage Examples\n\n```bash\n# Run a specific task with output capture\nclaude -p \"Run all tests and generate coverage report\"\n\n# With structured output\nclaude -p --output-format json \"Analyze code quality\"\n\n# With input from stdin\necho \"Analyze code quality\" | claude -p \"explain this\"\n```\n\n### Example: CI/CD Integration\n\n**GitHub Actions**:\n```yaml\n# .github/workflows/code-review.yml\nname: AI Code Review\n\non: [pull_request]\n\njobs:\n  review:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n\n      - name: Install Claude Code\n        run: npm install -g @anthropic-ai/claude-code\n\n      - name: Run Claude Code Review\n        env:\n          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}\n        run: |\n          claude -p --output-format json \\\n            --max-turns 3 \\\n            \"Review this PR for:\n            - Code quality issues\n            - Security vulnerabilities\n            - Performance concerns\n            - Test coverage\n            Output results as JSON\" > review.json\n\n      - name: Post Review Comment\n        uses: actions/github-script@v7\n        with:\n          script: |\n            const fs = require('fs');\n            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));\n            github.rest.issues.createComment({\n              issue_number: context.issue.number,\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              body: JSON.stringify(review, null, 2)\n            });\n```\n\n### Print Mode Configuration\n\nPrint mode (`claude -p`) supports several flags for automation:\n\n```bash\n# Limit autonomous turns\nclaude -p --max-turns 5 \"refactor this module\"\n\n# Structured JSON output\nclaude -p --output-format json \"analyze this codebase\"\n\n# With schema validation\nclaude -p --json-schema '{\"type\":\"object\",\"properties\":{\"issues\":{\"type\":\"array\"}}}' \\\n  \"find bugs in this code\"\n\n# Disable session persistence\nclaude -p --no-session-persistence \"one-off analysis\"\n```\n\n---\n\n## Session Management\n\nManage multiple Claude Code sessions effectively.\n\n### Session Management Commands\n\n| Command | Description |\n|---------|-------------|\n| `/resume` | Resume a conversation by ID or name |\n| `/rename` | Name the current session |\n| `/fork` | Fork current session into a new branch |\n| `claude -c` | Continue most recent conversation |\n| `claude -r \"session\"` | Resume session by name or ID |\n\n### Resuming Sessions\n\n**Continue last conversation**:\n```bash\nclaude -c\n```\n\n**Resume a named session**:\n```bash\nclaude -r \"auth-refactor\" \"finish this PR\"\n```\n\n**Rename the current session** (inside the REPL):\n```\n/rename auth-refactor\n```\n\n### Forking Sessions\n\nFork a session to try an alternative approach without losing the original:\n\n```\n/fork\n```\n\nOr from the CLI:\n```bash\nclaude --resume auth-refactor --fork-session \"try OAuth instead\"\n```\n\n### Session Persistence\n\nSessions are automatically saved and can be resumed:\n\n```bash\n# Continue last conversation\nclaude -c\n\n# Resume specific session by name or ID\nclaude -r \"auth-refactor\"\n\n# Resume and fork for experimentation\nclaude --resume auth-refactor --fork-session \"alternative approach\"\n```\n\n---\n\n## Interactive Features\n\n### Keyboard Shortcuts\n\nClaude Code supports keyboard shortcuts for efficiency. Here's the complete reference from official docs:\n\n| Shortcut | Description |\n|----------|-------------|\n| `Ctrl+C` | Cancel current input/generation |\n| `Ctrl+D` | Exit Claude Code |\n| `Ctrl+G` | Edit plan in external editor |\n| `Ctrl+L` | Clear terminal screen |\n| `Ctrl+O` | Toggle verbose output (view reasoning) |\n| `Ctrl+R` | Reverse search history |\n| `Ctrl+T` | Toggle task list view |\n| `Ctrl+B` | Background running tasks |\n| `Esc+Esc` | Rewind code/conversation |\n| `Shift+Tab` / `Alt+M` | Toggle permission modes |\n| `Option+P` / `Alt+P` | Switch model |\n| `Option+T` / `Alt+T` | Toggle extended thinking |\n\n**Line Editing (standard readline shortcuts):**\n\n| Shortcut | Action |\n|----------|--------|\n| `Ctrl + A` | Move to line start |\n| `Ctrl + E` | Move to line end |\n| `Ctrl + K` | Cut to end of line |\n| `Ctrl + U` | Cut to start of line |\n| `Ctrl + W` | Delete word backward |\n| `Ctrl + Y` | Paste (yank) |\n| `Tab` | Autocomplete |\n| `↑ / ↓` | Command history |\n\n### Customizing keybindings\n\nCreate custom keyboard shortcuts by running `/keybindings`, which opens `~/.claude/keybindings.json` for editing (v2.1.18+).\n\n**Configuration format**:\n\n```json\n{\n  \"$schema\": \"https://www.schemastore.org/claude-code-keybindings.json\",\n  \"bindings\": [\n    {\n      \"context\": \"Chat\",\n      \"bindings\": {\n        \"ctrl+e\": \"chat:externalEditor\",\n        \"ctrl+u\": null,\n        \"ctrl+k ctrl+s\": \"chat:stash\"\n      }\n    },\n    {\n      \"context\": \"Confirmation\",\n      \"bindings\": {\n        \"ctrl+a\": \"confirmation:yes\"\n      }\n    }\n  ]\n}\n```\n\nSet a binding to `null` to unbind a default shortcut.\n\n### Available contexts\n\nKeybindings are scoped to specific UI contexts:\n\n| Context | Key Actions |\n|---------|-------------|\n| **Chat** | `submit`, `cancel`, `cycleMode`, `modelPicker`, `thinkingToggle`, `undo`, `externalEditor`, `stash`, `imagePaste` |\n| **Confirmation** | `yes`, `no`, `previous`, `next`, `nextField`, `cycleMode`, `toggleExplanation` |\n| **Global** | `interrupt`, `exit`, `toggleTodos`, `toggleTranscript` |\n| **Autocomplete** | `accept`, `dismiss`, `next`, `previous` |\n| **HistorySearch** | `search`, `previous`, `next` |\n| **Settings** | Context-specific settings navigation |\n| **Tabs** | Tab switching and management |\n| **Help** | Help panel navigation |\n\nThere are 18 contexts total including `Transcript`, `Task`, `ThemePicker`, `Attachments`, `Footer`, `MessageSelector`, `DiffDialog`, `ModelPicker`, and `Select`.\n\n### Chord support\n\nKeybindings support chord sequences (multi-key combinations):\n\n```\n\"ctrl+k ctrl+s\"   → Two-key sequence: press ctrl+k, then ctrl+s\n\"ctrl+shift+p\"    → Simultaneous modifier keys\n```\n\n**Keystroke syntax**:\n- **Modifiers**: `ctrl`, `alt` (or `opt`), `shift`, `meta` (or `cmd`)\n- **Uppercase implies Shift**: `K` is equivalent to `shift+k`\n- **Special keys**: `escape`, `enter`, `return`, `tab`, `space`, `backspace`, `delete`, arrow keys\n\n### Reserved and conflicting keys\n\n| Key | Status | Notes |\n|-----|--------|-------|\n| `Ctrl+C` | Reserved | Cannot be rebound (interrupt) |\n| `Ctrl+D` | Reserved | Cannot be rebound (exit) |\n| `Ctrl+B` | Terminal conflict | tmux prefix key |\n| `Ctrl+A` | Terminal conflict | GNU Screen prefix key |\n| `Ctrl+Z` | Terminal conflict | Process suspend |\n\n> **Tip**: If a shortcut does not work, check for conflicts with your terminal emulator or multiplexer.\n\n### Tab Completion\n\nClaude Code provides intelligent tab completion:\n\n```\nUser: /rew<TAB>\n→ /rewind\n\nUser: /plu<TAB>\n→ /plugin\n\nUser: /plugin <TAB>\n→ /plugin install\n→ /plugin enable\n→ /plugin disable\n```\n\n### Command History\n\nAccess previous commands:\n\n```\nUser: <↑>  # Previous command\nUser: <↓>  # Next command\nUser: Ctrl+R  # Search history\n\n(reverse-i-search)`test': run all tests\n```\n\n### Multi-line Input\n\nFor complex queries, use multi-line mode:\n\n```bash\nUser: \\\n> Long complex prompt\n> spanning multiple lines\n> \\end\n```\n\n**Example:**\n\n```\nUser: \\\n> Implement a user authentication system\n> with the following requirements:\n> - JWT tokens\n> - Email verification\n> - Password reset\n> - 2FA support\n> \\end\n\nClaude: [Processes the multi-line request]\n```\n\n### Inline Editing\n\nEdit commands before sending:\n\n```\nUser: Deploy to prodcution<Backspace><Backspace>uction\n\n[Edit in-place before sending]\n```\n\n### Vim Mode\n\nEnable Vi/Vim keybindings for text editing:\n\n**Activation**:\n- Use `/vim` command or `/config` to enable\n- Mode switching with `Esc` for NORMAL, `i/a/o` for INSERT\n\n**Navigation keys**:\n- `h` / `l` - Move left/right\n- `j` / `k` - Move down/up\n- `w` / `b` / `e` - Move by word\n- `0` / `$` - Move to line start/end\n- `gg` / `G` - Jump to start/end of text\n\n**Text objects**:\n- `iw` / `aw` - Inner/around word\n- `i\"` / `a\"` - Inner/around quoted string\n- `i(` / `a(` - Inner/around parentheses\n\n### Bash Mode\n\nExecute shell commands directly with `!` prefix:\n\n```bash\n! npm test\n! git status\n! cat src/index.js\n```\n\nUse this for quick command execution without switching contexts.\n\n---\n\n## Voice Dictation\n\nVoice Dictation provides push-to-talk voice input for Claude Code, allowing you to speak your prompts instead of typing them.\n\n### Activating Voice Dictation\n\n```\n/voice\n```\n\n### Features\n\n| Feature | Description |\n|---------|-------------|\n| **Push-to-talk** | Hold a key to record, release to send |\n| **20 languages** | Speech-to-text supports 20 languages |\n| **Custom keybinding** | Configure the push-to-talk key via `/keybindings` |\n| **Account requirement** | Requires a Claude.ai account for STT processing |\n\n### Configuration\n\nCustomize the push-to-talk keybinding in your keybindings file (`/keybindings`). Voice dictation uses your Claude.ai account for speech-to-text processing.\n\n---\n\n## Channels\n\nChannels (Research Preview) allow MCP servers to push messages into running Claude Code sessions, enabling real-time integrations with external services.\n\n### Subscribing to Channels\n\n```bash\n# Subscribe to channel plugins at startup\nclaude --channels discord,telegram\n```\n\n### Supported Integrations\n\n| Integration | Description |\n|-------------|-------------|\n| **Discord** | Receive and respond to Discord messages in your session |\n| **Telegram** | Receive and respond to Telegram messages in your session |\n\n### Configuration\n\n**Managed setting** for enterprise deployments:\n\n```json\n{\n  \"allowedChannelPlugins\": [\"discord\", \"telegram\"]\n}\n```\n\nThe `allowedChannelPlugins` managed setting controls which channel plugins are permitted across the organization.\n\n### How It Works\n\n1. MCP servers act as channel plugins that connect to external services\n2. Incoming messages are pushed into the active Claude Code session\n3. Claude can read and respond to messages within the session context\n4. Channel plugins must be approved via the `allowedChannelPlugins` managed setting\n\n---\n\n## Chrome Integration\n\nChrome Integration connects Claude Code to your Chrome or Microsoft Edge browser for live web automation and debugging. This is a beta feature available since v2.0.73+ (Edge support added in v1.0.36+).\n\n### Enabling Chrome Integration\n\n**At startup**:\n\n```bash\nclaude --chrome      # Enable Chrome connection\nclaude --no-chrome   # Disable Chrome connection\n```\n\n**Within a session**:\n\n```\n/chrome\n```\n\nSelect \"Enabled by default\" to activate Chrome Integration for all future sessions. Claude Code shares your browser's login state, so it can interact with authenticated web apps.\n\n### Capabilities\n\n| Capability | Description |\n|------------|-------------|\n| **Live debugging** | Read console logs, inspect DOM elements, debug JavaScript in real time |\n| **Design verification** | Compare rendered pages against design mockups |\n| **Form validation** | Test form submissions, input validation, and error handling |\n| **Web app testing** | Interact with authenticated apps (Gmail, Google Docs, Notion, etc.) |\n| **Data extraction** | Scrape and process content from web pages |\n| **Session recording** | Record browser interactions as GIF files |\n\n### Site-level permissions\n\nThe Chrome extension manages per-site access. Grant or revoke access for specific sites at any time through the extension popup. Claude Code only interacts with sites you have explicitly allowed.\n\n### How it works\n\nClaude Code controls the browser in a visible window — you can watch actions happen in real time. When the browser encounters a login page or CAPTCHA, Claude pauses and waits for you to handle it manually before continuing.\n\n### Known limitations\n\n- **Browser support**: Chrome and Edge only — Brave, Arc, and other Chromium browsers are not supported\n- **WSL**: Not available in Windows Subsystem for Linux\n- **Third-party providers**: Not supported with Bedrock, Vertex, or Foundry API providers\n- **Service worker idle**: The Chrome extension service worker may go idle during extended sessions\n\n> **Tip**: Chrome Integration is a beta feature. Browser support may expand in future releases.\n\n---\n\n## Remote Control\n\nRemote Control lets you continue a locally running Claude Code session from your phone, tablet, or any browser. Your local session keeps running on your machine — nothing moves to the cloud. Available on Pro, Max, Team, and Enterprise plans (v2.1.51+).\n\n### Starting Remote Control\n\n**From the CLI**:\n\n```bash\n# Start with default session name\nclaude remote-control\n\n# Start with a custom name\nclaude remote-control --name \"Auth Refactor\"\n```\n\n**From within a session**:\n\n```\n/remote-control\n/remote-control \"Auth Refactor\"\n```\n\n**Available flags**:\n\n| Flag | Description |\n|------|-------------|\n| `--name \"title\"` | Custom session title for easy identification |\n| `--verbose` | Show detailed connection logs |\n| `--sandbox` | Enable filesystem and network isolation |\n| `--no-sandbox` | Disable sandboxing (default) |\n\n### Connecting to a session\n\nThree ways to connect from another device:\n\n1. **Session URL** — Printed to the terminal when the session starts; open in any browser\n2. **QR code** — Press `spacebar` after starting to display a scannable QR code\n3. **Find by name** — Browse your sessions at claude.ai/code or in the Claude mobile app (iOS/Android)\n\n### Security\n\n- **No inbound ports** opened on your machine\n- **Outbound HTTPS only** over TLS\n- **Scoped credentials** — multiple short-lived, narrowly scoped tokens\n- **Session isolation** — each remote session is independent\n\n### Remote Control vs Claude Code on the web\n\n| Aspect | Remote Control | Claude Code on Web |\n|--------|---------------|-------------------|\n| **Execution** | Runs on your machine | Runs on Anthropic cloud |\n| **Local tools** | Full access to local MCP servers, files, and CLI | No local dependencies |\n| **Use case** | Continue local work from another device | Start fresh from any browser |\n\n### Limitations\n\n- One remote session per Claude Code instance\n- Terminal must stay open on the host machine\n- Session times out after ~10 minutes if the network is unreachable\n\n### Use cases\n\n- Control Claude Code from a mobile device or tablet while away from your desk\n- Use the richer claude.ai UI while maintaining local tool execution\n- Quick code reviews on the go with your full local development environment\n\n---\n\n## Web Sessions\n\nWeb Sessions allow you to run Claude Code directly in the browser at claude.ai/code, or create web sessions from the CLI.\n\n### Creating a Web Session\n\n```bash\n# Create a new web session from the CLI\nclaude --remote \"implement the new API endpoints\"\n```\n\nThis starts a Claude Code session on claude.ai that you can access from any browser.\n\n### Resuming Web Sessions Locally\n\nIf you started a session on the web and want to continue it locally:\n\n```bash\n# Resume a web session in the local terminal\nclaude --teleport\n```\n\nOr from within an interactive REPL:\n```\n/teleport\n```\n\n### Use Cases\n\n- Start work on one machine and continue on another\n- Share a session URL with team members\n- Use the web UI for visual diff review, then switch to terminal for execution\n\n---\n\n## Desktop App\n\nThe Claude Code Desktop App provides a standalone application with visual diff review, parallel sessions, and integrated connectors. Available for macOS and Windows (Pro, Max, Team, and Enterprise plans).\n\n### Installation\n\nDownload from [claude.ai](https://claude.ai) for your platform:\n- **macOS**: Universal build (Apple Silicon and Intel)\n- **Windows**: x64 and ARM64 installers available\n\nSee the [Desktop Quickstart](https://code.claude.com/docs/en/desktop-quickstart) for setup instructions.\n\n### Handing off from CLI\n\nTransfer your current CLI session to the Desktop App:\n\n```\n/desktop\n```\n\n### Core features\n\n| Feature | Description |\n|---------|-------------|\n| **Diff view** | File-by-file visual review with inline comments; Claude reads comments and revises |\n| **App preview** | Auto-starts dev servers with an embedded browser for live verification |\n| **PR monitoring** | GitHub CLI integration with auto-fix CI failures and auto-merge when checks pass |\n| **Parallel sessions** | Multiple sessions in the sidebar with automatic Git worktree isolation |\n| **Scheduled tasks** | Recurring tasks (hourly, daily, weekdays, weekly) that run while the app is open |\n| **Rich rendering** | Code, markdown, and diagram rendering with syntax highlighting |\n\n### App preview configuration\n\nConfigure dev server behavior in `.claude/launch.json`:\n\n```json\n{\n  \"command\": \"npm run dev\",\n  \"port\": 3000,\n  \"readyPattern\": \"ready on\",\n  \"persistCookies\": true\n}\n```\n\n### Connectors\n\nConnect external services for richer context:\n\n| Connector | Capability |\n|-----------|------------|\n| **GitHub** | PR monitoring, issue tracking, code review |\n| **Slack** | Notifications, channel context |\n| **Linear** | Issue tracking, sprint management |\n| **Notion** | Documentation, knowledge base access |\n| **Asana** | Task management, project tracking |\n| **Calendar** | Schedule awareness, meeting context |\n\n> **Note**: Connectors are not available for remote (cloud) sessions.\n\n### Remote and SSH sessions\n\n- **Remote sessions**: Run on Anthropic cloud infrastructure; continue even when the app is closed. Accessible from claude.ai/code or the Claude mobile app\n- **SSH sessions**: Connect to remote machines over SSH with full access to the remote filesystem and tools. Claude Code must be installed on the remote machine\n\n### Permission modes in Desktop\n\nThe Desktop App supports the same 4 permission modes as the CLI:\n\n| Mode | Behavior |\n|------|----------|\n| **Ask permissions** (default) | Review and approve every edit and command |\n| **Auto accept edits** | File edits auto-approved; commands require manual approval |\n| **Plan mode** | Review approach before any changes are made |\n| **Bypass permissions** | Automatic execution (sandbox-only, admin-controlled) |\n\n### Enterprise features\n\n- **Admin console**: Control Code tab access and permission settings for the organization\n- **MDM deployment**: Deploy via MDM on macOS or MSIX on Windows\n- **SSO integration**: Require single sign-on for organization members\n- **Managed settings**: Centrally manage team configuration and model availability\n\n---\n\n## Task List\n\nThe Task List feature provides persistent task tracking that survives context compactions (when the conversation history is trimmed to fit the context window).\n\n### Toggling the Task List\n\nPress `Ctrl+T` to toggle the task list view on or off during a session.\n\n### Persistent Tasks\n\nTasks persist across context compactions, ensuring that long-running work items are not lost when the conversation context is trimmed. This is particularly useful for complex, multi-step implementations.\n\n### Named Task Directories\n\nUse the `CLAUDE_CODE_TASK_LIST_ID` environment variable to create named task directories shared across sessions:\n\n```bash\nexport CLAUDE_CODE_TASK_LIST_ID=my-project-sprint-3\n```\n\nThis allows multiple sessions to share the same task list, making it useful for team workflows or multi-session projects.\n\n---\n\n## Prompt Suggestions\n\nPrompt Suggestions display grayed-out example commands based on your git history and current conversation context.\n\n### How It Works\n\n- Suggestions appear as grayed-out text below your input prompt\n- Press `Tab` to accept the suggestion\n- Press `Enter` to accept and immediately submit\n- Suggestions are context-aware, drawing from git history and conversation state\n\n### Disabling Prompt Suggestions\n\n```bash\nexport CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false\n```\n\n---\n\n## Git Worktrees\n\nGit Worktrees allow you to start Claude Code in an isolated worktree, enabling parallel work on different branches without stashing or switching.\n\n### Starting in a Worktree\n\n```bash\n# Start Claude Code in an isolated worktree\nclaude --worktree\n# or\nclaude -w\n```\n\n### Worktree Location\n\nWorktrees are created at:\n```\n<repo>/.claude/worktrees/<name>\n```\n\n### Sparse Checkout for Monorepos\n\nUse the `worktree.sparsePaths` setting to perform sparse-checkout in monorepos, reducing disk usage and clone time:\n\n```json\n{\n  \"worktree\": {\n    \"sparsePaths\": [\"packages/my-package\", \"shared/\"]\n  }\n}\n```\n\n### Worktree Tools and Hooks\n\n| Item | Description |\n|------|-------------|\n| `ExitWorktree` | Tool to exit and clean up the current worktree |\n| `WorktreeCreate` | Hook event fired when a worktree is created |\n| `WorktreeRemove` | Hook event fired when a worktree is removed |\n\n### Auto-Cleanup\n\nIf no changes are made in the worktree, it is automatically cleaned up when the session ends.\n\n### Use Cases\n\n- Work on a feature branch while keeping main branch untouched\n- Run tests in isolation without affecting the working directory\n- Try experimental changes in a disposable environment\n- Sparse-checkout specific packages in monorepos for faster startup\n\n---\n\n## Sandboxing\n\nSandboxing provides OS-level filesystem and network isolation for Bash commands executed by Claude Code. This is complementary to permission rules and provides an additional security layer.\n\n### Enabling Sandboxing\n\n**Slash command**:\n```\n/sandbox\n```\n\n**CLI flags**:\n```bash\nclaude --sandbox       # Enable sandboxing\nclaude --no-sandbox    # Disable sandboxing\n```\n\n### Configuration Settings\n\n| Setting | Description |\n|---------|-------------|\n| `sandbox.enabled` | Enable or disable sandboxing |\n| `sandbox.failIfUnavailable` | Fail if sandboxing cannot be activated |\n| `sandbox.filesystem.allowWrite` | Paths allowed for write access |\n| `sandbox.filesystem.allowRead` | Paths allowed for read access |\n| `sandbox.filesystem.denyRead` | Paths denied for read access |\n| `sandbox.enableWeakerNetworkIsolation` | Enable weaker network isolation on macOS |\n\n### Example Configuration\n\n```json\n{\n  \"sandbox\": {\n    \"enabled\": true,\n    \"failIfUnavailable\": true,\n    \"filesystem\": {\n      \"allowWrite\": [\"/Users/me/project\"],\n      \"allowRead\": [\"/Users/me/project\", \"/usr/local/lib\"],\n      \"denyRead\": [\"/Users/me/.ssh\", \"/Users/me/.aws\"]\n    },\n    \"enableWeakerNetworkIsolation\": true\n  }\n}\n```\n\n### How It Works\n\n- Bash commands run in a sandboxed environment with restricted filesystem access\n- Network access can be isolated to prevent unintended external connections\n- Works alongside permission rules for defense in depth\n- On macOS, use `sandbox.enableWeakerNetworkIsolation` for network restrictions (full network isolation is not available on macOS)\n\n### Use Cases\n\n- Running untrusted or generated code safely\n- Preventing accidental modifications to files outside the project\n- Restricting network access during automated tasks\n\n---\n\n## Managed Settings (Enterprise)\n\nManaged Settings enable enterprise administrators to deploy Claude Code configuration across an organization using platform-native management tools.\n\n### Deployment Methods\n\n| Platform | Method | Since |\n|----------|--------|-------|\n| macOS | Managed plist files (MDM) | v2.1.51+ |\n| Windows | Windows Registry | v2.1.51+ |\n| Cross-platform | Managed configuration files | v2.1.51+ |\n| Cross-platform | Managed drop-ins (`managed-settings.d/` directory) | v2.1.83+ |\n\n### Managed Drop-ins\n\nSince v2.1.83, administrators can deploy multiple managed settings files into a `managed-settings.d/` directory. Files are merged in alphabetical order, allowing modular configuration across teams:\n\n```\n~/.claude/managed-settings.d/\n  00-org-defaults.json\n  10-team-policies.json\n  20-project-overrides.json\n```\n\n### Available Managed Settings\n\n| Setting | Description |\n|---------|-------------|\n| `disableBypassPermissionsMode` | Prevent users from enabling bypass permissions |\n| `availableModels` | Restrict which models users can select |\n| `allowedChannelPlugins` | Control which channel plugins are permitted |\n| `autoMode.environment` | Configure trusted infrastructure for auto mode |\n| Custom policies | Organization-specific permission and tool policies |\n\n### Example: macOS Plist\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"\n  \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n  <key>disableBypassPermissionsMode</key>\n  <true/>\n  <key>availableModels</key>\n  <array>\n    <string>claude-sonnet-4-6</string>\n    <string>claude-haiku-4-5</string>\n  </array>\n</dict>\n</plist>\n```\n\n---\n\n## Configuration and Settings\n\n### Configuration File Locations\n\n1. **Global config**: `~/.claude/config.json`\n2. **Project config**: `./.claude/config.json`\n3. **User config**: `~/.config/claude-code/settings.json`\n\n### Complete Configuration Example\n\n**Core advanced features configuration:**\n\n```json\n{\n  \"permissions\": {\n    \"mode\": \"default\"\n  },\n  \"hooks\": {\n    \"PreToolUse:Edit\": \"eslint --fix ${file_path}\",\n    \"PostToolUse:Write\": \"~/.claude/hooks/security-scan.sh\"\n  },\n  \"mcp\": {\n    \"enabled\": true,\n    \"servers\": {\n      \"github\": {\n        \"command\": \"npx\",\n        \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"]\n      }\n    }\n  }\n}\n```\n\n**Extended configuration example:**\n\n```json\n{\n  \"permissions\": {\n    \"mode\": \"default\",\n    \"allowedTools\": [\"Bash(git log:*)\", \"Read\"],\n    \"disallowedTools\": [\"Bash(rm -rf:*)\"]\n  },\n\n  \"hooks\": {\n    \"PreToolUse\": [{ \"matcher\": \"Edit\", \"hooks\": [\"eslint --fix ${file_path}\"] }],\n    \"PostToolUse\": [{ \"matcher\": \"Write\", \"hooks\": [\"~/.claude/hooks/security-scan.sh\"] }],\n    \"Stop\": [{ \"hooks\": [\"~/.claude/hooks/notify.sh\"] }]\n  },\n\n  \"mcp\": {\n    \"enabled\": true,\n    \"servers\": {\n      \"github\": {\n        \"command\": \"npx\",\n        \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n        \"env\": {\n          \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n        }\n      }\n    }\n  }\n}\n```\n\n### Environment Variables\n\nOverride config with environment variables:\n\n```bash\n# Model selection\nexport ANTHROPIC_MODEL=claude-opus-4-6\nexport ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-4-6\nexport ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-4-6\nexport ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-4-5\n\n# API configuration\nexport ANTHROPIC_API_KEY=sk-ant-...\n\n# Thinking configuration\nexport MAX_THINKING_TOKENS=16000\nexport CLAUDE_CODE_EFFORT_LEVEL=high\n\n# Feature toggles\nexport CLAUDE_CODE_DISABLE_AUTO_MEMORY=true\nexport CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=true\nexport CLAUDE_CODE_DISABLE_CRON=1\nexport CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=true\nexport CLAUDE_CODE_DISABLE_TERMINAL_TITLE=true\nexport CLAUDE_CODE_DISABLE_1M_CONTEXT=true\nexport CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=true\nexport CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false\nexport CLAUDE_CODE_ENABLE_TASKS=true\nexport CLAUDE_CODE_SIMPLE=true              # Set by --bare flag\n\n# MCP configuration\nexport MAX_MCP_OUTPUT_TOKENS=50000\nexport ENABLE_TOOL_SEARCH=true\n\n# Task management\nexport CLAUDE_CODE_TASK_LIST_ID=my-project-tasks\n\n# Agent teams (experimental)\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=true\n\n# Subagent and plugin configuration\nexport CLAUDE_CODE_SUBAGENT_MODEL=sonnet\nexport CLAUDE_CODE_PLUGIN_SEED_DIR=./my-plugins\nexport CLAUDE_CODE_NEW_INIT=true\n\n# Subprocess and streaming\nexport CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=\"SECRET_KEY,DB_PASSWORD\"\nexport CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=80\nexport CLAUDE_STREAM_IDLE_TIMEOUT_MS=30000\nexport ANTHROPIC_CUSTOM_MODEL_OPTION=my-custom-model\nexport SLASH_COMMAND_TOOL_CHAR_BUDGET=50000\n```\n\n### Configuration Management Commands\n\n```\nUser: /config\n[Opens interactive configuration menu]\n```\n\nThe `/config` command provides an interactive menu to toggle settings such as:\n- Extended thinking on/off\n- Verbose output\n- Permission mode\n- Model selection\n\n### Per-Project Configuration\n\nCreate `.claude/config.json` in your project:\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [{ \"matcher\": \"Bash\", \"hooks\": [\"npm test && npm run lint\"] }]\n  },\n  \"permissions\": {\n    \"mode\": \"default\"\n  },\n  \"mcp\": {\n    \"servers\": {\n      \"project-db\": {\n        \"command\": \"mcp-postgres\",\n        \"env\": {\n          \"DATABASE_URL\": \"${PROJECT_DB_URL}\"\n        }\n      }\n    }\n  }\n}\n```\n\n---\n\n## Best Practices\n\n### Planning Mode\n- ✅ Use for complex multi-step tasks\n- ✅ Review plans before approving\n- ✅ Modify plans when needed\n- ❌ Don't use for simple tasks\n\n### Extended Thinking\n- ✅ Use for architectural decisions\n- ✅ Use for complex problem-solving\n- ✅ Review the thinking process\n- ❌ Don't use for simple queries\n\n### Background Tasks\n- ✅ Use for long-running operations\n- ✅ Monitor task progress\n- ✅ Handle task failures gracefully\n- ❌ Don't start too many concurrent tasks\n\n### Permissions\n- ✅ Use `plan` for code review (read-only)\n- ✅ Use `default` for interactive development\n- ✅ Use `acceptEdits` for automation workflows\n- ✅ Use `auto` for autonomous work with safety guardrails\n- ❌ Don't use `bypassPermissions` unless absolutely necessary\n\n### Sessions\n- ✅ Use separate sessions for different tasks\n- ✅ Save important session states\n- ✅ Clean up old sessions\n- ❌ Don't mix unrelated work in one session\n\n---\n\n## Additional Resources\n\nFor more information about Claude Code and related features:\n\n- [Official Interactive Mode Documentation](https://code.claude.com/docs/en/interactive-mode)\n- [Official Headless Mode Documentation](https://code.claude.com/docs/en/headless)\n- [CLI Reference](https://code.claude.com/docs/en/cli-reference)\n- [Checkpoints Guide](../08-checkpoints/) - Session management and rewinding\n- [Slash Commands](../01-slash-commands/) - Command reference\n- [Memory Guide](../02-memory/) - Persistent context\n- [Skills Guide](../03-skills/) - Autonomous capabilities\n- [Subagents Guide](../04-subagents/) - Delegated task execution\n- [MCP Guide](../05-mcp/) - External data access\n- [Hooks Guide](../06-hooks/) - Event-driven automation\n- [Plugins Guide](../07-plugins/) - Bundled extensions\n- [Official Scheduled Tasks Documentation](https://code.claude.com/docs/en/scheduled-tasks)\n- [Official Chrome Integration Documentation](https://code.claude.com/docs/en/chrome)\n- [Official Remote Control Documentation](https://code.claude.com/docs/en/remote-control)\n- [Official Keybindings Documentation](https://code.claude.com/docs/en/keybindings)\n- [Official Desktop App Documentation](https://code.claude.com/docs/en/desktop)\n"
  },
  {
    "path": "09-advanced-features/config-examples.json",
    "content": "{\n  \"description\": \"Example Claude Code configurations for different use cases\",\n\n  \"examples\": {\n    \"development\": {\n      \"name\": \"Development Environment\",\n      \"description\": \"Configuration for active development work\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0.7\n        },\n        \"planning\": {\n          \"autoEnter\": true,\n          \"complexityThreshold\": 3,\n          \"requireApproval\": true\n        },\n        \"permissions\": {\n          \"mode\": \"unrestricted\"\n        },\n        \"backgroundTasks\": {\n          \"enabled\": true,\n          \"maxConcurrentTasks\": 3\n        },\n        \"hooks\": {\n          \"PreToolUse:Write\": \"prettier --write ${file_path}\",\n          \"PostToolUse:Write\": \"eslint ${file_path}\",\n          \"PreCommit\": \"npm test\"\n        }\n      }\n    },\n\n    \"code_review\": {\n      \"name\": \"Code Review Mode\",\n      \"description\": \"Configuration for reviewing code without modifications\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0.3\n        },\n        \"permissions\": {\n          \"mode\": \"plan\"\n        },\n        \"extendedThinking\": {\n          \"enabled\": true,\n          \"showThinkingProcess\": true\n        },\n        \"planning\": {\n          \"autoEnter\": false\n        }\n      }\n    },\n\n    \"learning\": {\n      \"name\": \"Learning Mode\",\n      \"description\": \"Configuration for learning and experimentation\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0.5\n        },\n        \"permissions\": {\n          \"mode\": \"confirm\"\n        },\n        \"extendedThinking\": {\n          \"enabled\": true,\n          \"showThinkingProcess\": true\n        },\n        \"planning\": {\n          \"autoEnter\": true,\n          \"requireApproval\": true,\n          \"showTimeEstimates\": true\n        },\n        \"checkpoints\": {\n          \"autoCheckpoint\": true\n        }\n      }\n    },\n\n    \"production\": {\n      \"name\": \"Production Deployment\",\n      \"description\": \"Configuration for production operations with safety checks\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-opus-4\",\n          \"temperature\": 0.1\n        },\n        \"permissions\": {\n          \"mode\": \"confirm\",\n          \"requireConfirmationFor\": [\"Bash\", \"Git\", \"Write\", \"Edit\"]\n        },\n        \"hooks\": {\n          \"PreCommit\": \"npm test && npm run lint && npm run build\",\n          \"PrePush\": \"npm run test:e2e\",\n          \"PostPush\": \"~/.claude/hooks/notify-team.sh\"\n        },\n        \"checkpoints\": {\n          \"autoCheckpoint\": true\n        },\n        \"planning\": {\n          \"autoEnter\": true,\n          \"requireApproval\": true\n        }\n      }\n    },\n\n    \"ci_cd\": {\n      \"name\": \"CI/CD Pipeline\",\n      \"description\": \"Configuration for automated CI/CD operations\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0\n        },\n        \"permissions\": {\n          \"mode\": \"unrestricted\"\n        },\n        \"headless\": {\n          \"exitOnError\": true,\n          \"verbose\": true,\n          \"timeout\": 3600\n        },\n        \"logging\": {\n          \"level\": \"debug\",\n          \"file\": \"./ci-claude.log\"\n        },\n        \"planning\": {\n          \"autoEnter\": false,\n          \"requireApproval\": false\n        }\n      }\n    },\n\n    \"security_audit\": {\n      \"name\": \"Security Audit\",\n      \"description\": \"Configuration for security-focused code analysis\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-opus-4\",\n          \"temperature\": 0.2\n        },\n        \"permissions\": {\n          \"mode\": \"plan\"\n        },\n        \"extendedThinking\": {\n          \"enabled\": true,\n          \"showThinkingProcess\": true,\n          \"minThinkingTime\": 10\n        },\n        \"hooks\": {\n          \"PostToolUse:Read\": \"~/.claude/hooks/security-scan.sh ${file_path}\"\n        }\n      }\n    },\n\n    \"performance_optimization\": {\n      \"name\": \"Performance Optimization\",\n      \"description\": \"Configuration for performance analysis and optimization\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0.4\n        },\n        \"planning\": {\n          \"autoEnter\": true,\n          \"requireApproval\": true\n        },\n        \"backgroundTasks\": {\n          \"enabled\": true,\n          \"maxConcurrentTasks\": 5\n        },\n        \"checkpoints\": {\n          \"autoCheckpoint\": true\n        }\n      }\n    },\n\n    \"pair_programming\": {\n      \"name\": \"Pair Programming\",\n      \"description\": \"Configuration for collaborative development\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0.6\n        },\n        \"permissions\": {\n          \"mode\": \"confirm\"\n        },\n        \"planning\": {\n          \"autoEnter\": true,\n          \"requireApproval\": true,\n          \"showTimeEstimates\": true\n        },\n        \"extendedThinking\": {\n          \"enabled\": true,\n          \"showThinkingProcess\": true\n        },\n        \"ui\": {\n          \"compactMode\": false,\n          \"showProgress\": true\n        }\n      }\n    },\n\n    \"refactoring\": {\n      \"name\": \"Large Refactoring\",\n      \"description\": \"Configuration for major refactoring work\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-opus-4\",\n          \"temperature\": 0.3\n        },\n        \"planning\": {\n          \"autoEnter\": true,\n          \"requireApproval\": true,\n          \"showTimeEstimates\": true\n        },\n        \"checkpoints\": {\n          \"autoCheckpoint\": true\n        },\n        \"hooks\": {\n          \"PreToolUse:Edit\": \"~/.claude/hooks/backup-file.sh ${file_path}\",\n          \"PostToolUse:Edit\": \"npm test -- --findRelatedTests ${file_path}\"\n        },\n        \"permissions\": {\n          \"mode\": \"confirm\"\n        }\n      }\n    },\n\n    \"autonomous\": {\n      \"name\": \"Autonomous Development\",\n      \"description\": \"Configuration for autonomous work with auto mode safety checks\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-6\",\n          \"temperature\": 0.5\n        },\n        \"permissions\": {\n          \"mode\": \"auto\"\n        },\n        \"sandbox\": {\n          \"enabled\": true,\n          \"failIfUnavailable\": false\n        },\n        \"backgroundTasks\": {\n          \"enabled\": true,\n          \"maxConcurrentTasks\": 3\n        }\n      }\n    },\n\n    \"documentation\": {\n      \"name\": \"Documentation Writing\",\n      \"description\": \"Configuration for writing documentation\",\n      \"config\": {\n        \"general\": {\n          \"model\": \"claude-sonnet-4-5\",\n          \"temperature\": 0.7\n        },\n        \"permissions\": {\n          \"mode\": \"unrestricted\"\n        },\n        \"hooks\": {\n          \"PostToolUse:Write\": \"markdownlint ${file_path}\"\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "09-advanced-features/planning-mode-examples.md",
    "content": "# Planning Mode Examples\n\nReal-world examples demonstrating effective use of planning mode in Claude Code.\n\n## Example 1: Building a REST API\n\n### Without Planning Mode\n\n```\nUser: Build a REST API for a blog\n\nClaude: I'll create the API...\n[Starts coding immediately, may miss requirements]\n```\n\n### With Planning Mode\n\n```\nUser: /plan Build a REST API for a blog\n\nClaude: Let me create a comprehensive plan for the blog API.\n\n## Blog REST API Implementation Plan\n\n### Phase 1: Project Setup (15 min)\n1. Initialize Node.js project with Express\n2. Set up TypeScript configuration\n3. Install dependencies (express, pg, jwt, joi)\n4. Configure environment variables\n5. Set up project structure\n\n### Phase 2: Database Layer (30 min)\n6. Design database schema\n   - users table (id, email, password_hash, created_at)\n   - posts table (id, user_id, title, content, published, created_at, updated_at)\n   - comments table (id, post_id, user_id, content, created_at)\n7. Create migration files\n8. Set up database connection pool\n9. Implement database models\n\n### Phase 3: Authentication (45 min)\n10. Implement user registration endpoint\n11. Implement login endpoint with JWT\n12. Create authentication middleware\n13. Add password hashing with bcrypt\n14. Implement token refresh logic\n\n### Phase 4: Posts API (40 min)\n15. GET /api/posts - List all published posts (with pagination)\n16. GET /api/posts/:id - Get single post\n17. POST /api/posts - Create new post (auth required)\n18. PUT /api/posts/:id - Update post (auth required, ownership check)\n19. DELETE /api/posts/:id - Delete post (auth required, ownership check)\n20. GET /api/users/:id/posts - Get user's posts\n\n### Phase 5: Comments API (30 min)\n21. GET /api/posts/:id/comments - Get post comments\n22. POST /api/posts/:id/comments - Add comment (auth required)\n23. DELETE /api/comments/:id - Delete comment (auth required, ownership check)\n\n### Phase 6: Validation & Error Handling (30 min)\n24. Add request validation with Joi\n25. Implement global error handler\n26. Add input sanitization\n27. Implement rate limiting\n\n### Phase 7: Testing (60 min)\n28. Write unit tests for models\n29. Write integration tests for auth endpoints\n30. Write integration tests for posts endpoints\n31. Write integration tests for comments endpoints\n32. Achieve 80%+ code coverage\n\n### Phase 8: Documentation & Deployment (30 min)\n33. Generate API documentation with Swagger\n34. Create README with setup instructions\n35. Add Docker configuration\n36. Set up CI/CD pipeline\n\n**Estimated Time**: 4.5 hours\n**Files to Create**: ~25\n**Key Technologies**: Express, PostgreSQL, JWT, TypeScript\n\n**API Endpoints Summary**:\n- Authentication: 2 endpoints\n- Posts: 6 endpoints\n- Comments: 3 endpoints\n- Total: 11 endpoints\n\nReady to proceed? (yes/no/modify)\n\nUser: yes\n\nClaude: Starting Phase 1: Project Setup...\n[Implements each phase systematically]\n```\n\n## Example 2: Database Migration\n\n### With Planning Mode\n\n```\nUser: /plan Migrate from MongoDB to PostgreSQL\n\nClaude: This is a complex migration. Let me create a detailed plan.\n\n## MongoDB to PostgreSQL Migration Plan\n\n### Phase 1: Analysis & Preparation (Day 1)\n1. Analyze current MongoDB schema\n2. Identify data relationships and constraints\n3. Document current data volume and growth rate\n4. Design equivalent PostgreSQL schema\n5. Plan data type mappings\n6. Identify potential migration challenges\n\n### Phase 2: PostgreSQL Setup (Day 1)\n7. Set up PostgreSQL database\n8. Create schema with tables, indexes, constraints\n9. Set up connection pooling\n10. Configure backup strategy\n\n### Phase 3: Dual-Write Implementation (Day 2-3)\n11. Create database abstraction layer\n12. Implement dual-write to both databases\n13. Add data consistency checks\n14. Deploy dual-write to staging\n15. Monitor for issues\n\n### Phase 4: Data Migration (Day 4)\n16. Create data export scripts for MongoDB\n17. Create data import scripts for PostgreSQL\n18. Implement data transformation logic\n19. Run initial migration on copy of production data\n20. Validate migrated data integrity\n\n### Phase 5: Gradual Cutover (Day 5-7)\n21. Enable dual-write in production\n22. Migrate historical data in batches\n23. Continuously validate data consistency\n24. Monitor both databases\n25. Fix any data synchronization issues\n\n### Phase 6: PostgreSQL Primary (Day 8)\n26. Switch read operations to PostgreSQL\n27. Monitor query performance\n28. Optimize slow queries\n29. Continue dual-write for safety\n\n### Phase 7: MongoDB Retirement (Day 9-10)\n30. Stop writing to MongoDB\n31. Keep MongoDB as backup for 2 weeks\n32. Remove MongoDB dependencies from code\n33. Archive MongoDB data\n34. Decommission MongoDB instance\n\n**Estimated Time**: 10 days\n**Risk Level**: High\n**Rollback Strategy**: Keep MongoDB running with dual-write\n**Success Criteria**:\n- Zero data loss\n- <5% performance regression\n- All tests passing\n\n**Key Risks**:\n1. Data inconsistency during migration\n2. Query performance degradation\n3. Application downtime\n4. Data loss\n\n**Mitigation**:\n- Dual-write pattern for safety\n- Gradual cutover\n- Continuous monitoring\n- Quick rollback capability\n\nProceed with this plan? (yes/no/modify)\n\nUser: Modify - let's add a rollback plan for each phase\n\nClaude: Updated plan with rollback procedures for each phase...\n```\n\n## Example 3: Frontend Refactoring\n\n```\nUser: /plan Refactor our React app from class components to hooks\n\nClaude: I'll create a systematic refactoring plan.\n\n## React Class to Hooks Migration Plan\n\n### Phase 1: Preparation & Analysis (2 hours)\n1. Audit all class components (find all .jsx/.tsx files)\n2. Categorize by complexity:\n   - Simple (state only): ~15 components\n   - Medium (lifecycle methods): ~23 components\n   - Complex (multiple lifecycle, refs): ~8 components\n3. Identify third-party libraries that need updates\n4. Create component dependency graph\n5. Plan migration order (leaf nodes first)\n\n### Phase 2: Setup & Tooling (1 hour)\n6. Update React to v18+\n7. Set up ESLint rules for hooks\n8. Create conversion templates\n9. Set up automated tests\n10. Create checkpoint before starting\n\n### Phase 3: Migrate Simple Components (4 hours)\n11. Convert simple stateful components (15 components)\n12. Replace this.state with useState\n13. Replace this.setState with state setters\n14. Test each component after conversion\n15. Update tests\n\n### Phase 4: Migrate Medium Components (8 hours)\n16. Convert components with lifecycle methods (23 components)\n17. Replace componentDidMount with useEffect\n18. Replace componentDidUpdate with useEffect\n19. Replace componentWillUnmount with useEffect cleanup\n20. Test thoroughly\n\n### Phase 5: Migrate Complex Components (12 hours)\n21. Convert complex components (8 components)\n22. Replace refs with useRef\n23. Extract custom hooks for shared logic\n24. Handle edge cases (multiple useEffect)\n25. Extensive testing\n\n### Phase 6: Shared Logic Extraction (6 hours)\n26. Identify duplicated logic across components\n27. Create custom hooks:\n    - useAuth\n    - useFetch\n    - useLocalStorage\n    - useDebounce\n28. Refactor components to use custom hooks\n29. Test custom hooks independently\n\n### Phase 7: Performance Optimization (4 hours)\n30. Add React.memo where needed\n31. Optimize with useCallback\n32. Optimize with useMemo\n33. Profile and fix performance regressions\n\n### Phase 8: Cleanup & Documentation (2 hours)\n34. Remove unused class component utilities\n35. Update documentation\n36. Update coding guidelines\n37. Create migration guide for team\n\n**Estimated Time**: 5 days (39 hours)\n**Files to Modify**: 46 components\n**Risk Level**: Medium\n\n**Migration Order**:\n1. Leaf components (no dependencies)\n2. Mid-level components\n3. Top-level container components\n4. App.jsx (last)\n\n**Testing Strategy**:\n- Unit tests for each component\n- Integration tests for user flows\n- Visual regression tests\n- Performance benchmarks\n\n**Success Metrics**:\n- All tests passing\n- No visual regressions\n- Performance maintained or improved\n- Bundle size not significantly increased\n\nProceed? (yes/no/modify)\n```\n\n## Example 4: Security Implementation\n\n```\nUser: /plan Implement comprehensive security for our web app\n\nClaude: Let me create a thorough security implementation plan.\n\n## Web Application Security Implementation Plan\n\n### Phase 1: Security Audit (Day 1)\n1. Run automated security scanners (npm audit, Snyk)\n2. Review dependencies for vulnerabilities\n3. Check OWASP Top 10 compliance\n4. Audit authentication flows\n5. Review data handling practices\n6. Document current security gaps\n\n### Phase 2: Authentication Hardening (Day 2-3)\n7. Implement strong password requirements\n8. Add password strength meter\n9. Implement rate limiting on login\n10. Add account lockout after failed attempts\n11. Implement 2FA (TOTP)\n12. Add session management improvements\n13. Implement secure password reset flow\n\n### Phase 3: Authorization & Access Control (Day 3-4)\n14. Implement RBAC (Role-Based Access Control)\n15. Add permission checks on all endpoints\n16. Implement principle of least privilege\n17. Add audit logging for sensitive operations\n18. Implement resource-level permissions\n\n### Phase 4: Data Protection (Day 4-5)\n19. Implement encryption at rest (sensitive fields)\n20. Ensure TLS/SSL for all communications\n21. Implement secure session storage\n22. Add PII data masking in logs\n23. Implement data retention policies\n24. Add secure file upload handling\n\n### Phase 5: Input Validation & Sanitization (Day 5-6)\n25. Implement input validation on all endpoints\n26. Add XSS protection (Content Security Policy)\n27. Implement SQL injection prevention (parameterized queries)\n28. Add CSRF protection\n29. Implement request size limits\n30. Add file upload type validation\n\n### Phase 6: Security Headers & Configuration (Day 6)\n31. Add security headers:\n    - Strict-Transport-Security\n    - X-Content-Type-Options\n    - X-Frame-Options\n    - X-XSS-Protection\n    - Content-Security-Policy\n32. Configure CORS properly\n33. Disable unnecessary HTTP methods\n34. Remove server version headers\n\n### Phase 7: Monitoring & Logging (Day 7)\n35. Implement security event logging\n36. Add anomaly detection\n37. Set up intrusion detection\n38. Implement real-time alerting\n39. Create security dashboard\n\n### Phase 8: Testing & Documentation (Day 8-9)\n40. Perform penetration testing\n41. Run security scanners\n42. Test all security features\n43. Create security documentation\n44. Train team on security practices\n45. Create incident response plan\n\n### Phase 9: Compliance & Policies (Day 10)\n46. GDPR compliance check\n47. Create privacy policy\n48. Implement data subject rights\n49. Add cookie consent\n50. Create security policies documentation\n\n**Estimated Time**: 10 days\n**Risk Level**: Critical\n**Priority**: High\n\n**Security Improvements Summary**:\n- Authentication: 7 enhancements\n- Authorization: 5 enhancements\n- Data Protection: 6 enhancements\n- Input Validation: 6 enhancements\n- Infrastructure: 9 enhancements\n- Monitoring: 5 enhancements\n\n**Compliance**: OWASP Top 10, GDPR\n\n**Success Criteria**:\n- Zero critical vulnerabilities\n- All OWASP Top 10 mitigated\n- Security score >90/100\n- All pen test issues resolved\n\nProceed? (yes/no/modify)\n```\n\n## Example 5: Performance Optimization\n\n```\nUser: /plan Optimize our slow e-commerce website\n\nClaude: Let me create a comprehensive performance optimization plan.\n\n## E-commerce Performance Optimization Plan\n\n### Phase 1: Performance Audit (4 hours)\n1. Run Lighthouse audit\n2. Analyze Chrome DevTools performance profile\n3. Measure Core Web Vitals:\n   - LCP (Largest Contentful Paint)\n   - FID (First Input Delay)\n   - CLS (Cumulative Layout Shift)\n4. Identify performance bottlenecks\n5. Create baseline performance metrics\n\n**Current Metrics**:\n- LCP: 4.2s (target: <2.5s)\n- FID: 280ms (target: <100ms)\n- CLS: 0.25 (target: <0.1)\n- Page Load: 8.3s (target: <3s)\n\n### Phase 2: Image Optimization (6 hours)\n6. Convert images to WebP format\n7. Implement responsive images\n8. Add lazy loading for images\n9. Optimize image sizes (compression)\n10. Implement CDN for images\n11. Add image placeholders\n\n**Expected Impact**: -40% load time\n\n### Phase 3: Code Splitting & Lazy Loading (8 hours)\n12. Implement route-based code splitting\n13. Lazy load non-critical components\n14. Split vendor bundles\n15. Optimize chunk sizes\n16. Implement dynamic imports\n17. Add preloading for critical resources\n\n**Expected Impact**: -30% initial bundle size\n\n### Phase 4: Caching Strategy (6 hours)\n18. Implement browser caching (Cache-Control)\n19. Add service worker for offline support\n20. Implement API response caching\n21. Add Redis cache for database queries\n22. Implement stale-while-revalidate\n23. Configure CDN caching\n\n**Expected Impact**: -50% API response time\n\n### Phase 5: Database Optimization (8 hours)\n24. Add database indexes\n25. Optimize slow queries (>100ms)\n26. Implement query result caching\n27. Add connection pooling\n28. Denormalize where appropriate\n29. Implement database read replicas\n\n**Expected Impact**: -60% database query time\n\n### Phase 6: Frontend Optimization (10 hours)\n30. Minimize and compress JavaScript\n31. Minimize and compress CSS\n32. Remove unused CSS (PurgeCSS)\n33. Implement critical CSS\n34. Defer non-critical JavaScript\n35. Reduce DOM size\n36. Optimize React rendering (memo, useMemo)\n37. Implement virtual scrolling for long lists\n\n**Expected Impact**: -35% JavaScript execution time\n\n### Phase 7: Network Optimization (4 hours)\n38. Enable HTTP/2\n39. Implement resource hints (preconnect, prefetch)\n40. Reduce number of HTTP requests\n41. Enable Brotli compression\n42. Optimize third-party scripts\n\n**Expected Impact**: -25% network time\n\n### Phase 8: Monitoring & Testing (4 hours)\n43. Set up performance monitoring (Datadog/New Relic)\n44. Add Real User Monitoring (RUM)\n45. Create performance budgets\n46. Set up automated Lighthouse CI\n47. Test on real devices\n\n**Estimated Time**: 50 hours (2 weeks)\n\n**Target Metrics** (90th percentile):\n- LCP: <2.0s (from 4.2s) ✅\n- FID: <50ms (from 280ms) ✅\n- CLS: <0.05 (from 0.25) ✅\n- Page Load: <2.5s (from 8.3s) ✅\n\n**Expected Revenue Impact**:\n- 100ms faster = 1% conversion increase\n- Target: 5.8s improvement = ~58% conversion increase\n- Estimated additional revenue: Significant\n\n**Priority Order**:\n1. Image optimization (quick wins)\n2. Code splitting (high impact)\n3. Caching (high impact)\n4. Database optimization (critical)\n5. Frontend optimization (polish)\n\nProceed with this plan? (yes/no/modify)\n```\n\n## Key Takeaways\n\n### Benefits of Planning Mode\n\n1. **Clarity**: Clear roadmap before starting\n2. **Estimation**: Time and effort estimates\n3. **Risk Assessment**: Identify potential issues early\n4. **Prioritization**: Logical order of tasks\n5. **Approval**: Review and approve before execution\n6. **Modification**: Adjust plan based on feedback\n\n### When to Use Planning Mode\n\n✅ **Always use for**:\n- Multi-day projects\n- Team collaborations\n- Critical system changes\n- Learning new concepts\n- Complex refactoring\n\n❌ **Don't use for**:\n- Bug fixes\n- Small tweaks\n- Simple queries\n- Quick experiments\n\n### Best Practices\n\n1. **Review plans carefully** before approving\n2. **Modify plans** when you spot issues\n3. **Break down** complex tasks\n4. **Estimate realistic** timeframes\n5. **Include rollback** strategies\n6. **Add success** criteria\n7. **Plan for testing** at each phase\n"
  },
  {
    "path": "10-cli/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# CLI Reference\n\n## Overview\n\nThe Claude Code CLI (Command Line Interface) is the primary way to interact with Claude Code. It provides powerful options for running queries, managing sessions, configuring models, and integrating Claude into your development workflows.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[\"User Terminal\"] -->|\"claude [options] [query]\"| B[\"Claude Code CLI\"]\n    B -->|Interactive| C[\"REPL Mode\"]\n    B -->|\"--print\"| D[\"Print Mode (SDK)\"]\n    B -->|\"--resume\"| E[\"Session Resume\"]\n    C -->|Conversation| F[\"Claude API\"]\n    D -->|Single Query| F\n    E -->|Load Context| F\n    F -->|Response| G[\"Output\"]\n    G -->|text/json/stream-json| H[\"Terminal/Pipe\"]\n```\n\n## CLI Commands\n\n| Command | Description | Example |\n|---------|-------------|---------|\n| `claude` | Start interactive REPL | `claude` |\n| `claude \"query\"` | Start REPL with initial prompt | `claude \"explain this project\"` |\n| `claude -p \"query\"` | Print mode - query then exit | `claude -p \"explain this function\"` |\n| `cat file \\| claude -p \"query\"` | Process piped content | `cat logs.txt \\| claude -p \"explain\"` |\n| `claude -c` | Continue most recent conversation | `claude -c` |\n| `claude -c -p \"query\"` | Continue in print mode | `claude -c -p \"check for type errors\"` |\n| `claude -r \"<session>\" \"query\"` | Resume session by ID or name | `claude -r \"auth-refactor\" \"finish this PR\"` |\n| `claude update` | Update to latest version | `claude update` |\n| `claude mcp` | Configure MCP servers | See [MCP documentation](../05-mcp/) |\n| `claude mcp serve` | Run Claude Code as an MCP server | `claude mcp serve` |\n| `claude agents` | List all configured subagents | `claude agents` |\n| `claude auto-mode defaults` | Print auto mode default rules as JSON | `claude auto-mode defaults` |\n| `claude remote-control` | Start Remote Control server | `claude remote-control` |\n| `claude plugin` | Manage plugins (install, enable, disable) | `claude plugin install my-plugin` |\n| `claude auth login` | Log in (supports `--email`, `--sso`) | `claude auth login --email user@example.com` |\n| `claude auth logout` | Log out of current account | `claude auth logout` |\n| `claude auth status` | Check auth status (exit 0 if logged in, 1 if not) | `claude auth status` |\n\n## Core Flags\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `-p, --print` | Print response without interactive mode | `claude -p \"query\"` |\n| `-c, --continue` | Load most recent conversation | `claude --continue` |\n| `-r, --resume` | Resume specific session by ID or name | `claude --resume auth-refactor` |\n| `-v, --version` | Output version number | `claude -v` |\n| `-w, --worktree` | Start in isolated git worktree | `claude -w` |\n| `-n, --name` | Session display name | `claude -n \"auth-refactor\"` |\n| `--from-pr <number>` | Resume sessions linked to GitHub PR | `claude --from-pr 42` |\n| `--remote \"task\"` | Create web session on claude.ai | `claude --remote \"implement API\"` |\n| `--remote-control, --rc` | Interactive session with Remote Control | `claude --rc` |\n| `--teleport` | Resume web session locally | `claude --teleport` |\n| `--teammate-mode` | Agent team display mode | `claude --teammate-mode tmux` |\n| `--bare` | Minimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md) | `claude --bare` |\n| `--enable-auto-mode` | Unlock auto permission mode | `claude --enable-auto-mode` |\n| `--channels` | Subscribe to MCP channel plugins | `claude --channels discord,telegram` |\n| `--chrome` / `--no-chrome` | Enable/disable Chrome browser integration | `claude --chrome` |\n| `--effort` | Set thinking effort level | `claude --effort high` |\n| `--init` / `--init-only` | Run initialization hooks | `claude --init` |\n| `--maintenance` | Run maintenance hooks and exit | `claude --maintenance` |\n| `--disable-slash-commands` | Disable all skills and slash commands | `claude --disable-slash-commands` |\n| `--no-session-persistence` | Disable session saving (print mode) | `claude -p --no-session-persistence \"query\"` |\n\n### Interactive vs Print Mode\n\n```mermaid\ngraph LR\n    A[\"claude\"] -->|Default| B[\"Interactive REPL\"]\n    A -->|\"-p flag\"| C[\"Print Mode\"]\n    B -->|Features| D[\"Multi-turn conversation<br>Tab completion<br>History<br>Slash commands\"]\n    C -->|Features| E[\"Single query<br>Scriptable<br>Pipeable<br>JSON output\"]\n```\n\n**Interactive Mode** (default):\n```bash\n# Start interactive session\nclaude\n\n# Start with initial prompt\nclaude \"explain the authentication flow\"\n```\n\n**Print Mode** (non-interactive):\n```bash\n# Single query, then exit\nclaude -p \"what does this function do?\"\n\n# Process file content\ncat error.log | claude -p \"explain this error\"\n\n# Chain with other tools\nclaude -p \"list todos\" | grep \"URGENT\"\n```\n\n## Model & Configuration\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--model` | Set model (sonnet, opus, haiku, or full name) | `claude --model opus` |\n| `--fallback-model` | Automatic model fallback when overloaded | `claude -p --fallback-model sonnet \"query\"` |\n| `--agent` | Specify agent for session | `claude --agent my-custom-agent` |\n| `--agents` | Define custom subagents via JSON | See [Agents Configuration](#agents-configuration) |\n| `--effort` | Set effort level (low, medium, high, max) | `claude --effort high` |\n\n### Model Selection Examples\n\n```bash\n# Use Opus 4.6 for complex tasks\nclaude --model opus \"design a caching strategy\"\n\n# Use Haiku 4.5 for quick tasks\nclaude --model haiku -p \"format this JSON\"\n\n# Full model name\nclaude --model claude-sonnet-4-6-20250929 \"review this code\"\n\n# With fallback for reliability\nclaude -p --model opus --fallback-model sonnet \"analyze architecture\"\n\n# Use opusplan (Opus plans, Sonnet executes)\nclaude --model opusplan \"design and implement the caching layer\"\n```\n\n## System Prompt Customization\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--system-prompt` | Replace entire default prompt | `claude --system-prompt \"You are a Python expert\"` |\n| `--system-prompt-file` | Load prompt from file (print mode) | `claude -p --system-prompt-file ./prompt.txt \"query\"` |\n| `--append-system-prompt` | Append to default prompt | `claude --append-system-prompt \"Always use TypeScript\"` |\n\n### System Prompt Examples\n\n```bash\n# Complete custom persona\nclaude --system-prompt \"You are a senior security engineer. Focus on vulnerabilities.\"\n\n# Append specific instructions\nclaude --append-system-prompt \"Always include unit tests with code examples\"\n\n# Load complex prompt from file\nclaude -p --system-prompt-file ./prompts/code-reviewer.txt \"review main.py\"\n```\n\n### System Prompt Flags Comparison\n\n| Flag | Behavior | Interactive | Print |\n|------|----------|-------------|-------|\n| `--system-prompt` | Replaces entire default system prompt | ✅ | ✅ |\n| `--system-prompt-file` | Replaces with prompt from file | ❌ | ✅ |\n| `--append-system-prompt` | Appends to default system prompt | ✅ | ✅ |\n\n**Use `--system-prompt-file` only in print mode. For interactive mode, use `--system-prompt` or `--append-system-prompt`.**\n\n## Tool & Permission Management\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--tools` | Restrict available built-in tools | `claude -p --tools \"Bash,Edit,Read\" \"query\"` |\n| `--allowedTools` | Tools that execute without prompting | `\"Bash(git log:*)\" \"Read\"` |\n| `--disallowedTools` | Tools removed from context | `\"Bash(rm:*)\" \"Edit\"` |\n| `--dangerously-skip-permissions` | Skip all permission prompts | `claude --dangerously-skip-permissions` |\n| `--permission-mode` | Begin in specified permission mode | `claude --permission-mode auto` |\n| `--permission-prompt-tool` | MCP tool for permission handling | `claude -p --permission-prompt-tool mcp_auth \"query\"` |\n| `--enable-auto-mode` | Unlock auto permission mode | `claude --enable-auto-mode` |\n\n### Permission Examples\n\n```bash\n# Read-only mode for code review\nclaude --permission-mode plan \"review this codebase\"\n\n# Restrict to safe tools only\nclaude --tools \"Read,Grep,Glob\" -p \"find all TODO comments\"\n\n# Allow specific git commands without prompts\nclaude --allowedTools \"Bash(git status:*)\" \"Bash(git log:*)\"\n\n# Block dangerous operations\nclaude --disallowedTools \"Bash(rm -rf:*)\" \"Bash(git push --force:*)\"\n```\n\n## Output & Format\n\n| Flag | Description | Options | Example |\n|------|-------------|---------|---------|\n| `--output-format` | Specify output format (print mode) | `text`, `json`, `stream-json` | `claude -p --output-format json \"query\"` |\n| `--input-format` | Specify input format (print mode) | `text`, `stream-json` | `claude -p --input-format stream-json` |\n| `--verbose` | Enable verbose logging | | `claude --verbose` |\n| `--include-partial-messages` | Include streaming events | Requires `stream-json` | `claude -p --output-format stream-json --include-partial-messages \"query\"` |\n| `--json-schema` | Get validated JSON matching schema | | `claude -p --json-schema '{\"type\":\"object\"}' \"query\"` |\n| `--max-budget-usd` | Maximum spend for print mode | | `claude -p --max-budget-usd 5.00 \"query\"` |\n\n### Output Format Examples\n\n```bash\n# Plain text (default)\nclaude -p \"explain this code\"\n\n# JSON for programmatic use\nclaude -p --output-format json \"list all functions in main.py\"\n\n# Streaming JSON for real-time processing\nclaude -p --output-format stream-json \"generate a long report\"\n\n# Structured output with schema validation\nclaude -p --json-schema '{\"type\":\"object\",\"properties\":{\"bugs\":{\"type\":\"array\"}}}' \\\n  \"find bugs in this code and return as JSON\"\n```\n\n## Workspace & Directory\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--add-dir` | Add additional working directories | `claude --add-dir ../apps ../lib` |\n| `--setting-sources` | Comma-separated setting sources | `claude --setting-sources user,project` |\n| `--settings` | Load settings from file or JSON | `claude --settings ./settings.json` |\n| `--plugin-dir` | Load plugins from directory (repeatable) | `claude --plugin-dir ./my-plugin` |\n\n### Multi-Directory Example\n\n```bash\n# Work across multiple project directories\nclaude --add-dir ../frontend ../backend ../shared \"find all API endpoints\"\n\n# Load custom settings\nclaude --settings '{\"model\":\"opus\",\"verbose\":true}' \"complex task\"\n```\n\n## MCP Configuration\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--mcp-config` | Load MCP servers from JSON | `claude --mcp-config ./mcp.json` |\n| `--strict-mcp-config` | Only use specified MCP config | `claude --strict-mcp-config --mcp-config ./mcp.json` |\n| `--channels` | Subscribe to MCP channel plugins | `claude --channels discord,telegram` |\n\n### MCP Examples\n\n```bash\n# Load GitHub MCP server\nclaude --mcp-config ./github-mcp.json \"list open PRs\"\n\n# Strict mode - only specified servers\nclaude --strict-mcp-config --mcp-config ./production-mcp.json \"deploy to staging\"\n```\n\n## Session Management\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--session-id` | Use specific session ID (UUID) | `claude --session-id \"550e8400-...\"` |\n| `--fork-session` | Create new session when resuming | `claude --resume abc123 --fork-session` |\n\n### Session Examples\n\n```bash\n# Continue last conversation\nclaude -c\n\n# Resume named session\nclaude -r \"feature-auth\" \"continue implementing login\"\n\n# Fork session for experimentation\nclaude --resume feature-auth --fork-session \"try alternative approach\"\n\n# Use specific session ID\nclaude --session-id \"550e8400-e29b-41d4-a716-446655440000\" \"continue\"\n```\n\n### Session Fork\n\nCreate a branch from an existing session for experimentation:\n\n```bash\n# Fork a session to try a different approach\nclaude --resume abc123 --fork-session \"try alternative implementation\"\n\n# Fork with a custom message\nclaude -r \"feature-auth\" --fork-session \"test with different architecture\"\n```\n\n**Use Cases:**\n- Try alternative implementations without losing the original session\n- Experiment with different approaches in parallel\n- Create branches from successful work for variations\n- Test breaking changes without affecting the main session\n\nThe original session remains unchanged, and the fork becomes a new independent session.\n\n## Advanced Features\n\n| Flag | Description | Example |\n|------|-------------|---------|\n| `--chrome` | Enable Chrome browser integration | `claude --chrome` |\n| `--no-chrome` | Disable Chrome browser integration | `claude --no-chrome` |\n| `--ide` | Auto-connect to IDE if available | `claude --ide` |\n| `--max-turns` | Limit agentic turns (non-interactive) | `claude -p --max-turns 3 \"query\"` |\n| `--debug` | Enable debug mode with filtering | `claude --debug \"api,mcp\"` |\n| `--enable-lsp-logging` | Enable verbose LSP logging | `claude --enable-lsp-logging` |\n| `--betas` | Beta headers for API requests | `claude --betas interleaved-thinking` |\n| `--plugin-dir` | Load plugins from directory (repeatable) | `claude --plugin-dir ./my-plugin` |\n| `--enable-auto-mode` | Unlock auto permission mode | `claude --enable-auto-mode` |\n| `--effort` | Set thinking effort level | `claude --effort high` |\n| `--bare` | Minimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md) | `claude --bare` |\n| `--channels` | Subscribe to MCP channel plugins | `claude --channels discord` |\n| `--fork-session` | Create new session ID when resuming | `claude --resume abc --fork-session` |\n| `--max-budget-usd` | Maximum spend (print mode) | `claude -p --max-budget-usd 5.00 \"query\"` |\n| `--json-schema` | Validated JSON output | `claude -p --json-schema '{\"type\":\"object\"}' \"q\"` |\n\n### Advanced Examples\n\n```bash\n# Limit autonomous actions\nclaude -p --max-turns 5 \"refactor this module\"\n\n# Debug API calls\nclaude --debug \"api\" \"test query\"\n\n# Enable IDE integration\nclaude --ide \"help me with this file\"\n```\n\n## Agents Configuration\n\nThe `--agents` flag accepts a JSON object defining custom subagents for a session.\n\n### Agents JSON Format\n\n```json\n{\n  \"agent-name\": {\n    \"description\": \"Required: when to invoke this agent\",\n    \"prompt\": \"Required: system prompt for the agent\",\n    \"tools\": [\"Optional\", \"array\", \"of\", \"tools\"],\n    \"model\": \"optional: sonnet|opus|haiku\"\n  }\n}\n```\n\n**Required Fields:**\n- `description` - Natural language description of when to use this agent\n- `prompt` - System prompt that defines the agent's role and behavior\n\n**Optional Fields:**\n- `tools` - Array of available tools (inherits all if omitted)\n  - Format: `[\"Read\", \"Grep\", \"Glob\", \"Bash\"]`\n- `model` - Model to use: `sonnet`, `opus`, or `haiku`\n\n### Complete Agents Example\n\n```json\n{\n  \"code-reviewer\": {\n    \"description\": \"Expert code reviewer. Use proactively after code changes.\",\n    \"prompt\": \"You are a senior code reviewer. Focus on code quality, security, and best practices.\",\n    \"tools\": [\"Read\", \"Grep\", \"Glob\", \"Bash\"],\n    \"model\": \"sonnet\"\n  },\n  \"debugger\": {\n    \"description\": \"Debugging specialist for errors and test failures.\",\n    \"prompt\": \"You are an expert debugger. Analyze errors, identify root causes, and provide fixes.\",\n    \"tools\": [\"Read\", \"Edit\", \"Bash\", \"Grep\"],\n    \"model\": \"opus\"\n  },\n  \"documenter\": {\n    \"description\": \"Documentation specialist for generating guides.\",\n    \"prompt\": \"You are a technical writer. Create clear, comprehensive documentation.\",\n    \"tools\": [\"Read\", \"Write\"],\n    \"model\": \"haiku\"\n  }\n}\n```\n\n### Agents Command Examples\n\n```bash\n# Define custom agents inline\nclaude --agents '{\n  \"security-auditor\": {\n    \"description\": \"Security specialist for vulnerability analysis\",\n    \"prompt\": \"You are a security expert. Find vulnerabilities and suggest fixes.\",\n    \"tools\": [\"Read\", \"Grep\", \"Glob\"],\n    \"model\": \"opus\"\n  }\n}' \"audit this codebase for security issues\"\n\n# Load agents from file\nclaude --agents \"$(cat ~/.claude/agents.json)\" \"review the auth module\"\n\n# Combine with other flags\nclaude -p --agents \"$(cat agents.json)\" --model sonnet \"analyze performance\"\n```\n\n### Agent Priority\n\nWhen multiple agent definitions exist, they are loaded in this priority order:\n1. **CLI-defined** (`--agents` flag) - Session-specific\n2. **User-level** (`~/.claude/agents/`) - All projects\n3. **Project-level** (`.claude/agents/`) - Current project\n\nCLI-defined agents override both user and project agents for the session.\n\n---\n\n## High-Value Use Cases\n\n### 1. CI/CD Integration\n\nUse Claude Code in your CI/CD pipelines for automated code review, testing, and documentation.\n\n**GitHub Actions Example:**\n\n```yaml\nname: AI Code Review\n\non: [pull_request]\n\njobs:\n  review:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n\n      - name: Install Claude Code\n        run: npm install -g @anthropic-ai/claude-code\n\n      - name: Run Code Review\n        env:\n          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}\n        run: |\n          claude -p --output-format json \\\n            --max-turns 1 \\\n            \"Review the changes in this PR for:\n            - Security vulnerabilities\n            - Performance issues\n            - Code quality\n            Output as JSON with 'issues' array\" > review.json\n\n      - name: Post Review Comment\n        uses: actions/github-script@v7\n        with:\n          script: |\n            const fs = require('fs');\n            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));\n            // Process and post review comments\n```\n\n**Jenkins Pipeline:**\n\n```groovy\npipeline {\n    agent any\n    stages {\n        stage('AI Review') {\n            steps {\n                sh '''\n                    claude -p --output-format json \\\n                      --max-turns 3 \\\n                      \"Analyze test coverage and suggest missing tests\" \\\n                      > coverage-analysis.json\n                '''\n            }\n        }\n    }\n}\n```\n\n### 2. Script Piping\n\nProcess files, logs, and data through Claude for analysis.\n\n**Log Analysis:**\n\n```bash\n# Analyze error logs\ntail -1000 /var/log/app/error.log | claude -p \"summarize these errors and suggest fixes\"\n\n# Find patterns in access logs\ncat access.log | claude -p \"identify suspicious access patterns\"\n\n# Analyze git history\ngit log --oneline -50 | claude -p \"summarize recent development activity\"\n```\n\n**Code Processing:**\n\n```bash\n# Review a specific file\ncat src/auth.ts | claude -p \"review this authentication code for security issues\"\n\n# Generate documentation\ncat src/api/*.ts | claude -p \"generate API documentation in markdown\"\n\n# Find TODOs and prioritize\ngrep -r \"TODO\" src/ | claude -p \"prioritize these TODOs by importance\"\n```\n\n### 3. Multi-Session Workflows\n\nManage complex projects with multiple conversation threads.\n\n```bash\n# Start a feature branch session\nclaude -r \"feature-auth\" \"let's implement user authentication\"\n\n# Later, continue the session\nclaude -r \"feature-auth\" \"add password reset functionality\"\n\n# Fork to try an alternative approach\nclaude --resume feature-auth --fork-session \"try OAuth instead\"\n\n# Switch between different feature sessions\nclaude -r \"feature-payments\" \"continue with Stripe integration\"\n```\n\n### 4. Custom Agent Configuration\n\nDefine specialized agents for your team's workflows.\n\n```bash\n# Save agents config to file\ncat > ~/.claude/agents.json << 'EOF'\n{\n  \"reviewer\": {\n    \"description\": \"Code reviewer for PR reviews\",\n    \"prompt\": \"Review code for quality, security, and maintainability.\",\n    \"model\": \"opus\"\n  },\n  \"documenter\": {\n    \"description\": \"Documentation specialist\",\n    \"prompt\": \"Generate clear, comprehensive documentation.\",\n    \"model\": \"sonnet\"\n  },\n  \"refactorer\": {\n    \"description\": \"Code refactoring expert\",\n    \"prompt\": \"Suggest and implement clean code refactoring.\",\n    \"tools\": [\"Read\", \"Edit\", \"Glob\"]\n  }\n}\nEOF\n\n# Use agents in session\nclaude --agents \"$(cat ~/.claude/agents.json)\" \"review the auth module\"\n```\n\n### 5. Batch Processing\n\nProcess multiple queries with consistent settings.\n\n```bash\n# Process multiple files\nfor file in src/*.ts; do\n  echo \"Processing $file...\"\n  claude -p --model haiku \"summarize this file: $(cat $file)\" >> summaries.md\ndone\n\n# Batch code review\nfind src -name \"*.py\" -exec sh -c '\n  echo \"## $1\" >> review.md\n  cat \"$1\" | claude -p \"brief code review\" >> review.md\n' _ {} \\;\n\n# Generate tests for all modules\nfor module in $(ls src/modules/); do\n  claude -p \"generate unit tests for src/modules/$module\" > \"tests/$module.test.ts\"\ndone\n```\n\n### 6. Security-Conscious Development\n\nUse permission controls for safe operation.\n\n```bash\n# Read-only security audit\nclaude --permission-mode plan \\\n  --tools \"Read,Grep,Glob\" \\\n  \"audit this codebase for security vulnerabilities\"\n\n# Block dangerous commands\nclaude --disallowedTools \"Bash(rm:*)\" \"Bash(curl:*)\" \"Bash(wget:*)\" \\\n  \"help me clean up this project\"\n\n# Restricted automation\nclaude -p --max-turns 2 \\\n  --allowedTools \"Read\" \"Glob\" \\\n  \"find all hardcoded credentials\"\n```\n\n### 7. JSON API Integration\n\nUse Claude as a programmable API for your tools with `jq` parsing.\n\n```bash\n# Get structured analysis\nclaude -p --output-format json \\\n  --json-schema '{\"type\":\"object\",\"properties\":{\"functions\":{\"type\":\"array\"},\"complexity\":{\"type\":\"string\"}}}' \\\n  \"analyze main.py and return function list with complexity rating\"\n\n# Integrate with jq for processing\nclaude -p --output-format json \"list all API endpoints\" | jq '.endpoints[]'\n\n# Use in scripts\nRESULT=$(claude -p --output-format json \"is this code secure? answer with {secure: boolean, issues: []}\" < code.py)\nif echo \"$RESULT\" | jq -e '.secure == false' > /dev/null; then\n  echo \"Security issues found!\"\n  echo \"$RESULT\" | jq '.issues[]'\nfi\n```\n\n### jq Parsing Examples\n\nParse and process Claude's JSON output using `jq`:\n\n```bash\n# Extract specific fields\nclaude -p --output-format json \"analyze this code\" | jq '.result'\n\n# Filter array elements\nclaude -p --output-format json \"list issues\" | jq -r '.issues[] | select(.severity==\"high\")'\n\n# Extract multiple fields\nclaude -p --output-format json \"describe the project\" | jq -r '.{name, version, description}'\n\n# Convert to CSV\nclaude -p --output-format json \"list functions\" | jq -r '.functions[] | [.name, .lineCount] | @csv'\n\n# Conditional processing\nclaude -p --output-format json \"check security\" | jq 'if .vulnerabilities | length > 0 then \"UNSAFE\" else \"SAFE\" end'\n\n# Extract nested values\nclaude -p --output-format json \"analyze performance\" | jq '.metrics.cpu.usage'\n\n# Process entire array\nclaude -p --output-format json \"find todos\" | jq '.todos | length'\n\n# Transform output\nclaude -p --output-format json \"list improvements\" | jq 'map({title: .title, priority: .priority})'\n```\n\n---\n\n## Models\n\nClaude Code supports multiple models with different capabilities:\n\n| Model | ID | Context Window | Notes |\n|-------|-----|----------------|-------|\n| Opus 4.6 | `claude-opus-4-6` | 1M tokens | Most capable, adaptive effort levels |\n| Sonnet 4.6 | `claude-sonnet-4-6` | 1M tokens | Balanced speed and capability |\n| Haiku 4.5 | `claude-haiku-4-5` | 1M tokens | Fastest, best for quick tasks |\n\n### Model Selection\n\n```bash\n# Use short names\nclaude --model opus \"complex architectural review\"\nclaude --model sonnet \"implement this feature\"\nclaude --model haiku -p \"format this JSON\"\n\n# Use opusplan alias (Opus plans, Sonnet executes)\nclaude --model opusplan \"design and implement the API\"\n\n# Toggle fast mode during session\n/fast\n```\n\n### Effort Levels (Opus 4.6)\n\nOpus 4.6 supports adaptive reasoning with effort levels:\n\n```bash\n# Set effort level via CLI flag\nclaude --effort high \"complex review\"\n\n# Set effort level via slash command\n/effort high\n\n# Set effort level via environment variable\nexport CLAUDE_CODE_EFFORT_LEVEL=high   # low, medium, high, or max (Opus 4.6 only)\n```\n\nThe \"ultrathink\" keyword in prompts activates deep reasoning. The `max` effort level is exclusive to Opus 4.6.\n\n---\n\n## Key Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `ANTHROPIC_API_KEY` | API key for authentication |\n| `ANTHROPIC_MODEL` | Override default model |\n| `ANTHROPIC_CUSTOM_MODEL_OPTION` | Custom model option for API |\n| `ANTHROPIC_DEFAULT_OPUS_MODEL` | Override default Opus model ID |\n| `ANTHROPIC_DEFAULT_SONNET_MODEL` | Override default Sonnet model ID |\n| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | Override default Haiku model ID |\n| `MAX_THINKING_TOKENS` | Set extended thinking token budget |\n| `CLAUDE_CODE_EFFORT_LEVEL` | Set effort level (`low`/`medium`/`high`/`max`) |\n| `CLAUDE_CODE_SIMPLE` | Minimal mode, set by `--bare` flag |\n| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | Disable automatic CLAUDE.md updates |\n| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Disable background task execution |\n| `CLAUDE_CODE_DISABLE_CRON` | Disable scheduled/cron tasks |\n| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | Disable git-related instructions |\n| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Disable terminal title updates |\n| `CLAUDE_CODE_DISABLE_1M_CONTEXT` | Disable 1M token context window |\n| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Disable non-streaming fallback |\n| `CLAUDE_CODE_ENABLE_TASKS` | Enable task list feature |\n| `CLAUDE_CODE_TASK_LIST_ID` | Named task directory shared across sessions |\n| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | Toggle prompt suggestions (`true`/`false`) |\n| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Enable experimental agent teams |\n| `CLAUDE_CODE_NEW_INIT` | Use new initialization flow |\n| `CLAUDE_CODE_SUBAGENT_MODEL` | Model for subagent execution |\n| `CLAUDE_CODE_PLUGIN_SEED_DIR` | Directory for plugin seed files |\n| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | Env vars to scrub from subprocesses |\n| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Override auto-compaction percentage |\n| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Stream idle timeout in milliseconds |\n| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Character budget for slash command tools |\n| `ENABLE_TOOL_SEARCH` | Enable tool search capability |\n| `MAX_MCP_OUTPUT_TOKENS` | Maximum tokens for MCP tool output |\n\n---\n\n## Quick Reference\n\n### Most Common Commands\n\n```bash\n# Interactive session\nclaude\n\n# Quick question\nclaude -p \"how do I...\"\n\n# Continue conversation\nclaude -c\n\n# Process a file\ncat file.py | claude -p \"review this\"\n\n# JSON output for scripts\nclaude -p --output-format json \"query\"\n```\n\n### Flag Combinations\n\n| Use Case | Command |\n|----------|---------|\n| Quick code review | `cat file | claude -p \"review\"` |\n| Structured output | `claude -p --output-format json \"query\"` |\n| Safe exploration | `claude --permission-mode plan` |\n| Autonomous with safety | `claude --enable-auto-mode --permission-mode auto` |\n| CI/CD integration | `claude -p --max-turns 3 --output-format json` |\n| Resume work | `claude -r \"session-name\"` |\n| Custom model | `claude --model opus \"complex task\"` |\n| Minimal mode | `claude --bare \"quick query\"` |\n| Budget-capped run | `claude -p --max-budget-usd 2.00 \"analyze code\"` |\n\n---\n\n## Troubleshooting\n\n### Command Not Found\n\n**Problem:** `claude: command not found`\n\n**Solutions:**\n- Install Claude Code: `npm install -g @anthropic-ai/claude-code`\n- Check PATH includes npm global bin directory\n- Try running with full path: `npx claude`\n\n### API Key Issues\n\n**Problem:** Authentication failed\n\n**Solutions:**\n- Set API key: `export ANTHROPIC_API_KEY=your-key`\n- Check key is valid and has sufficient credits\n- Verify key permissions for the model requested\n\n### Session Not Found\n\n**Problem:** Cannot resume session\n\n**Solutions:**\n- List available sessions to find correct name/ID\n- Sessions may expire after period of inactivity\n- Use `-c` to continue most recent session\n\n### Output Format Issues\n\n**Problem:** JSON output is malformed\n\n**Solutions:**\n- Use `--json-schema` to enforce structure\n- Add explicit JSON instructions in prompt\n- Use `--output-format json` (not just asking for JSON in prompt)\n\n### Permission Denied\n\n**Problem:** Tool execution blocked\n\n**Solutions:**\n- Check `--permission-mode` setting\n- Review `--allowedTools` and `--disallowedTools` flags\n- Use `--dangerously-skip-permissions` for automation (with caution)\n\n---\n\n## Additional Resources\n\n- **[Official CLI Reference](https://code.claude.com/docs/en/cli-reference)** - Complete command reference\n- **[Headless Mode Documentation](https://code.claude.com/docs/en/headless)** - Automated execution\n- **[Slash Commands](../01-slash-commands/)** - Custom shortcuts within Claude\n- **[Memory Guide](../02-memory/)** - Persistent context via CLAUDE.md\n- **[MCP Protocol](../05-mcp/)** - External tool integrations\n- **[Advanced Features](../09-advanced-features/)** - Planning mode, extended thinking\n- **[Subagents Guide](../04-subagents/)** - Delegated task execution\n\n---\n\n*Part of the [Claude How To](../) guide series*\n"
  },
  {
    "path": "CATALOG.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Claude Code Feature Catalog\n\n> Quick reference guide to all Claude Code features: commands, agents, skills, plugins, and hooks.\n\n**Navigation**: [Commands](#slash-commands) | [Permission Modes](#permission-modes) | [Subagents](#subagents) | [Skills](#skills) | [Plugins](#plugins) | [MCP Servers](#mcp-servers) | [Hooks](#hooks) | [Memory](#memory-files) | [New Features](#new-features-march-2026)\n\n---\n\n## Summary\n\n| Feature | Built-in | Examples | Total | Reference |\n|---------|----------|----------|-------|-----------|\n| **Slash Commands** | 55+ | 8 | 63+ | [01-slash-commands/](01-slash-commands/) |\n| **Subagents** | 6 | 10 | 16 | [04-subagents/](04-subagents/) |\n| **Skills** | 5 bundled | 4 | 9 | [03-skills/](03-skills/) |\n| **Plugins** | - | 3 | 3 | [07-plugins/](07-plugins/) |\n| **MCP Servers** | 1 | 8 | 9 | [05-mcp/](05-mcp/) |\n| **Hooks** | 25 events | 7 | 7 | [06-hooks/](06-hooks/) |\n| **Memory** | 7 types | 3 | 3 | [02-memory/](02-memory/) |\n| **Total** | **99** | **43** | **117** | |\n\n---\n\n## Slash Commands\n\nCommands are user-invoked shortcuts that execute specific actions.\n\n### Built-in Commands\n\n| Command | Description | When to Use |\n|---------|-------------|-------------|\n| `/help` | Show help information | Get started, learn commands |\n| `/btw` | Side question without adding to context | Quick tangent questions |\n| `/chrome` | Configure Chrome integration | Browser automation |\n| `/clear` | Clear conversation history | Start fresh, reduce context |\n| `/diff` | Interactive diff viewer | Review changes |\n| `/config` | View/edit configuration | Customize behavior |\n| `/status` | Show session status | Check current state |\n| `/agents` | List available agents | See delegation options |\n| `/skills` | List available skills | See auto-invoke capabilities |\n| `/hooks` | List configured hooks | Debug automation |\n| `/insights` | Analyze session patterns | Session optimization |\n| `/install-slack-app` | Install Claude Slack app | Slack integration |\n| `/keybindings` | Customize keyboard shortcuts | Key customization |\n| `/mcp` | List MCP servers | Check external integrations |\n| `/memory` | View loaded memory files | Debug context loading |\n| `/mobile` | Generate mobile QR code | Mobile access |\n| `/passes` | View usage passes | Subscription info |\n| `/plugin` | Manage plugins | Install/remove extensions |\n| `/plan` | Enter planning mode | Complex implementations |\n| `/rewind` | Rewind to checkpoint | Undo changes, explore alternatives |\n| `/checkpoint` | Manage checkpoints | Save/restore states |\n| `/cost` | Show token usage costs | Monitor spending |\n| `/context` | Show context window usage | Manage conversation length |\n| `/export` | Export conversation | Save for reference |\n| `/extra-usage` | Configure extra usage limits | Rate limit management |\n| `/feedback` | Submit feedback or bug report | Report issues |\n| `/login` | Authenticate with Anthropic | Access features |\n| `/logout` | Sign out | Switch accounts |\n| `/sandbox` | Toggle sandbox mode | Safe command execution |\n| `/vim` | Toggle vim mode | Vim-style editing |\n| `/doctor` | Run diagnostics | Troubleshoot issues |\n| `/reload-plugins` | Reload installed plugins | Plugin management |\n| `/release-notes` | Show release notes | Check new features |\n| `/remote-control` | Enable remote control | Remote access |\n| `/permissions` | Manage permissions | Control access |\n| `/session` | Manage sessions | Multi-session workflows |\n| `/rename` | Rename current session | Organize sessions |\n| `/resume` | Resume previous session | Continue work |\n| `/todo` | View/manage todo list | Track tasks |\n| `/tasks` | View background tasks | Monitor async operations |\n| `/copy` | Copy last response to clipboard | Share output quickly |\n| `/teleport` | Transfer session to another machine | Continue work remotely |\n| `/desktop` | Open Claude Desktop app | Switch to desktop interface |\n| `/theme` | Change color theme | Customize appearance |\n| `/usage` | Show API usage statistics | Monitor quota and costs |\n| `/fork` | Fork current conversation | Explore alternatives |\n| `/stats` | Show session statistics | Review session metrics |\n| `/statusline` | Configure status line | Customize status display |\n| `/stickers` | View session stickers | Fun rewards |\n| `/fast` | Toggle fast output mode | Speed up responses |\n| `/terminal-setup` | Configure terminal integration | Setup terminal features |\n| `/upgrade` | Check for updates | Version management |\n\n### Custom Commands (Examples)\n\n| Command | Description | When to Use | Scope | Installation |\n|---------|-------------|-------------|-------|--------------|\n| `/optimize` | Analyze code for optimization | Performance improvement | Project | `cp 01-slash-commands/optimize.md .claude/commands/` |\n| `/pr` | Prepare pull request | Before submitting PRs | Project | `cp 01-slash-commands/pr.md .claude/commands/` |\n| `/generate-api-docs` | Generate API documentation | Document APIs | Project | `cp 01-slash-commands/generate-api-docs.md .claude/commands/` |\n| `/commit` | Create git commit with context | Commit changes | User | `cp 01-slash-commands/commit.md .claude/commands/` |\n| `/push-all` | Stage, commit, and push | Quick deployment | User | `cp 01-slash-commands/push-all.md .claude/commands/` |\n| `/doc-refactor` | Restructure documentation | Improve docs | Project | `cp 01-slash-commands/doc-refactor.md .claude/commands/` |\n| `/setup-ci-cd` | Setup CI/CD pipeline | New projects | Project | `cp 01-slash-commands/setup-ci-cd.md .claude/commands/` |\n| `/unit-test-expand` | Expand test coverage | Improve testing | Project | `cp 01-slash-commands/unit-test-expand.md .claude/commands/` |\n\n> **Scope**: `User` = personal workflows (`~/.claude/commands/`), `Project` = team-shared (`.claude/commands/`)\n\n**Reference**: [01-slash-commands/](01-slash-commands/) | [Official Docs](https://code.claude.com/docs/en/interactive-mode)\n\n**Quick Install (All Custom Commands)**:\n```bash\ncp 01-slash-commands/*.md .claude/commands/\n```\n\n---\n\n## Permission Modes\n\nClaude Code supports 6 permission modes that control how tool use is authorized.\n\n| Mode | Description | When to Use |\n|------|-------------|-------------|\n| `default` | Prompt for each tool call | Standard interactive use |\n| `acceptEdits` | Auto-accept file edits, prompt for others | Trusted editing workflows |\n| `plan` | Read-only tools only, no writes | Planning and exploration |\n| `auto` | Accept all tools without prompting | Fully autonomous operation (Research Preview) |\n| `bypassPermissions` | Skip all permission checks | CI/CD, headless environments |\n| `dontAsk` | Skip tools that would require permission | Non-interactive scripting |\n\n> **Note**: `auto` mode is a Research Preview feature (March 2026). Use `bypassPermissions` only in trusted, sandboxed environments.\n\n**Reference**: [Official Docs](https://code.claude.com/docs/en/permissions)\n\n---\n\n## Subagents\n\nSpecialized AI assistants with isolated contexts for specific tasks.\n\n### Built-in Subagents\n\n| Agent | Description | Tools | Model | When to Use |\n|-------|-------------|-------|-------|-------------|\n| **general-purpose** | Multi-step tasks, research | All tools | Inherits model | Complex research, multi-file tasks |\n| **Plan** | Implementation planning | Read, Glob, Grep, Bash | Inherits model | Architecture design, planning |\n| **Explore** | Codebase exploration | Read, Glob, Grep | Haiku 4.5 | Quick searches, understanding code |\n| **Bash** | Command execution | Bash | Inherits model | Git operations, terminal tasks |\n| **statusline-setup** | Status line configuration | Bash, Read, Write | Sonnet 4.6 | Configure status line display |\n| **Claude Code Guide** | Help and documentation | Read, Glob, Grep | Haiku 4.5 | Getting help, learning features |\n\n### Subagent Configuration Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | string | Agent identifier |\n| `description` | string | What the agent does |\n| `model` | string | Model override (e.g., `haiku-4.5`) |\n| `tools` | array | Allowed tools list |\n| `effort` | string | Reasoning effort level (`low`, `medium`, `high`) |\n| `initialPrompt` | string | System prompt injected at agent start |\n| `disallowedTools` | array | Tools explicitly denied to this agent |\n\n### Custom Subagents (Examples)\n\n| Agent | Description | When to Use | Scope | Installation |\n|-------|-------------|-------------|-------|--------------|\n| `code-reviewer` | Comprehensive code quality | Code review sessions | Project | `cp 04-subagents/code-reviewer.md .claude/agents/` |\n| `code-architect` | Feature architecture design | New feature planning | Project | `cp 04-subagents/code-architect.md .claude/agents/` |\n| `code-explorer` | Deep codebase analysis | Understanding existing features | Project | `cp 04-subagents/code-explorer.md .claude/agents/` |\n| `clean-code-reviewer` | Clean Code principles review | Maintainability review | Project | `cp 04-subagents/clean-code-reviewer.md .claude/agents/` |\n| `test-engineer` | Test strategy & coverage | Test planning | Project | `cp 04-subagents/test-engineer.md .claude/agents/` |\n| `documentation-writer` | Technical documentation | API docs, guides | Project | `cp 04-subagents/documentation-writer.md .claude/agents/` |\n| `secure-reviewer` | Security-focused review | Security audits | Project | `cp 04-subagents/secure-reviewer.md .claude/agents/` |\n| `implementation-agent` | Full feature implementation | Feature development | Project | `cp 04-subagents/implementation-agent.md .claude/agents/` |\n| `debugger` | Root cause analysis | Bug investigation | User | `cp 04-subagents/debugger.md .claude/agents/` |\n| `data-scientist` | SQL queries, data analysis | Data tasks | User | `cp 04-subagents/data-scientist.md .claude/agents/` |\n\n> **Scope**: `User` = personal (`~/.claude/agents/`), `Project` = team-shared (`.claude/agents/`)\n\n**Reference**: [04-subagents/](04-subagents/) | [Official Docs](https://code.claude.com/docs/en/sub-agents)\n\n**Quick Install (All Custom Agents)**:\n```bash\ncp 04-subagents/*.md .claude/agents/\n```\n\n---\n\n## Skills\n\nAuto-invoked capabilities with instructions, scripts, and templates.\n\n### Example Skills\n\n| Skill | Description | When Auto-Invoked | Scope | Installation |\n|-------|-------------|-------------------|-------|--------------|\n| `code-review` | Comprehensive code review | \"Review this code\", \"Check quality\" | Project | `cp -r 03-skills/code-review .claude/skills/` |\n| `brand-voice` | Brand consistency checker | Writing marketing copy | Project | `cp -r 03-skills/brand-voice .claude/skills/` |\n| `doc-generator` | API documentation generator | \"Generate docs\", \"Document API\" | Project | `cp -r 03-skills/doc-generator .claude/skills/` |\n| `refactor` | Systematic code refactoring (Martin Fowler) | \"Refactor this\", \"Clean up code\" | User | `cp -r 03-skills/refactor ~/.claude/skills/` |\n\n> **Scope**: `User` = personal (`~/.claude/skills/`), `Project` = team-shared (`.claude/skills/`)\n\n### Skill Structure\n\n```\n~/.claude/skills/skill-name/\n├── SKILL.md          # Skill definition & instructions\n├── scripts/          # Helper scripts\n└── templates/        # Output templates\n```\n\n### Skill Frontmatter Fields\n\nSkills support YAML frontmatter in `SKILL.md` for configuration:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | string | Skill display name |\n| `description` | string | What the skill does |\n| `autoInvoke` | array | Trigger phrases for auto-invocation |\n| `effort` | string | Reasoning effort level (`low`, `medium`, `high`) |\n| `shell` | string | Shell to use for scripts (`bash`, `zsh`, `sh`) |\n\n**Reference**: [03-skills/](03-skills/) | [Official Docs](https://code.claude.com/docs/en/skills)\n\n**Quick Install (All Skills)**:\n```bash\ncp -r 03-skills/* ~/.claude/skills/\n```\n\n### Bundled Skills\n\n| Skill | Description | When Auto-Invoked |\n|-------|-------------|-------------------|\n| `/simplify` | Review code for quality | After writing code |\n| `/batch` | Run prompts on multiple files | Batch operations |\n| `/debug` | Debug failing tests/errors | Debugging sessions |\n| `/loop` | Run prompts on interval | Recurring tasks |\n| `/claude-api` | Build apps with Claude API | API development |\n\n---\n\n## Plugins\n\nBundled collections of commands, agents, MCP servers, and hooks.\n\n### Example Plugins\n\n| Plugin | Description | Components | When to Use | Scope | Installation |\n|--------|-------------|------------|-------------|-------|--------------|\n| `pr-review` | PR review workflow | 3 commands, 3 agents, GitHub MCP | Code reviews | Project | `/plugin install pr-review` |\n| `devops-automation` | Deployment & monitoring | 4 commands, 3 agents, K8s MCP | DevOps tasks | Project | `/plugin install devops-automation` |\n| `documentation` | Doc generation suite | 4 commands, 3 agents, templates | Documentation | Project | `/plugin install documentation` |\n\n> **Scope**: `Project` = team-shared, `User` = personal workflows\n\n### Plugin Structure\n\n```\n.claude-plugin/\n├── plugin.json       # Manifest file\n├── commands/         # Slash commands\n├── agents/           # Subagents\n├── skills/           # Skills\n├── mcp/              # MCP configurations\n├── hooks/            # Hook scripts\n└── scripts/          # Utility scripts\n```\n\n**Reference**: [07-plugins/](07-plugins/) | [Official Docs](https://code.claude.com/docs/en/plugins)\n\n**Plugin Management Commands**:\n```bash\n/plugin list              # List installed plugins\n/plugin install <name>    # Install plugin\n/plugin remove <name>     # Remove plugin\n/plugin update <name>     # Update plugin\n```\n\n---\n\n## MCP Servers\n\nModel Context Protocol servers for external tool and API access.\n\n### Common MCP Servers\n\n| Server | Description | When to Use | Scope | Installation |\n|--------|-------------|-------------|-------|--------------|\n| **GitHub** | PR management, issues, code | GitHub workflows | Project | `claude mcp add github -- npx -y @modelcontextprotocol/server-github` |\n| **Database** | SQL queries, data access | Database operations | Project | `claude mcp add db -- npx -y @modelcontextprotocol/server-postgres` |\n| **Filesystem** | Advanced file operations | Complex file tasks | User | `claude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem` |\n| **Slack** | Team communication | Notifications, updates | Project | Configure in settings |\n| **Google Docs** | Document access | Doc editing, review | Project | Configure in settings |\n| **Asana** | Project management | Task tracking | Project | Configure in settings |\n| **Stripe** | Payment data | Financial analysis | Project | Configure in settings |\n| **Memory** | Persistent memory | Cross-session recall | User | Configure in settings |\n| **Context7** | Library documentation | Up-to-date docs lookup | Built-in | Built-in |\n\n> **Scope**: `Project` = team (`.mcp.json`), `User` = personal (`~/.claude.json`), `Built-in` = pre-installed\n\n### MCP Configuration Example\n\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n**Reference**: [05-mcp/](05-mcp/) | [MCP Protocol Docs](https://modelcontextprotocol.io)\n\n**Quick Install (GitHub MCP)**:\n```bash\nexport GITHUB_TOKEN=\"your_token\" && claude mcp add github -- npx -y @modelcontextprotocol/server-github\n```\n\n---\n\n## Hooks\n\nEvent-driven automation that executes shell commands on Claude Code events.\n\n### Hook Events\n\n| Event | Description | When Triggered | Use Cases |\n|-------|-------------|----------------|-----------|\n| `SessionStart` | Session begins/resumes | Session initialization | Setup tasks |\n| `InstructionsLoaded` | Instructions loaded | CLAUDE.md or rules file loaded | Custom instruction handling |\n| `UserPromptSubmit` | Before prompt processing | User sends message | Input validation |\n| `PreToolUse` | Before tool execution | Before any tool runs | Validation, logging |\n| `PermissionRequest` | Permission dialog shown | Before sensitive actions | Custom approval flows |\n| `PostToolUse` | After tool succeeds | After any tool completes | Formatting, notifications |\n| `PostToolUseFailure` | Tool execution fails | After tool error | Error handling, logging |\n| `Notification` | Notification sent | Claude sends notification | External alerts |\n| `SubagentStart` | Subagent spawned | Subagent task starts | Initialize subagent context |\n| `SubagentStop` | Subagent finishes | Subagent task complete | Chain actions |\n| `Stop` | Claude finishes responding | Response complete | Cleanup, reporting |\n| `StopFailure` | API error ends turn | API error occurs | Error recovery, logging |\n| `TeammateIdle` | Teammate agent idle | Agent team coordination | Distribute work |\n| `TaskCompleted` | Task marked complete | Task done | Post-task processing |\n| `TaskCreated` | Task created via TaskCreate | New task created | Task tracking, logging |\n| `ConfigChange` | Configuration updated | Settings modified | React to config changes |\n| `CwdChanged` | Working directory changes | Directory changed | Directory-specific setup |\n| `FileChanged` | Watched file changes | File modified | File monitoring, rebuild |\n| `PreCompact` | Before compact operation | Context compression | State preservation |\n| `PostCompact` | After compaction completes | Compaction done | Post-compact actions |\n| `WorktreeCreate` | Worktree being created | Git worktree created | Setup worktree environment |\n| `WorktreeRemove` | Worktree being removed | Git worktree removed | Cleanup worktree resources |\n| `Elicitation` | MCP server requests input | MCP elicitation | Input validation |\n| `ElicitationResult` | User responds to elicitation | User responds | Response processing |\n| `SessionEnd` | Session terminates | Session termination | Cleanup, save state |\n\n### Example Hooks\n\n| Hook | Description | Event | Scope | Installation |\n|------|-------------|-------|-------|--------------|\n| `validate-bash.py` | Command validation | PreToolUse:Bash | Project | `cp 06-hooks/validate-bash.py .claude/hooks/` |\n| `security-scan.py` | Security scanning | PostToolUse:Write | Project | `cp 06-hooks/security-scan.py .claude/hooks/` |\n| `format-code.sh` | Auto-formatting | PostToolUse:Write | User | `cp 06-hooks/format-code.sh ~/.claude/hooks/` |\n| `validate-prompt.py` | Prompt validation | UserPromptSubmit | Project | `cp 06-hooks/validate-prompt.py .claude/hooks/` |\n| `context-tracker.py` | Token usage tracking | Stop | User | `cp 06-hooks/context-tracker.py ~/.claude/hooks/` |\n| `pre-commit.sh` | Pre-commit validation | PreToolUse:Bash | Project | `cp 06-hooks/pre-commit.sh .claude/hooks/` |\n| `log-bash.sh` | Command logging | PostToolUse:Bash | User | `cp 06-hooks/log-bash.sh ~/.claude/hooks/` |\n\n> **Scope**: `Project` = team (`.claude/settings.json`), `User` = personal (`~/.claude/settings.json`)\n\n### Hook Configuration\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"command\": \"~/.claude/hooks/validate-bash.py\"\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Write\",\n        \"command\": \"~/.claude/hooks/format-code.sh\"\n      }\n    ]\n  }\n}\n```\n\n**Reference**: [06-hooks/](06-hooks/) | [Official Docs](https://code.claude.com/docs/en/hooks)\n\n**Quick Install (All Hooks)**:\n```bash\nmkdir -p ~/.claude/hooks && cp 06-hooks/*.sh ~/.claude/hooks/ && chmod +x ~/.claude/hooks/*.sh\n```\n\n---\n\n## Memory Files\n\nPersistent context loaded automatically across sessions.\n\n### Memory Types\n\n| Type | Location | Scope | When to Use |\n|------|----------|-------|-------------|\n| **Managed Policy** | Org-managed policies | Organization | Enforce org-wide standards |\n| **Project** | `./CLAUDE.md` | Project (team) | Team standards, project context |\n| **Project Rules** | `.claude/rules/` | Project (team) | Modular project rules |\n| **User** | `~/.claude/CLAUDE.md` | User (personal) | Personal preferences |\n| **User Rules** | `~/.claude/rules/` | User (personal) | Modular personal rules |\n| **Local** | `./CLAUDE.local.md` | Local (git-ignored) | Machine-specific overrides (not in official docs as of March 2026; may be legacy) |\n| **Auto Memory** | Automatic | Session | Auto-captured insights and corrections |\n\n> **Scope**: `Organization` = managed by admins, `Project` = shared with team via git, `User` = personal preferences, `Local` = not committed, `Session` = auto-managed\n\n**Reference**: [02-memory/](02-memory/) | [Official Docs](https://code.claude.com/docs/en/memory)\n\n**Quick Install**:\n```bash\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\ncp 02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md\n```\n\n---\n\n## New Features (March 2026)\n\n| Feature | Description | How to Use |\n|---------|-------------|------------|\n| **Remote Control** | Control Claude Code sessions remotely via API | Use the remote control API to send prompts and receive responses programmatically |\n| **Web Sessions** | Run Claude Code in a browser-based environment | Access via `claude web` or through the Anthropic Console |\n| **Desktop App** | Native desktop application for Claude Code | Use `/desktop` or download from Anthropic website |\n| **Agent Teams** | Coordinate multiple agents working on related tasks | Configure teammate agents that collaborate and share context |\n| **Task List** | Background task management and monitoring | Use `/tasks` to view and manage background operations |\n| **Prompt Suggestions** | Context-aware command suggestions | Suggestions appear automatically based on current context |\n| **Git Worktrees** | Isolated git worktrees for parallel development | Use worktree commands for safe parallel branch work |\n| **Sandboxing** | Isolated execution environments for safety | Use `/sandbox` to toggle; runs commands in restricted environments |\n| **MCP OAuth** | OAuth authentication for MCP servers | Configure OAuth credentials in MCP server settings for secure access |\n| **MCP Tool Search** | Search and discover MCP tools dynamically | Use tool search to find available MCP tools across connected servers |\n| **Scheduled Tasks** | Set up recurring tasks with `/loop` and cron tools | Use `/loop 5m /command` or CronCreate tool |\n| **Chrome Integration** | Browser automation with headless Chromium | Use `--chrome` flag or `/chrome` command |\n| **Keyboard Customization** | Customize keybindings including chord support | Use `/keybindings` or edit `~/.claude/keybindings.json` |\n| **Auto Mode** | Fully autonomous operation without permission prompts (Research Preview) | Use `--mode auto` or `/permissions auto`; March 2026 |\n| **Channels** | Multi-channel communication (Telegram, Slack, etc.) (Research Preview) | Configure channel plugins; March 2026 |\n| **Voice Dictation** | Voice input for prompts | Use microphone icon or voice keybinding |\n| **Agent Hook Type** | Hooks that spawn a subagent instead of running a shell command | Set `\"type\": \"agent\"` in hook configuration |\n| **Prompt Hook Type** | Hooks that inject prompt text into the conversation | Set `\"type\": \"prompt\"` in hook configuration |\n| **MCP Elicitation** | MCP servers can request user input during tool execution | Handle via `Elicitation` and `ElicitationResult` hook events |\n| **WebSocket MCP Transport** | WebSocket-based transport for MCP server connections | Use `\"transport\": \"websocket\"` in MCP server config |\n| **Plugin LSP Support** | Language Server Protocol integration via plugins | Configure LSP servers in `plugin.json` for editor features |\n| **Managed Drop-ins** | Organization-managed drop-in configurations (v2.1.83) | Admin-configured via managed policies; auto-applied to all users |\n\n---\n\n## Quick Reference Matrix\n\n### Feature Selection Guide\n\n| Need | Recommended Feature | Why |\n|------|---------------------|-----|\n| Quick shortcut | Slash Command | Manual, immediate |\n| Persistent context | Memory | Auto-loaded |\n| Complex automation | Skill | Auto-invoked |\n| Specialized task | Subagent | Isolated context |\n| External data | MCP Server | Real-time access |\n| Event automation | Hook | Event-triggered |\n| Complete solution | Plugin | All-in-one bundle |\n\n### Installation Priority\n\n| Priority | Feature | Command |\n|----------|---------|---------|\n| 1. Essential | Memory | `cp 02-memory/project-CLAUDE.md ./CLAUDE.md` |\n| 2. Daily Use | Slash Commands | `cp 01-slash-commands/*.md .claude/commands/` |\n| 3. Quality | Subagents | `cp 04-subagents/*.md .claude/agents/` |\n| 4. Automation | Hooks | `cp 06-hooks/*.sh ~/.claude/hooks/ && chmod +x ~/.claude/hooks/*.sh` |\n| 5. External | MCP | `claude mcp add github -- npx -y @modelcontextprotocol/server-github` |\n| 6. Advanced | Skills | `cp -r 03-skills/* ~/.claude/skills/` |\n| 7. Complete | Plugins | `/plugin install pr-review` |\n\n---\n\n## Complete One-Command Installation\n\nInstall all examples from this repository:\n\n```bash\n# Create directories\nmkdir -p .claude/{commands,agents,skills} ~/.claude/{hooks,skills}\n\n# Install all features\ncp 01-slash-commands/*.md .claude/commands/ && \\\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md && \\\ncp -r 03-skills/* ~/.claude/skills/ && \\\ncp 04-subagents/*.md .claude/agents/ && \\\ncp 06-hooks/*.sh ~/.claude/hooks/ && \\\nchmod +x ~/.claude/hooks/*.sh\n```\n\n---\n\n## Additional Resources\n\n- [Official Claude Code Documentation](https://code.claude.com/docs/en/overview)\n- [MCP Protocol Specification](https://modelcontextprotocol.io)\n- [Learning Roadmap](LEARNING-ROADMAP.md)\n- [Main README](README.md)\n\n---\n\n**Last Updated**: March 2026\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\n## v2.2.0 — 2026-03-26\n\n### Documentation\n\n- Sync all tutorials and references with Claude Code v2.1.84 (f78c094) @luongnv89\n  - Update slash commands to 55+ built-in + 5 bundled skills, mark 3 deprecated\n  - Expand hook events from 18 to 25, add `agent` hook type (now 4 types)\n  - Add Auto Mode, Channels, Voice Dictation to advanced features\n  - Add `effort`, `shell` skill frontmatter fields; `initialPrompt`, `disallowedTools` agent fields\n  - Add WebSocket MCP transport, elicitation, 2KB tool cap\n  - Add plugin LSP support, `userConfig`, `${CLAUDE_PLUGIN_DATA}`\n  - Update all reference docs (CATALOG, QUICK_REFERENCE, LEARNING-ROADMAP, INDEX)\n- Rewrite README as landing-page-structured guide (32a0776) @luongnv89\n\n### Bug Fixes\n\n- Add missing cSpell words and README sections for CI compliance (93f9d51) @luongnv89\n- Add `Sandboxing` to cSpell dictionary (b80ce6f) @luongnv89\n\n**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.1.1...v2.2.0\n\n---\n\n## v2.1.1 — 2026-03-13\n\n### Bug Fixes\n\n- Remove dead marketplace link failing CI link checks (3fdf0d6) @luongnv89\n- Add `sandboxed` and `pycache` to cSpell dictionary (dc64618) @luongnv89\n\n**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.1.0...v2.1.1\n\n---\n\n## v2.1.0 — 2026-03-13\n\n### Features\n\n- Add adaptive learning path with self-assessment and lesson quiz skills (1ef46cd) @luongnv89\n  - `/self-assessment` — interactive proficiency quiz across 10 feature areas with personalized learning path\n  - `/lesson-quiz [lesson]` — per-lesson knowledge check with 8-10 targeted questions\n\n### Bug Fixes\n\n- Update broken URLs, deprecations, and outdated references (8fe4520) @luongnv89\n- Fix broken links in resources and self-assessment skill (7a05863) @luongnv89\n- Use tilde fences for nested code blocks in concepts guide (5f82719) @VikalpP\n- Add missing words to cSpell dictionary (8df7572) @luongnv89\n\n### Documentation\n\n- Phase 5 QA — fix consistency, URLs, and terminology across docs (00bbe4c) @luongnv89\n- Complete Phases 3-4 — new feature coverage and reference doc updates (132de29) @luongnv89\n- Add MCPorter runtime to MCP context bloat section (ef52705) @luongnv89\n- Add missing commands, features, and settings across 6 guides (4bc8f15) @luongnv89\n- Add style guide based on existing repo conventions (84141d0) @luongnv89\n- Add self-assessment row to guide comparison table (8fe0c96) @luongnv89\n- Add VikalpP to contributors list for PR #7 (d5b4350) @luongnv89\n- Add self-assessment and lesson-quiz skill references to README and roadmap (d5a6106) @luongnv89\n\n### New Contributors\n\n- @VikalpP made their first contribution in #7\n\n**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.0.0...v2.1.0\n\n---\n\n## v2.0.0 — 2026-02-01\n\n### Features\n\n- Sync all documentation with Claude Code February 2026 features (487c96d)\n  - Update 26 files across all 10 tutorial directories and 7 reference documents\n  - Add documentation for **Auto Memory** — persistent learnings per project\n  - Add documentation for **Remote Control**, **Web Sessions**, and **Desktop App**\n  - Add documentation for **Agent Teams** (experimental multi-agent collaboration)\n  - Add documentation for **MCP OAuth 2.0**, **Tool Search**, and **Claude.ai Connectors**\n  - Add documentation for **Persistent Memory** and **Worktree Isolation** for subagents\n  - Add documentation for **Background Subagents**, **Task List**, **Prompt Suggestions**\n  - Add documentation for **Sandboxing** and **Managed Settings** (Enterprise)\n  - Add documentation for **HTTP Hooks** and 7 new hook events\n  - Add documentation for **Plugin Settings**, **LSP Servers**, and Marketplace updates\n  - Add documentation for **Summarize from Checkpoint** rewind option\n  - Document 17 new slash commands (`/fork`, `/desktop`, `/teleport`, `/tasks`, `/fast`, etc.)\n  - Document new CLI flags (`--worktree`, `--from-pr`, `--remote`, `--teleport`, `--teammate-mode`, etc.)\n  - Document new environment variables for auto memory, effort levels, agent teams, and more\n\n### Design\n\n- Redesign logo to compass-bracket mark with minimal palette (20779db)\n\n### Bug Fixes / Corrections\n\n- Update model names: Sonnet 4.5 → **Sonnet 4.6**, Opus 4.5 → **Opus 4.6**\n- Fix permission mode names: replace fictional \"Unrestricted/Confirm/Read-only\" with actual `default`/`acceptEdits`/`plan`/`dontAsk`/`bypassPermissions`\n- Fix hook events: remove fictional `PreCommit`/`PostCommit`/`PrePush`, add real events (`SubagentStart`, `WorktreeCreate`, `ConfigChange`, etc.)\n- Fix CLI syntax: replace `claude-code --headless` with `claude -p` (print mode)\n- Fix checkpoint commands: replace fictional `/checkpoint save/list/rewind/diff` with actual `Esc+Esc` / `/rewind` interface\n- Fix session management: replace fictional `/session list/new/switch/save` with real `/resume`/`/rename`/`/fork`\n- Fix plugin manifest format: migrate `plugin.yaml` → `.claude-plugin/plugin.json`\n- Fix MCP config paths: `~/.claude/mcp.json` → `.mcp.json` (project) / `~/.claude.json` (user)\n- Fix documentation URLs: `docs.claude.com` → `docs.anthropic.com`; remove fictional `plugins.claude.com`\n- Remove fictional configuration fields across multiple files\n- Update all \"Last Updated\" dates to February 2026\n\n**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/20779db...v2.0.0\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Code of Conduct\n\n## Our Commitment\n\nWe are committed to providing a welcoming and inspiring community for all. We pledge that participating in our community is a harassment-free experience for everyone, regardless of age, body size, caste, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socioeconomic status, nationality, personal appearance, race, religion, or sexual identity and orientation.\n\nWe are dedicated to providing a positive, inclusive, and safe environment where all contributors feel respected, valued, and empowered to contribute their best work.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment include:\n\n### Be Respectful\n- Use welcoming and inclusive language\n- Be respectful of differing opinions, viewpoints, and experiences\n- Accept constructive criticism gracefully\n- Respect cultural and linguistic differences\n- Acknowledge and celebrate diverse backgrounds\n\n### Be Collaborative\n- Work together to resolve conflicts\n- Give credit and recognize others' contributions\n- Help others learn and grow\n- Share knowledge and ask questions\n- Support fellow community members\n\n### Be Professional\n- Keep discussions focused and productive\n- Avoid demeaning or insulting remarks\n- Stay on topic in issues and discussions\n- Use clear and respectful communication\n- Assume good intent in others' messages\n\n### Be Inclusive\n- Welcome new contributors\n- Help onboard people new to the project\n- Provide constructive feedback\n- Include people with different perspectives\n- Create space for quiet voices to be heard\n\n## Unacceptable Behavior\n\nThe following behaviors are considered harassment and are unacceptable within our community:\n\n### Harassment and Discrimination\n- Offensive comments related to gender, gender identity and expression, sexual orientation, disability, mental illness, neuro(a)typicality, physical appearance, body size, age, race, or religion\n- Unwelcome comments regarding a person's lifestyle choices and practices\n- Deliberate misgendering or use of 'dead' or rejected names\n- Gratuitous or off-topic sexual images or behavior\n- Physical contact and simulated physical contact without consent or after a request to stop\n\n### Abusive Behavior\n- Threats of violence or violent language directed against another person\n- Incitement of violence or violent language toward any individual\n- Deliberate intimidation\n- Stalking or following\n- Harassment through repeated contact\n- Any other conduct which could reasonably be considered inappropriate\n\n### Online Harassment\n- Sustained disruption of online discussion\n- Publishing others' private information (doxxing)\n- Unwelcome sexual attention or advances\n- Trolling or intentional disruption\n- Spam or repetitive advertising\n- Spreading misinformation or disinformation\n\n### Retaliation\n- Taking retaliatory action against someone for reporting a violation\n- Treating someone unfairly because they reported unacceptable behavior\n- Threatening to report someone in retaliation\n\n## Scope\n\nThis Code of Conduct applies to:\n- All community spaces (GitHub issues, pull requests, discussions, etc.)\n- Project repositories and documentation\n- Events and gatherings organized by or representing the project\n- Public spaces where individuals are representing the project or the community\n- Private communications when they relate to project business\n\nThe Code of Conduct applies to all project spaces, and it also applies when an individual is representing the project or community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.\n\n## Enforcement\n\nCommunity leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.\n\n### Reporting a Violation\n\nIf you experience or witness unacceptable behavior, or have any other concerns, please report it by:\n\n1. **Email**: Contact the project maintainers at [provide contact method if available]\n2. **GitHub Issues**: Private report feature (if available in your GitHub settings)\n3. **Direct Message**: Contact a project maintainer directly\n\nPlease provide:\n- Your contact information\n- Names of those involved (if you feel comfortable sharing)\n- Description of the incident\n- Context and any relevant links\n- How the incident affected you\n\n**All reports will be kept confidential.**\n\n### Investigation and Response\n\nCommunity leaders will:\n- Review and investigate all complaints promptly and fairly\n- Maintain confidentiality with respect to the reporter\n- Respond to the reporter about the status of their report\n- Take appropriate action based on findings\n\nPossible actions include:\n- Private warning or coaching\n- Public apology (if the violator agrees)\n- Temporary or permanent removal from community spaces\n- Loss of contributor privileges\n- Escalation to GitHub or other platforms as needed\n\n### Appeal Process\n\nIf you believe a decision was made in error, you may appeal by:\n1. Providing new information or context\n2. Requesting a review by multiple maintainers\n3. Following up within 30 days of the initial decision\n\n## Guidelines for Respectful Disagreement\n\nDisagreements are natural in technical communities. Here's how to disagree respectfully:\n\n### Do's\n- ✅ Focus on the idea, not the person\n- ✅ Ask clarifying questions\n- ✅ Acknowledge valid points in opposing views\n- ✅ Use \"I\" statements (\"I disagree because...\")\n- ✅ Cite sources and evidence\n- ✅ Thank others for their perspective\n\n### Don'ts\n- ❌ Make personal attacks\n- ❌ Use dismissive language (\"That's stupid\")\n- ❌ Assume bad intent\n- ❌ Bring up unrelated past conflicts\n- ❌ Escalate tone or become hostile\n- ❌ Deliberately misrepresent others' views\n\n### Example of Respectful Disagreement\n```\n❌ Bad: \"That's a dumb idea and you clearly don't understand the project.\"\n\n✅ Good: \"I see your point, but I'm concerned this approach might\nnot scale well with larger projects. Have you considered the\nperformance implications shown in this benchmark? I'd love to\nhear your thoughts on this.\"\n```\n\n## Building Bridges\n\nWe believe in the power of dialogue and reconciliation:\n\n- If someone calls out your behavior, listen and reflect\n- Be willing to apologize if you've caused harm\n- Support others in learning and growth\n- Recognize that people make mistakes\n- Focus on solutions, not blame\n- Assume good intent while holding people accountable\n\n## Benefits of Following This Code\n\nBy maintaining a respectful and inclusive community, we:\n- Attract diverse contributors with varied perspectives\n- Create better solutions through collaboration\n- Build stronger relationships\n- Make the project more welcoming to newcomers\n- Produce higher-quality documentation and examples\n- Foster a culture of learning and growth\n\n## Special Considerations\n\n### For Maintainers\n- Lead by example in adhering to this Code\n- Be responsive to reports\n- Be transparent about decisions\n- Help resolve conflicts fairly\n- Create a safe environment for all\n\n### For Contributors\n- Assume good intent from maintainers and other contributors\n- Provide constructive feedback\n- Support newcomers\n- Help enforce community standards\n- Take ownership of the community culture\n\n### For Everyone\n- Remember there's a human behind every message\n- Take breaks if you're feeling frustrated\n- Reach out to community leaders if you need support\n- Help create the community you want to be part of\n\n## Attribution\n\nThis Code of Conduct is adapted from:\n- The [Contributor Covenant](https://www.contributor-covenant.org/)\n- The [Mozilla Community Participation Guidelines](https://www.mozilla.org/en-US/about/governance/policies/participation/)\n- The [Python Community Code of Conduct](https://www.python.org/psf/conduct/)\n\n## Questions?\n\nIf you have questions about this Code of Conduct, please reach out to the project maintainers.\n\n## Version History\n\n- **Version 1.0** (January 2026) - Initial Code of Conduct\n\n---\n\n**Thank you for helping us create a welcoming, inclusive, and respectful community!** 🌟\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Contributing to Claude How To\n\nThank you for your interest in contributing to this project! This guide will help you understand how to contribute effectively.\n\n## About This Project\n\nClaude How To is a visual, example-driven guide to Claude Code. We provide:\n- **Mermaid diagrams** explaining how features work\n- **Production-ready templates** you can use immediately\n- **Real-world examples** with context and best practices\n- **Progressive learning paths** from beginner to advanced\n\n## Types of Contributions\n\n### 1. New Examples or Templates\nAdd examples for existing features (slash commands, skills, hooks, etc.):\n- Copy-paste ready code\n- Clear explanations of how it works\n- Use cases and benefits\n- Troubleshooting tips\n\n### 2. Documentation Improvements\n- Clarify confusing sections\n- Fix typos and grammar\n- Add missing information\n- Improve code examples\n\n### 3. Feature Guides\nCreate guides for new Claude Code features:\n- Step-by-step tutorials\n- Architecture diagrams\n- Common patterns and anti-patterns\n- Real-world workflows\n\n### 4. Bug Reports\nReport issues you encounter:\n- Describe what you expected\n- Describe what actually happened\n- Include steps to reproduce\n- Add relevant Claude Code version and OS\n\n### 5. Feedback and Suggestions\nHelp improve the guide:\n- Suggest better explanations\n- Point out gaps in coverage\n- Recommend new sections or reorganization\n\n## Getting Started\n\n### 1. Fork and Clone\n```bash\ngit clone https://github.com/luongnv89/claude-howto.git\ncd claude-howto\n```\n\n### 2. Create a Branch\nUse a descriptive branch name:\n```bash\ngit checkout -b add/feature-name\ngit checkout -b fix/issue-description\ngit checkout -b docs/improvement-area\n```\n\n### 3. Set Up Your Environment\n```bash\n# Create virtual environment\npython3 -m venv .venv\nsource .venv/bin/activate\n\n# Install pre-commit hooks (optional but recommended)\npip install pre-commit\npre-commit install\n\n# Run pre-commit checks manually\npre-commit run --all-files\n```\n\n## Directory Structure\n\n```\n├── 01-slash-commands/      # User-invoked shortcuts\n├── 02-memory/              # Persistent context examples\n├── 03-skills/              # Reusable capabilities\n├── 04-subagents/           # Specialized AI assistants\n├── 05-mcp/                 # Model Context Protocol examples\n├── 06-hooks/               # Event-driven automation\n├── 07-plugins/             # Bundled features\n├── 08-checkpoints/         # Session snapshots\n├── 09-advanced-features/   # Planning, thinking, backgrounds\n├── 10-cli/                 # CLI reference\n├── scripts/                # Build and utility scripts\n└── README.md               # Main guide\n```\n\n## How to Contribute Examples\n\n### Adding a Slash Command\n1. Create a `.md` file in `01-slash-commands/`\n2. Include:\n   - Clear description of what it does\n   - Use cases\n   - Installation instructions\n   - Usage examples\n   - Customization tips\n3. Update `01-slash-commands/README.md`\n\n### Adding a Skill\n1. Create a directory in `03-skills/`\n2. Include:\n   - `SKILL.md` - Main documentation\n   - `scripts/` - Helper scripts if needed\n   - `templates/` - Prompt templates\n   - Example usage in README\n3. Update `03-skills/README.md`\n\n### Adding a Subagent\n1. Create a `.md` file in `04-subagents/`\n2. Include:\n   - Agent purpose and capabilities\n   - System prompt structure\n   - Example use cases\n   - Integration examples\n3. Update `04-subagents/README.md`\n\n### Adding MCP Configuration\n1. Create a `.json` file in `05-mcp/`\n2. Include:\n   - Configuration explanation\n   - Required environment variables\n   - Setup instructions\n   - Usage examples\n3. Update `05-mcp/README.md`\n\n### Adding a Hook\n1. Create a `.sh` file in `06-hooks/`\n2. Include:\n   - Shebang and description\n   - Clear comments explaining logic\n   - Error handling\n   - Security considerations\n3. Update `06-hooks/README.md`\n\n## Writing Guidelines\n\n### Markdown Style\n- Use clear headings (H2 for sections, H3 for subsections)\n- Keep paragraphs short and focused\n- Use bullet points for lists\n- Include code blocks with language specification\n- Add blank lines between sections\n\n### Code Examples\n- Make examples copy-paste ready\n- Comment non-obvious logic\n- Include both simple and advanced versions\n- Show real-world use cases\n- Highlight potential issues\n\n### Documentation\n- Explain the \"why\" not just the \"what\"\n- Include prerequisites\n- Add troubleshooting sections\n- Link to related topics\n- Keep it beginner-friendly\n\n### JSON/YAML\n- Use proper indentation (2 or 4 spaces consistently)\n- Add comments explaining configuration\n- Include validation examples\n\n### Diagrams\n- Use Mermaid when possible\n- Keep diagrams simple and readable\n- Include descriptions below diagrams\n- Link to relevant sections\n\n## Commit Guidelines\n\nFollow conventional commit format:\n```\ntype(scope): description\n\n[optional body]\n```\n\nTypes:\n- `feat`: New feature or example\n- `fix`: Bug fix or correction\n- `docs`: Documentation changes\n- `refactor`: Code restructuring\n- `style`: Formatting changes\n- `test`: Test additions or changes\n- `chore`: Build, dependencies, etc.\n\nExamples:\n```\nfeat(slash-commands): Add API documentation generator\ndocs(memory): Improve personal preferences example\nfix(README): Correct table of contents link\ndocs(skills): Add comprehensive code review skill\n```\n\n## Before Submitting\n\n### Checklist\n- [ ] Code follows project style and conventions\n- [ ] New examples include clear documentation\n- [ ] README files are updated (both local and root)\n- [ ] No sensitive information (API keys, credentials)\n- [ ] Examples are tested and working\n- [ ] Links are verified and correct\n- [ ] Files have proper permissions (scripts are executable)\n- [ ] Commit message is clear and descriptive\n\n### Local Testing\n```bash\n# Check file formatting\npre-commit run --all-files\n\n# Verify links work (if applicable)\n# Test examples manually with Claude Code\n\n# Review your changes\ngit diff\n\n# Test the EPUB generation (if docs changed)\nuv run scripts/build_epub.py\n```\n\n## Pull Request Process\n\n1. **Create PR with clear description**:\n   - What does this add/fix?\n   - Why is it needed?\n   - Related issues (if any)\n\n2. **Include relevant details**:\n   - New feature? Include use cases\n   - Documentation? Explain improvements\n   - Examples? Show before/after\n\n3. **Link to issues**:\n   - Use `Closes #123` to auto-close related issues\n\n4. **Be patient with reviews**:\n   - Maintainers may suggest improvements\n   - Iterate based on feedback\n   - Final decision rests with maintainers\n\n## Code Review Process\n\nReviewers will check:\n- **Accuracy**: Does it work as described?\n- **Quality**: Is it production-ready?\n- **Consistency**: Does it follow project patterns?\n- **Documentation**: Is it clear and complete?\n- **Security**: Are there any vulnerabilities?\n\n## Reporting Issues\n\n### Bug Reports\nInclude:\n- Claude Code version\n- Operating system\n- Steps to reproduce\n- Expected behavior\n- Actual behavior\n- Screenshots if applicable\n\n### Feature Requests\nInclude:\n- Use case or problem being solved\n- Proposed solution\n- Alternatives you've considered\n- Additional context\n\n### Documentation Issues\nInclude:\n- What's confusing or missing\n- Suggested improvements\n- Examples or references\n\n## Project Policies\n\n### Sensitive Information\n- Never commit API keys, tokens, or credentials\n- Use placeholder values in examples\n- Include `.env.example` for configuration files\n- Document required environment variables\n\n### Code Quality\n- Keep examples focused and readable\n- Avoid over-engineering solutions\n- Include comments for non-obvious logic\n- Test thoroughly before submitting\n\n### Intellectual Property\n- Original content owned by author\n- Project uses educational license\n- Respect existing copyrights\n- Provide attribution where needed\n\n## Getting Help\n\n- **Questions**: Open a discussion in GitHub Issues\n- **General Help**: Check existing documentation\n- **Development Help**: Review similar examples\n- **Code Review**: Tag maintainers in PRs\n\n## Recognition\n\nContributors are recognized in:\n- README.md Contributors section\n- GitHub contributors page\n- Commit history\n\n## Security\n\nWhen contributing examples and documentation, please follow secure coding practices:\n\n- **Never hardcode secrets or API keys** - Use environment variables\n- **Warn about security implications** - Highlight potential risks\n- **Use secure defaults** - Enable security features by default\n- **Validate inputs** - Show proper input validation and sanitization\n- **Include security notes** - Document security considerations\n\nFor security issues, see [SECURITY.md](SECURITY.md) for our vulnerability reporting process.\n\n## Code of Conduct\n\nWe are committed to providing a welcoming and inclusive community. Please read [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for our full community standards.\n\nIn brief:\n- Be respectful and inclusive\n- Welcome feedback gracefully\n- Help others learn and grow\n- Avoid harassment or discrimination\n- Report issues to maintainers\n\nAll contributors are expected to uphold this code and treat each other with kindness and respect.\n\n## License\n\nBy contributing to this project, you agree that your contributions will be licensed under the MIT License. See [LICENSE](LICENSE) file for details.\n\n## Questions?\n\n- Check the [README](README.md)\n- Review [LEARNING-ROADMAP.md](LEARNING-ROADMAP.md)\n- Look at existing examples\n- Open an issue for discussion\n\nThank you for contributing! 🙏\n"
  },
  {
    "path": "INDEX.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Claude Code Examples - Complete Index\n\nThis document provides a complete index of all example files organized by feature type.\n\n## Summary Statistics\n\n- **Total Files**: 100+ files\n- **Categories**: 10 feature categories\n- **Plugins**: 3 complete plugins\n- **Skills**: 6 complete skills\n- **Hooks**: 8 example hooks\n- **Ready to Use**: All examples\n\n---\n\n## 01. Slash Commands (10 files)\n\nUser-invoked shortcuts for common workflows.\n\n| File | Description | Use Case |\n|------|-------------|----------|\n| `optimize.md` | Code optimization analyzer | Find performance issues |\n| `pr.md` | Pull request preparation | PR workflow automation |\n| `generate-api-docs.md` | API documentation generator | Generate API docs |\n| `commit.md` | Commit message helper | Standardized commits |\n| `setup-ci-cd.md` | CI/CD pipeline setup | DevOps automation |\n| `push-all.md` | Push all changes | Quick push workflow |\n| `unit-test-expand.md` | Expand unit test coverage | Test automation |\n| `doc-refactor.md` | Documentation refactoring | Doc improvements |\n| `pr-slash-command.png` | Screenshot example | Visual reference |\n| `README.md` | Documentation | Setup and usage guide |\n\n**Installation Path**: `.claude/commands/`\n\n**Usage**: `/optimize`, `/pr`, `/generate-api-docs`, `/commit`, `/setup-ci-cd`, `/push-all`, `/unit-test-expand`, `/doc-refactor`\n\n---\n\n## 02. Memory (6 files)\n\nPersistent context and project standards.\n\n| File | Description | Scope | Location |\n|------|-------------|-------|----------|\n| `project-CLAUDE.md` | Team project standards | Project-wide | `./CLAUDE.md` |\n| `directory-api-CLAUDE.md` | API-specific rules | Directory | `./src/api/CLAUDE.md` |\n| `personal-CLAUDE.md` | Personal preferences | User | `~/.claude/CLAUDE.md` |\n| `memory-saved.png` | Screenshot: memory saved | - | Visual reference |\n| `memory-ask-claude.png` | Screenshot: ask Claude | - | Visual reference |\n| `README.md` | Documentation | - | Reference |\n\n**Installation**: Copy to appropriate location\n\n**Usage**: Automatically loaded by Claude\n\n---\n\n## 03. Skills (28 files)\n\nAuto-invoked capabilities with scripts and templates.\n\n### Code Review Skill (5 files)\n```\ncode-review/\n├── SKILL.md                          # Skill definition\n├── scripts/\n│   ├── analyze-metrics.py            # Code metrics analyzer\n│   └── compare-complexity.py         # Complexity comparison\n└── templates/\n    ├── review-checklist.md           # Review checklist\n    └── finding-template.md           # Finding documentation\n```\n\n**Purpose**: Comprehensive code review with security, performance, and quality analysis\n\n**Auto-invoked**: When reviewing code\n\n---\n\n### Brand Voice Skill (4 files)\n```\nbrand-voice/\n├── SKILL.md                          # Skill definition\n├── templates/\n│   ├── email-template.txt            # Email format\n│   └── social-post-template.txt      # Social media format\n└── tone-examples.md                  # Example messages\n```\n\n**Purpose**: Ensure consistent brand voice in communications\n\n**Auto-invoked**: When creating marketing copy\n\n---\n\n### Documentation Generator Skill (2 files)\n```\ndoc-generator/\n├── SKILL.md                          # Skill definition\n└── generate-docs.py                  # Python doc extractor\n```\n\n**Purpose**: Generate comprehensive API documentation from source code\n\n**Auto-invoked**: When creating/updating API documentation\n\n---\n\n### Refactor Skill (5 files)\n```\nrefactor/\n├── SKILL.md                          # Skill definition\n├── scripts/\n│   ├── analyze-complexity.py         # Complexity analyzer\n│   └── detect-smells.py              # Code smell detector\n├── references/\n│   ├── code-smells.md                # Code smells catalog\n│   └── refactoring-catalog.md        # Refactoring patterns\n└── templates/\n    └── refactoring-plan.md           # Refactoring plan template\n```\n\n**Purpose**: Systematic code refactoring with complexity analysis\n\n**Auto-invoked**: When refactoring code\n\n---\n\n### Claude MD Skill (1 file)\n```\nclaude-md/\n└── SKILL.md                          # Skill definition\n```\n\n**Purpose**: Manage and optimize CLAUDE.md files\n\n---\n\n### Blog Draft Skill (3 files)\n```\nblog-draft/\n├── SKILL.md                          # Skill definition\n└── templates/\n    ├── draft-template.md             # Blog draft template\n    └── outline-template.md           # Blog outline template\n```\n\n**Purpose**: Draft blog posts with consistent structure\n\n**Plus**: `README.md` - Skills overview and usage guide\n\n**Installation Path**: `~/.claude/skills/` or `.claude/skills/`\n\n---\n\n## 04. Subagents (9 files)\n\nSpecialized AI assistants with custom capabilities.\n\n| File | Description | Tools | Use Case |\n|------|-------------|-------|----------|\n| `code-reviewer.md` | Code quality analysis | read, grep, diff, lint_runner | Comprehensive reviews |\n| `test-engineer.md` | Test coverage analysis | read, write, bash, grep | Test automation |\n| `documentation-writer.md` | Documentation creation | read, write, grep | Doc generation |\n| `secure-reviewer.md` | Security review (read-only) | read, grep | Security audits |\n| `implementation-agent.md` | Full implementation | read, write, bash, grep, edit, glob | Feature development |\n| `debugger.md` | Debugging specialist | read, bash, grep | Bug investigation |\n| `data-scientist.md` | Data analysis specialist | read, write, bash | Data workflows |\n| `clean-code-reviewer.md` | Clean code standards | read, grep | Code quality |\n| `README.md` | Documentation | - | Setup and usage guide |\n\n**Installation Path**: `.claude/agents/`\n\n**Usage**: Automatically delegated by main agent\n\n---\n\n## 05. MCP Protocol (5 files)\n\nExternal tool and API integrations.\n\n| File | Description | Integrates With | Use Case |\n|------|-------------|-----------------|----------|\n| `github-mcp.json` | GitHub integration | GitHub API | PR/issue management |\n| `database-mcp.json` | Database queries | PostgreSQL/MySQL | Live data queries |\n| `filesystem-mcp.json` | File operations | Local filesystem | File management |\n| `multi-mcp.json` | Multiple servers | GitHub + DB + Slack | Complete integration |\n| `README.md` | Documentation | - | Setup and usage guide |\n\n**Installation Path**: `.mcp.json` (project scope) or `~/.claude.json` (user scope)\n\n**Usage**: `/mcp__github__list_prs`, etc.\n\n---\n\n## 06. Hooks (9 files)\n\nEvent-driven automation scripts that execute automatically.\n\n| File | Description | Event | Use Case |\n|------|-------------|-------|----------|\n| `format-code.sh` | Auto-format code | PreToolUse:Write | Code formatting |\n| `pre-commit.sh` | Run tests before commit | PreToolUse:Bash | Test automation |\n| `security-scan.sh` | Security scanning | PostToolUse:Write | Security checks |\n| `log-bash.sh` | Log bash commands | PostToolUse:Bash | Command logging |\n| `validate-prompt.sh` | Validate prompts | PreToolUse | Input validation |\n| `notify-team.sh` | Send notifications | Notification | Team notifications |\n| `context-tracker.py` | Track context window usage | PostToolUse | Context monitoring |\n| `context-tracker-tiktoken.py` | Token-based context tracking | PostToolUse | Precise token counting |\n| `README.md` | Documentation | - | Setup and usage guide |\n\n**Installation Path**: Configure in `~/.claude/settings.json`\n\n**Usage**: Configured in settings, executed automatically\n\n**Hook Types** (4 types, 25 events):\n- Tool Hooks: PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest\n- Session Hooks: SessionStart, SessionEnd, Stop, StopFailure, SubagentStart, SubagentStop\n- Task Hooks: UserPromptSubmit, TaskCompleted, TaskCreated, TeammateIdle\n- Lifecycle Hooks: ConfigChange, CwdChanged, FileChanged, PreCompact, PostCompact, WorktreeCreate, WorktreeRemove, Notification, InstructionsLoaded, Elicitation, ElicitationResult\n\n---\n\n## 07. Plugins (3 complete plugins, 40 files)\n\nBundled collections of features.\n\n### PR Review Plugin (10 files)\n```\npr-review/\n├── .claude-plugin/\n│   └── plugin.json                   # Plugin manifest\n├── commands/\n│   ├── review-pr.md                  # Comprehensive review\n│   ├── check-security.md             # Security check\n│   └── check-tests.md                # Test coverage check\n├── agents/\n│   ├── security-reviewer.md          # Security specialist\n│   ├── test-checker.md               # Test specialist\n│   └── performance-analyzer.md       # Performance specialist\n├── mcp/\n│   └── github-config.json            # GitHub integration\n├── hooks/\n│   └── pre-review.js                 # Pre-review validation\n└── README.md                         # Plugin documentation\n```\n\n**Features**: Security analysis, test coverage, performance impact\n\n**Commands**: `/review-pr`, `/check-security`, `/check-tests`\n\n**Installation**: `/plugin install pr-review`\n\n---\n\n### DevOps Automation Plugin (15 files)\n```\ndevops-automation/\n├── .claude-plugin/\n│   └── plugin.json                   # Plugin manifest\n├── commands/\n│   ├── deploy.md                     # Deployment\n│   ├── rollback.md                   # Rollback\n│   ├── status.md                     # System status\n│   └── incident.md                   # Incident response\n├── agents/\n│   ├── deployment-specialist.md      # Deployment expert\n│   ├── incident-commander.md         # Incident coordinator\n│   └── alert-analyzer.md             # Alert analyzer\n├── mcp/\n│   └── kubernetes-config.json        # Kubernetes integration\n├── hooks/\n│   ├── pre-deploy.js                 # Pre-deployment checks\n│   └── post-deploy.js                # Post-deployment tasks\n├── scripts/\n│   ├── deploy.sh                     # Deployment automation\n│   ├── rollback.sh                   # Rollback automation\n│   └── health-check.sh               # Health checks\n└── README.md                         # Plugin documentation\n```\n\n**Features**: Kubernetes deployment, rollback, monitoring, incident response\n\n**Commands**: `/deploy`, `/rollback`, `/status`, `/incident`\n\n**Installation**: `/plugin install devops-automation`\n\n---\n\n### Documentation Plugin (14 files)\n```\ndocumentation/\n├── .claude-plugin/\n│   └── plugin.json                   # Plugin manifest\n├── commands/\n│   ├── generate-api-docs.md          # API docs generation\n│   ├── generate-readme.md            # README creation\n│   ├── sync-docs.md                  # Doc synchronization\n│   └── validate-docs.md              # Doc validation\n├── agents/\n│   ├── api-documenter.md             # API doc specialist\n│   ├── code-commentator.md           # Code comment specialist\n│   └── example-generator.md          # Example creator\n├── mcp/\n│   └── github-docs-config.json       # GitHub integration\n├── templates/\n│   ├── api-endpoint.md               # API endpoint template\n│   ├── function-docs.md              # Function doc template\n│   └── adr-template.md               # ADR template\n└── README.md                         # Plugin documentation\n```\n\n**Features**: API docs, README generation, doc sync, validation\n\n**Commands**: `/generate-api-docs`, `/generate-readme`, `/sync-docs`, `/validate-docs`\n\n**Installation**: `/plugin install documentation`\n\n**Plus**: `README.md` - Plugins overview and usage guide\n\n---\n\n## 08. Checkpoints and Rewind (2 files)\n\nSave conversation state and explore alternative approaches.\n\n| File | Description | Content |\n|------|-------------|---------|\n| `README.md` | Documentation | Comprehensive checkpoint guide |\n| `checkpoint-examples.md` | Real-world examples | Database migration, performance optimization, UI iteration, debugging |\n| | | |\n\n**Key Concepts**:\n- **Checkpoint**: Snapshot of conversation state\n- **Rewind**: Return to previous checkpoint\n- **Branch Point**: Explore multiple approaches\n\n**Usage**:\n```\n# Checkpoints are created automatically with every user prompt\n# To rewind, press Esc twice or use:\n/rewind\n# Then choose: Restore code and conversation, Restore conversation,\n# Restore code, Summarize from here, or Never mind\n```\n\n**Use Cases**:\n- Try different implementations\n- Recover from mistakes\n- Safe experimentation\n- Compare solutions\n- A/B testing\n\n---\n\n## 09. Advanced Features (3 files)\n\nAdvanced capabilities for complex workflows.\n\n| File | Description | Features |\n|------|-------------|----------|\n| `README.md` | Complete guide | All advanced features documentation |\n| `config-examples.json` | Configuration examples | 10+ use-case-specific configurations |\n| `planning-mode-examples.md` | Planning examples | REST API, database migration, refactoring |\n| Scheduled Tasks | Recurring tasks with `/loop` and cron tools | Automated recurring workflows |\n| Chrome Integration | Browser automation via headless Chromium | Web testing and scraping |\n| Remote Control (expanded) | Connection methods, security, comparison table | Remote session management |\n| Keyboard Customization | Custom keybindings, chord support, contexts | Personalized shortcuts |\n| Desktop App (expanded) | Connectors, launch.json, enterprise features | Desktop integration |\n| | | |\n\n**Advanced Features Covered**:\n\n### Planning Mode\n- Create detailed implementation plans\n- Time estimates and risk assessment\n- Systematic task breakdown\n\n### Extended Thinking\n- Deep reasoning for complex problems\n- Architectural decision analysis\n- Trade-off evaluation\n\n### Background Tasks\n- Long-running operations without blocking\n- Parallel development workflows\n- Task management and monitoring\n\n### Permission Modes\n- **default**: Ask for approval on risky actions\n- **acceptEdits**: Auto-accept file edits, ask for others\n- **plan**: Read-only analysis, no modifications\n- **auto**: Automatically approve safe actions, prompt for risky ones\n- **dontAsk**: Accept all actions except risky ones\n- **bypassPermissions**: Accept all (requires `--dangerously-skip-permissions`)\n\n### Headless Mode (`claude -p`)\n- CI/CD integration\n- Automated task execution\n- Batch processing\n\n### Session Management\n- Multiple work sessions\n- Session switching and saving\n- Session persistence\n\n### Interactive Features\n- Keyboard shortcuts\n- Command history\n- Tab completion\n- Multi-line input\n\n### Configuration\n- Comprehensive settings management\n- Environment-specific configs\n- Per-project customization\n\n### Scheduled Tasks\n- Recurring tasks with `/loop` command\n- Cron tools: CronCreate, CronList, CronDelete\n- Automated recurring workflows\n\n### Chrome Integration\n- Browser automation via headless Chromium\n- Web testing and scraping capabilities\n- Page interaction and data extraction\n\n### Remote Control (expanded)\n- Connection methods and protocols\n- Security considerations and best practices\n- Comparison table of remote access options\n\n### Keyboard Customization\n- Custom keybindings configuration\n- Chord support for multi-key shortcuts\n- Context-aware keybinding activation\n\n### Desktop App (expanded)\n- Connectors for IDE integration\n- launch.json configuration\n- Enterprise features and deployment\n\n---\n\n## 10. CLI Usage (1 file)\n\nCommand-line interface usage patterns and reference.\n\n| File | Description | Content |\n|------|-------------|---------|\n| `README.md` | CLI documentation | Flags, options, and usage patterns |\n\n**Key CLI Features**:\n- `claude` - Start interactive session\n- `claude -p \"prompt\"` - Headless/non-interactive mode\n- `claude web` - Launch web session\n- `claude --model` - Select model (Sonnet 4.6, Opus 4.6)\n- `claude --permission-mode` - Set permission mode\n- `claude --remote` - Enable remote control via WebSocket\n\n---\n\n## Documentation Files (13 files)\n\n| File | Location | Description |\n|------|----------|-------------|\n| `README.md` | `/` | Main examples overview |\n| `INDEX.md` | `/` | This complete index |\n| `QUICK_REFERENCE.md` | `/` | Quick reference card |\n| `README.md` | `/01-slash-commands/` | Slash commands guide |\n| `README.md` | `/02-memory/` | Memory guide |\n| `README.md` | `/03-skills/` | Skills guide |\n| `README.md` | `/04-subagents/` | Subagents guide |\n| `README.md` | `/05-mcp/` | MCP guide |\n| `README.md` | `/06-hooks/` | Hooks guide |\n| `README.md` | `/07-plugins/` | Plugins guide |\n| `README.md` | `/08-checkpoints/` | Checkpoints guide |\n| `README.md` | `/09-advanced-features/` | Advanced features guide |\n| `README.md` | `/10-cli/` | CLI guide |\n\n---\n\n## Complete File Tree\n\n```\nclaude-howto/\n├── README.md                                    # Main overview\n├── INDEX.md                                     # This file\n├── QUICK_REFERENCE.md                           # Quick reference card\n├── claude_concepts_guide.md                     # Original guide\n│\n├── 01-slash-commands/                           # Slash Commands\n│   ├── optimize.md\n│   ├── pr.md\n│   ├── generate-api-docs.md\n│   ├── commit.md\n│   ├── setup-ci-cd.md\n│   ├── push-all.md\n│   ├── unit-test-expand.md\n│   ├── doc-refactor.md\n│   ├── pr-slash-command.png\n│   └── README.md\n│\n├── 02-memory/                                   # Memory\n│   ├── project-CLAUDE.md\n│   ├── directory-api-CLAUDE.md\n│   ├── personal-CLAUDE.md\n│   ├── memory-saved.png\n│   ├── memory-ask-claude.png\n│   └── README.md\n│\n├── 03-skills/                                   # Skills\n│   ├── code-review/\n│   │   ├── SKILL.md\n│   │   ├── scripts/\n│   │   │   ├── analyze-metrics.py\n│   │   │   └── compare-complexity.py\n│   │   └── templates/\n│   │       ├── review-checklist.md\n│   │       └── finding-template.md\n│   ├── brand-voice/\n│   │   ├── SKILL.md\n│   │   ├── templates/\n│   │   │   ├── email-template.txt\n│   │   │   └── social-post-template.txt\n│   │   └── tone-examples.md\n│   ├── doc-generator/\n│   │   ├── SKILL.md\n│   │   └── generate-docs.py\n│   ├── refactor/\n│   │   ├── SKILL.md\n│   │   ├── scripts/\n│   │   │   ├── analyze-complexity.py\n│   │   │   └── detect-smells.py\n│   │   ├── references/\n│   │   │   ├── code-smells.md\n│   │   │   └── refactoring-catalog.md\n│   │   └── templates/\n│   │       └── refactoring-plan.md\n│   ├── claude-md/\n│   │   └── SKILL.md\n│   ├── blog-draft/\n│   │   ├── SKILL.md\n│   │   └── templates/\n│   │       ├── draft-template.md\n│   │       └── outline-template.md\n│   └── README.md\n│\n├── 04-subagents/                                # Subagents\n│   ├── code-reviewer.md\n│   ├── test-engineer.md\n│   ├── documentation-writer.md\n│   ├── secure-reviewer.md\n│   ├── implementation-agent.md\n│   ├── debugger.md\n│   ├── data-scientist.md\n│   ├── clean-code-reviewer.md\n│   └── README.md\n│\n├── 05-mcp/                                      # MCP Protocol\n│   ├── github-mcp.json\n│   ├── database-mcp.json\n│   ├── filesystem-mcp.json\n│   ├── multi-mcp.json\n│   └── README.md\n│\n├── 06-hooks/                                    # Hooks\n│   ├── format-code.sh\n│   ├── pre-commit.sh\n│   ├── security-scan.sh\n│   ├── log-bash.sh\n│   ├── validate-prompt.sh\n│   ├── notify-team.sh\n│   ├── context-tracker.py\n│   ├── context-tracker-tiktoken.py\n│   └── README.md\n│\n├── 07-plugins/                                  # Plugins\n│   ├── pr-review/\n│   │   ├── .claude-plugin/\n│   │   │   └── plugin.json\n│   │   ├── commands/\n│   │   │   ├── review-pr.md\n│   │   │   ├── check-security.md\n│   │   │   └── check-tests.md\n│   │   ├── agents/\n│   │   │   ├── security-reviewer.md\n│   │   │   ├── test-checker.md\n│   │   │   └── performance-analyzer.md\n│   │   ├── mcp/\n│   │   │   └── github-config.json\n│   │   ├── hooks/\n│   │   │   └── pre-review.js\n│   │   └── README.md\n│   ├── devops-automation/\n│   │   ├── .claude-plugin/\n│   │   │   └── plugin.json\n│   │   ├── commands/\n│   │   │   ├── deploy.md\n│   │   │   ├── rollback.md\n│   │   │   ├── status.md\n│   │   │   └── incident.md\n│   │   ├── agents/\n│   │   │   ├── deployment-specialist.md\n│   │   │   ├── incident-commander.md\n│   │   │   └── alert-analyzer.md\n│   │   ├── mcp/\n│   │   │   └── kubernetes-config.json\n│   │   ├── hooks/\n│   │   │   ├── pre-deploy.js\n│   │   │   └── post-deploy.js\n│   │   ├── scripts/\n│   │   │   ├── deploy.sh\n│   │   │   ├── rollback.sh\n│   │   │   └── health-check.sh\n│   │   └── README.md\n│   ├── documentation/\n│   │   ├── .claude-plugin/\n│   │   │   └── plugin.json\n│   │   ├── commands/\n│   │   │   ├── generate-api-docs.md\n│   │   │   ├── generate-readme.md\n│   │   │   ├── sync-docs.md\n│   │   │   └── validate-docs.md\n│   │   ├── agents/\n│   │   │   ├── api-documenter.md\n│   │   │   ├── code-commentator.md\n│   │   │   └── example-generator.md\n│   │   ├── mcp/\n│   │   │   └── github-docs-config.json\n│   │   ├── templates/\n│   │   │   ├── api-endpoint.md\n│   │   │   ├── function-docs.md\n│   │   │   └── adr-template.md\n│   │   └── README.md\n│   └── README.md\n│\n├── 08-checkpoints/                              # Checkpoints\n│   ├── checkpoint-examples.md\n│   └── README.md\n│\n├── 09-advanced-features/                        # Advanced Features\n│   ├── config-examples.json\n│   ├── planning-mode-examples.md\n│   └── README.md\n│\n└── 10-cli/                                      # CLI Usage\n    └── README.md\n```\n\n---\n\n## Quick Start by Use Case\n\n### Code Quality & Reviews\n```bash\n# Install slash command\ncp 01-slash-commands/optimize.md .claude/commands/\n\n# Install subagent\ncp 04-subagents/code-reviewer.md .claude/agents/\n\n# Install skill\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Or install complete plugin\n/plugin install pr-review\n```\n\n### DevOps & Deployment\n```bash\n# Install plugin (includes everything)\n/plugin install devops-automation\n```\n\n### Documentation\n```bash\n# Install slash command\ncp 01-slash-commands/generate-api-docs.md .claude/commands/\n\n# Install subagent\ncp 04-subagents/documentation-writer.md .claude/agents/\n\n# Install skill\ncp -r 03-skills/doc-generator ~/.claude/skills/\n\n# Or install complete plugin\n/plugin install documentation\n```\n\n### Team Standards\n```bash\n# Set up project memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Edit to match your team's standards\n```\n\n### External Integrations\n```bash\n# Set environment variables\nexport GITHUB_TOKEN=\"your_token\"\nexport DATABASE_URL=\"postgresql://...\"\n\n# Install MCP config (project scope)\ncp 05-mcp/multi-mcp.json .mcp.json\n```\n\n### Automation & Validation\n```bash\n# Install hooks\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n\n# Configure hooks in settings (~/.claude/settings.json)\n# See 06-hooks/README.md\n```\n\n### Safe Experimentation\n```bash\n# Checkpoints are created automatically with every user prompt\n# To rewind: press Esc+Esc or use /rewind\n# Then choose what to restore from the rewind menu\n\n# See 08-checkpoints/README.md for examples\n```\n\n### Advanced Workflows\n```bash\n# Configure advanced features\n# See 09-advanced-features/config-examples.json\n\n# Use planning mode\n/plan Implement feature X\n\n# Use permission modes\nclaude --permission-mode plan          # For code review (read-only)\nclaude --permission-mode acceptEdits   # Auto-accept edits\nclaude --permission-mode auto          # Auto-approve safe actions\n\n# Run in headless mode for CI/CD\nclaude -p \"Run tests and report results\"\n\n# Run background tasks\nRun tests in background\n\n# See 09-advanced-features/README.md for complete guide\n```\n\n---\n\n## Feature Coverage Matrix\n\n| Category | Commands | Agents | MCP | Hooks | Scripts | Templates | Docs | Images | Total |\n|----------|----------|--------|-----|-------|---------|-----------|------|--------|-------|\n| **01 Slash Commands** | 8 | - | - | - | - | - | 1 | 1 | **10** |\n| **02 Memory** | - | - | - | - | - | 3 | 1 | 2 | **6** |\n| **03 Skills** | - | - | - | - | 5 | 9 | 1 | - | **28** |\n| **04 Subagents** | - | 8 | - | - | - | - | 1 | - | **9** |\n| **05 MCP** | - | - | 4 | - | - | - | 1 | - | **5** |\n| **06 Hooks** | - | - | - | 8 | - | - | 1 | - | **9** |\n| **07 Plugins** | 11 | 9 | 3 | 3 | 3 | 3 | 4 | - | **40** |\n| **08 Checkpoints** | - | - | - | - | - | - | 1 | 1 | **2** |\n| **09 Advanced** | - | - | - | - | - | - | 1 | 2 | **3** |\n| **10 CLI** | - | - | - | - | - | - | 1 | - | **1** |\n\n---\n\n## Learning Path\n\n### Beginner (Week 1)\n1. ✅ Read `README.md`\n2. ✅ Install 1-2 slash commands\n3. ✅ Create project memory file\n4. ✅ Try basic commands\n\n### Intermediate (Week 2-3)\n1. ✅ Set up GitHub MCP\n2. ✅ Install a subagent\n3. ✅ Try delegating tasks\n4. ✅ Install a skill\n\n### Advanced (Week 4+)\n1. ✅ Install complete plugin\n2. ✅ Create custom slash commands\n3. ✅ Create custom subagent\n4. ✅ Create custom skill\n5. ✅ Build your own plugin\n\n### Expert (Week 5+)\n1. ✅ Set up hooks for automation\n2. ✅ Use checkpoints for experimentation\n3. ✅ Configure planning mode\n4. ✅ Use permission modes effectively\n5. ✅ Set up headless mode for CI/CD\n6. ✅ Master session management\n\n---\n\n## Search by Keyword\n\n### Performance\n- `01-slash-commands/optimize.md` - Performance analysis\n- `04-subagents/code-reviewer.md` - Performance review\n- `03-skills/code-review/` - Performance metrics\n- `07-plugins/pr-review/agents/performance-analyzer.md` - Performance specialist\n\n### Security\n- `04-subagents/secure-reviewer.md` - Security review\n- `03-skills/code-review/` - Security analysis\n- `07-plugins/pr-review/` - Security checks\n\n### Testing\n- `04-subagents/test-engineer.md` - Test engineer\n- `07-plugins/pr-review/commands/check-tests.md` - Test coverage\n\n### Documentation\n- `01-slash-commands/generate-api-docs.md` - API docs command\n- `04-subagents/documentation-writer.md` - Doc writer agent\n- `03-skills/doc-generator/` - Doc generator skill\n- `07-plugins/documentation/` - Complete doc plugin\n\n### Deployment\n- `07-plugins/devops-automation/` - Complete DevOps solution\n\n### Automation\n- `06-hooks/` - Event-driven automation\n- `06-hooks/pre-commit.sh` - Pre-commit automation\n- `06-hooks/format-code.sh` - Auto-formatting\n- `09-advanced-features/` - Headless mode for CI/CD\n\n### Validation\n- `06-hooks/security-scan.sh` - Security validation\n- `06-hooks/validate-prompt.sh` - Prompt validation\n\n### Experimentation\n- `08-checkpoints/` - Safe experimentation with rewind\n- `08-checkpoints/checkpoint-examples.md` - Real-world examples\n\n### Planning\n- `09-advanced-features/planning-mode-examples.md` - Planning mode examples\n- `09-advanced-features/README.md` - Extended thinking\n\n### Configuration\n- `09-advanced-features/config-examples.json` - Configuration examples\n\n---\n\n## Notes\n\n- All examples are ready to use\n- Modify to fit your specific needs\n- Examples follow Claude Code best practices\n- Each category has its own README with detailed instructions\n- Scripts include proper error handling\n- Templates are customizable\n\n---\n\n## Contributing\n\nWant to add more examples? Follow the structure:\n1. Create appropriate subdirectory\n2. Include README.md with usage\n3. Follow naming conventions\n4. Test thoroughly\n5. Update this index\n\n---\n\n**Last Updated**: March 2026\n**Total Examples**: 100+ files\n**Categories**: 10 features\n**Hooks**: 8 automation scripts\n**Configuration Examples**: 10+ scenarios\n**Ready to Use**: All examples\n"
  },
  {
    "path": "LEARNING-ROADMAP.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# 📚 Claude Code Learning Roadmap\n\n**New to Claude Code?** This guide helps you master Claude Code features at your own pace. Whether you're a complete beginner or an experienced developer, start with the self-assessment quiz below to find the right path for you.\n\n---\n\n## 🧭 Find Your Level\n\nNot everyone starts from the same place. Take this quick self-assessment to find the right entry point.\n\n**Answer these questions honestly:**\n\n- [ ] I can start Claude Code and have a conversation (`claude`)\n- [ ] I have created or edited a CLAUDE.md file\n- [ ] I have used at least 3 built-in slash commands (e.g., /help, /compact, /model)\n- [ ] I have created a custom slash command or skill (SKILL.md)\n- [ ] I have configured an MCP server (e.g., GitHub, database)\n- [ ] I have set up hooks in ~/.claude/settings.json\n- [ ] I have created or used custom subagents (.claude/agents/)\n- [ ] I have used print mode (`claude -p`) for scripting or CI/CD\n\n**Your Level:**\n\n| Checks | Level | Start At | Time to Complete |\n|--------|-------|----------|------------------|\n| 0-2 | **Level 1: Beginner** — Getting Started | [Milestone 1A](#milestone-1a-first-commands--memory) | ~3 hours |\n| 3-5 | **Level 2: Intermediate** — Building Workflows | [Milestone 2A](#milestone-2a-automation-skills--hooks) | ~5 hours |\n| 6-8 | **Level 3: Advanced** — Power User & Team Lead | [Milestone 3A](#milestone-3a-advanced-features) | ~5 hours |\n\n> **Tip**: If you're unsure, start one level lower. It's better to review familiar material quickly than to miss foundational concepts.\n\n> **Interactive version**: Run `/self-assessment` in Claude Code for a guided, interactive quiz that scores your proficiency across all 10 feature areas and generates a personalized learning path.\n\n---\n\n## 🎯 Learning Philosophy\n\nThe folders in this repository are numbered in **recommended learning order** based on three key principles:\n\n1. **Dependencies** - Foundational concepts come first\n2. **Complexity** - Easier features before advanced ones\n3. **Frequency of Use** - Most common features taught early\n\nThis approach ensures you build a solid foundation while gaining immediate productivity benefits.\n\n---\n\n## 🗺️ Your Learning Path\n\n```mermaid\ngraph TD\n    Q[\"🧭 Self-Assessment Quiz<br/>Find Your Level\"] --> L1\n    Q --> L2\n    Q --> L3\n\n    subgraph L1[\"🟢 Level 1: Beginner — Getting Started\"]\n        direction LR\n        A[\"1A: First Commands & Memory<br/>Slash Commands + Memory\"] --> B[\"1B: Safe Exploration<br/>Checkpoints + CLI Basics\"]\n    end\n\n    subgraph L2[\"🔵 Level 2: Intermediate — Building Workflows\"]\n        direction LR\n        C[\"2A: Automation<br/>Skills + Hooks\"] --> D[\"2B: Integration<br/>MCP + Subagents\"]\n    end\n\n    subgraph L3[\"🔴 Level 3: Advanced — Power User\"]\n        direction LR\n        E[\"3A: Advanced Features<br/>Planning + Permissions\"] --> F[\"3B: Team & Distribution<br/>Plugins + CLI Mastery\"]\n    end\n\n    L1 --> L2\n    L2 --> L3\n\n    style Q fill:#6A1B9A,color:#fff,stroke:#9C27B0,stroke-width:2px\n    style A fill:#2E7D32,color:#fff\n    style B fill:#2E7D32,color:#fff\n    style C fill:#1565C0,color:#fff\n    style D fill:#F57C00,color:#fff\n    style E fill:#C62828,color:#fff\n    style F fill:#B71C1C,color:#fff\n```\n\n**Color Legend:**\n- 💜 Purple: Self-Assessment Quiz\n- 🟢 Green: Level 1 — Beginner path\n- 🔵 Blue / 🟡 Gold: Level 2 — Intermediate path\n- 🔴 Red: Level 3 — Advanced path\n\n---\n\n## 📊 Complete Roadmap Table\n\n| Step | Feature | Complexity | Time | Level | Dependencies | Why Learn This | Key Benefits |\n|------|---------|-----------|------|-------|--------------|----------------|--------------|\n| **1** | [Slash Commands](01-slash-commands/) | ⭐ Beginner | 30 min | Level 1 | None | Quick productivity wins (55+ built-in + 5 bundled skills) | Instant automation, team standards |\n| **2** | [Memory](02-memory/) | ⭐⭐ Beginner+ | 45 min | Level 1 | None | Essential for all features | Persistent context, preferences |\n| **3** | [Checkpoints](08-checkpoints/) | ⭐⭐ Intermediate | 45 min | Level 1 | Session management | Safe exploration | Experimentation, recovery |\n| **4** | [CLI Basics](10-cli/) | ⭐⭐ Beginner+ | 30 min | Level 1 | None | Core CLI usage | Interactive & print mode |\n| **5** | [Skills](03-skills/) | ⭐⭐ Intermediate | 1 hour | Level 2 | Slash Commands | Automatic expertise | Reusable capabilities, consistency |\n| **6** | [Hooks](06-hooks/) | ⭐⭐ Intermediate | 1 hour | Level 2 | Tools, Commands | Workflow automation (25 events, 4 types) | Validation, quality gates |\n| **7** | [MCP](05-mcp/) | ⭐⭐⭐ Intermediate+ | 1 hour | Level 2 | Configuration | Live data access | Real-time integration, APIs |\n| **8** | [Subagents](04-subagents/) | ⭐⭐⭐ Intermediate+ | 1.5 hours | Level 2 | Memory, Commands | Complex task handling (6 built-in including Bash) | Delegation, specialized expertise |\n| **9** | [Advanced Features](09-advanced-features/) | ⭐⭐⭐⭐⭐ Advanced | 2-3 hours | Level 3 | All previous | Power user tools | Planning, Auto Mode, Channels, Voice Dictation, permissions |\n| **10** | [Plugins](07-plugins/) | ⭐⭐⭐⭐ Advanced | 2 hours | Level 3 | All previous | Complete solutions | Team onboarding, distribution |\n| **11** | [CLI Mastery](10-cli/) | ⭐⭐⭐ Advanced | 1 hour | Level 3 | Recommended: All | Master command-line usage | Scripting, CI/CD, automation |\n\n**Total Learning Time**: ~11-13 hours (or jump to your level and save time)\n\n---\n\n## 🟢 Level 1: Beginner — Getting Started\n\n**For**: Users with 0-2 quiz checks\n**Time**: ~3 hours\n**Focus**: Immediate productivity, understanding fundamentals\n**Outcome**: Comfortable daily user, ready for Level 2\n\n### Milestone 1A: First Commands & Memory\n\n**Topics**: Slash Commands + Memory\n**Time**: 1-2 hours\n**Complexity**: ⭐ Beginner\n**Goal**: Immediate productivity boost with custom commands and persistent context\n\n#### What You'll Achieve\n✅ Create custom slash commands for repetitive tasks\n✅ Set up project memory for team standards\n✅ Configure personal preferences\n✅ Understand how Claude loads context automatically\n\n#### Hands-on Exercises\n\n```bash\n# Exercise 1: Install your first slash command\nmkdir -p .claude/commands\ncp 01-slash-commands/optimize.md .claude/commands/\n\n# Exercise 2: Create project memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Exercise 3: Try it out\n# In Claude Code, type: /optimize\n```\n\n#### Success Criteria\n- [ ] Successfully invoke `/optimize` command\n- [ ] Claude remembers your project standards from CLAUDE.md\n- [ ] You understand when to use slash commands vs. memory\n\n#### Next Steps\nOnce comfortable, read:\n- [01-slash-commands/README.md](01-slash-commands/README.md)\n- [02-memory/README.md](02-memory/README.md)\n\n> **Check your understanding**: Run `/lesson-quiz slash-commands` or `/lesson-quiz memory` in Claude Code to test what you've learned.\n\n---\n\n### Milestone 1B: Safe Exploration\n\n**Topics**: Checkpoints + CLI Basics\n**Time**: 1 hour\n**Complexity**: ⭐⭐ Beginner+\n**Goal**: Learn to experiment safely and use core CLI commands\n\n#### What You'll Achieve\n✅ Create and restore checkpoints for safe experimentation\n✅ Understand interactive vs. print mode\n✅ Use basic CLI flags and options\n✅ Process files via piping\n\n#### Hands-on Exercises\n\n```bash\n# Exercise 1: Try checkpoint workflow\n# In Claude Code:\n# Make some experimental changes, then press Esc+Esc or use /rewind\n# Select the checkpoint before your experiment\n# Choose \"Restore code and conversation\" to go back\n\n# Exercise 2: Interactive vs Print mode\nclaude \"explain this project\"           # Interactive mode\nclaude -p \"explain this function\"       # Print mode (non-interactive)\n\n# Exercise 3: Process file content via piping\ncat error.log | claude -p \"explain this error\"\n```\n\n#### Success Criteria\n- [ ] Created and reverted to a checkpoint\n- [ ] Used both interactive and print mode\n- [ ] Piped a file to Claude for analysis\n- [ ] Understand when to use checkpoints for safe experimentation\n\n#### Next Steps\n- Read: [08-checkpoints/README.md](08-checkpoints/README.md)\n- Read: [10-cli/README.md](10-cli/README.md)\n- **Ready for Level 2!** Proceed to [Milestone 2A](#milestone-2a-automation-skills--hooks)\n\n> **Check your understanding**: Run `/lesson-quiz checkpoints` or `/lesson-quiz cli` to verify you're ready for Level 2.\n\n---\n\n## 🔵 Level 2: Intermediate — Building Workflows\n\n**For**: Users with 3-5 quiz checks\n**Time**: ~5 hours\n**Focus**: Automation, integration, task delegation\n**Outcome**: Automated workflows, external integrations, ready for Level 3\n\n### Prerequisites Check\n\nBefore starting Level 2, make sure you're comfortable with these Level 1 concepts:\n\n- [ ] Can create and use slash commands ([01-slash-commands/](01-slash-commands/))\n- [ ] Have set up project memory via CLAUDE.md ([02-memory/](02-memory/))\n- [ ] Know how to create and restore checkpoints ([08-checkpoints/](08-checkpoints/))\n- [ ] Can use `claude` and `claude -p` from the command line ([10-cli/](10-cli/))\n\n> **Gaps?** Review the linked tutorials above before continuing.\n\n---\n\n### Milestone 2A: Automation (Skills + Hooks)\n\n**Topics**: Skills + Hooks\n**Time**: 2-3 hours\n**Complexity**: ⭐⭐ Intermediate\n**Goal**: Automate common workflows and quality checks\n\n#### What You'll Achieve\n✅ Auto-invoke specialized capabilities with YAML frontmatter (including `effort` and `shell` fields)\n✅ Set up event-driven automation across 25 hook events\n✅ Use all 4 hook types (command, http, prompt, agent)\n✅ Enforce code quality standards\n✅ Create custom hooks for your workflow\n\n#### Hands-on Exercises\n\n```bash\n# Exercise 1: Install a skill\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Exercise 2: Set up hooks\nmkdir -p ~/.claude/hooks\ncp 06-hooks/pre-tool-check.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/pre-tool-check.sh\n\n# Exercise 3: Configure hooks in settings\n# Add to ~/.claude/settings.json:\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"~/.claude/hooks/pre-tool-check.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n#### Success Criteria\n- [ ] Code review skill automatically invoked when relevant\n- [ ] PreToolUse hook runs before tool execution\n- [ ] You understand skill auto-invocation vs. hook event triggers\n\n#### Next Steps\n- Create your own custom skill\n- Set up additional hooks for your workflow\n- Read: [03-skills/README.md](03-skills/README.md)\n- Read: [06-hooks/README.md](06-hooks/README.md)\n\n> **Check your understanding**: Run `/lesson-quiz skills` or `/lesson-quiz hooks` to test your knowledge before moving on.\n\n---\n\n### Milestone 2B: Integration (MCP + Subagents)\n\n**Topics**: MCP + Subagents\n**Time**: 2-3 hours\n**Complexity**: ⭐⭐⭐ Intermediate+\n**Goal**: Integrate external services and delegate complex tasks\n\n#### What You'll Achieve\n✅ Access live data from GitHub, databases, etc.\n✅ Delegate work to specialized AI agents\n✅ Understand when to use MCP vs. subagents\n✅ Build integrated workflows\n\n#### Hands-on Exercises\n\n```bash\n# Exercise 1: Set up GitHub MCP\nexport GITHUB_TOKEN=\"your_github_token\"\nclaude mcp add github -- npx -y @modelcontextprotocol/server-github\n\n# Exercise 2: Test MCP integration\n# In Claude Code: /mcp__github__list_prs\n\n# Exercise 3: Install subagents\nmkdir -p .claude/agents\ncp 04-subagents/*.md .claude/agents/\n```\n\n#### Integration Exercise\nTry this complete workflow:\n1. Use MCP to fetch a GitHub PR\n2. Let Claude delegate review to code-reviewer subagent\n3. Use hooks to run tests automatically\n\n#### Success Criteria\n- [ ] Successfully query GitHub data via MCP\n- [ ] Claude delegates complex tasks to subagents\n- [ ] You understand the difference between MCP and subagents\n- [ ] Combined MCP + subagents + hooks in a workflow\n\n#### Next Steps\n- Set up additional MCP servers (database, Slack, etc.)\n- Create custom subagents for your domain\n- Read: [05-mcp/README.md](05-mcp/README.md)\n- Read: [04-subagents/README.md](04-subagents/README.md)\n- **Ready for Level 3!** Proceed to [Milestone 3A](#milestone-3a-advanced-features)\n\n> **Check your understanding**: Run `/lesson-quiz mcp` or `/lesson-quiz subagents` to verify you're ready for Level 3.\n\n---\n\n## 🔴 Level 3: Advanced — Power User & Team Lead\n\n**For**: Users with 6-8 quiz checks\n**Time**: ~5 hours\n**Focus**: Team tooling, CI/CD, enterprise features, plugin development\n**Outcome**: Power user, can set up team workflows and CI/CD\n\n### Prerequisites Check\n\nBefore starting Level 3, make sure you're comfortable with these Level 2 concepts:\n\n- [ ] Can create and use skills with auto-invocation ([03-skills/](03-skills/))\n- [ ] Have set up hooks for event-driven automation ([06-hooks/](06-hooks/))\n- [ ] Can configure MCP servers for external data ([05-mcp/](05-mcp/))\n- [ ] Know how to use subagents for task delegation ([04-subagents/](04-subagents/))\n\n> **Gaps?** Review the linked tutorials above before continuing.\n\n---\n\n### Milestone 3A: Advanced Features\n\n**Topics**: Advanced Features (Planning, Permissions, Extended Thinking, Auto Mode, Channels, Voice Dictation, Remote/Desktop/Web)\n**Time**: 2-3 hours\n**Complexity**: ⭐⭐⭐⭐⭐ Advanced\n**Goal**: Master advanced workflows and power user tools\n\n#### What You'll Achieve\n✅ Planning mode for complex features\n✅ Fine-grained permission control with 6 modes (default, acceptEdits, plan, auto, dontAsk, bypassPermissions)\n✅ Extended thinking via Alt+T / Option+T toggle\n✅ Background task management\n✅ Auto Memory for learned preferences\n✅ Auto Mode with background safety classifier\n✅ Channels for structured multi-session workflows\n✅ Voice Dictation for hands-free interaction\n✅ Remote control, desktop app, and web sessions\n✅ Agent Teams for multi-agent collaboration\n\n#### Hands-on Exercises\n\n```bash\n# Exercise 1: Use planning mode\n/plan Implement user authentication system\n\n# Exercise 2: Try permission modes (6 available: default, acceptEdits, plan, auto, dontAsk, bypassPermissions)\nclaude --permission-mode plan \"analyze this codebase\"\nclaude --permission-mode acceptEdits \"refactor the auth module\"\nclaude --permission-mode auto \"implement the feature\"\n\n# Exercise 3: Enable extended thinking\n# Press Alt+T (Option+T on macOS) during a session to toggle\n\n# Exercise 4: Advanced checkpoint workflow\n# 1. Create checkpoint \"Clean state\"\n# 2. Use planning mode to design a feature\n# 3. Implement with subagent delegation\n# 4. Run tests in background\n# 5. If tests fail, rewind to checkpoint\n# 6. Try alternative approach\n\n# Exercise 5: Try auto mode (background safety classifier)\nclaude --permission-mode auto \"implement user settings page\"\n\n# Exercise 6: Enable agent teams\nexport CLAUDE_AGENT_TEAMS=1\n# Ask Claude: \"Implement feature X using a team approach\"\n\n# Exercise 7: Scheduled tasks\n/loop 5m /check-status\n# Or use CronCreate for persistent scheduled tasks\n\n# Exercise 8: Channels for multi-session workflows\n# Use channels to organize work across sessions\n\n# Exercise 9: Voice Dictation\n# Use voice input for hands-free interaction with Claude Code\n```\n\n#### Success Criteria\n- [ ] Used planning mode for a complex feature\n- [ ] Configured permission modes (plan, acceptEdits, auto, dontAsk)\n- [ ] Toggled extended thinking with Alt+T / Option+T\n- [ ] Used auto mode with background safety classifier\n- [ ] Used background tasks for long operations\n- [ ] Explored Channels for multi-session workflows\n- [ ] Tried Voice Dictation for hands-free input\n- [ ] Understand Remote Control, Desktop App, and Web sessions\n- [ ] Enabled and used Agent Teams for collaborative tasks\n- [ ] Used `/loop` for recurring tasks or scheduled monitoring\n\n#### Next Steps\n- Read: [09-advanced-features/README.md](09-advanced-features/README.md)\n\n> **Check your understanding**: Run `/lesson-quiz advanced` to test your mastery of power user features.\n\n---\n\n### Milestone 3B: Team & Distribution (Plugins + CLI Mastery)\n\n**Topics**: Plugins + CLI Mastery + CI/CD\n**Time**: 2-3 hours\n**Complexity**: ⭐⭐⭐⭐ Advanced\n**Goal**: Build team tooling, create plugins, master CI/CD integration\n\n#### What You'll Achieve\n✅ Install and create complete bundled plugins\n✅ Master CLI for scripting and automation\n✅ Set up CI/CD integration with `claude -p`\n✅ JSON output for automated pipelines\n✅ Session management and batch processing\n\n#### Hands-on Exercises\n\n```bash\n# Exercise 1: Install a complete plugin\n# In Claude Code: /plugin install pr-review\n\n# Exercise 2: Print mode for CI/CD\nclaude -p \"Run all tests and generate report\"\n\n# Exercise 3: JSON output for scripts\nclaude -p --output-format json \"list all functions\"\n\n# Exercise 4: Session management and resumption\nclaude -r \"feature-auth\" \"continue implementation\"\n\n# Exercise 5: CI/CD integration with constraints\nclaude -p --max-turns 3 --output-format json \"review code\"\n\n# Exercise 6: Batch processing\nfor file in *.md; do\n  claude -p --output-format json \"summarize this: $(cat $file)\" > ${file%.md}.summary.json\ndone\n```\n\n#### CI/CD Integration Exercise\nCreate a simple CI/CD script:\n1. Use `claude -p` to review changed files\n2. Output results as JSON\n3. Process with `jq` for specific issues\n4. Integrate into GitHub Actions workflow\n\n#### Success Criteria\n- [ ] Installed and used a plugin\n- [ ] Built or modified a plugin for your team\n- [ ] Used print mode (`claude -p`) in CI/CD\n- [ ] Generated JSON output for scripting\n- [ ] Resumed a previous session successfully\n- [ ] Created a batch processing script\n- [ ] Integrated Claude into a CI/CD workflow\n\n#### Real-World Use Cases for CLI\n- **Code Review Automation**: Run code reviews in CI/CD pipelines\n- **Log Analysis**: Analyze error logs and system outputs\n- **Documentation Generation**: Batch generate documentation\n- **Testing Insights**: Analyze test failures\n- **Performance Analysis**: Review performance metrics\n- **Data Processing**: Transform and analyze data files\n\n#### Next Steps\n- Read: [07-plugins/README.md](07-plugins/README.md)\n- Read: [10-cli/README.md](10-cli/README.md)\n- Create team-wide CLI shortcuts and plugins\n- Set up batch processing scripts\n\n> **Check your understanding**: Run `/lesson-quiz plugins` or `/lesson-quiz cli` to confirm your mastery.\n\n---\n\n## 🧪 Test Your Knowledge\n\nThis repository includes two interactive skills you can use anytime in Claude Code to evaluate your understanding:\n\n| Skill | Command | Purpose |\n|-------|---------|---------|\n| **Self-Assessment** | `/self-assessment` | Evaluate your overall proficiency across all 10 features. Choose Quick (2 min) or Deep (5 min) mode to get a personalized skill profile and learning path. |\n| **Lesson Quiz** | `/lesson-quiz [lesson]` | Test your understanding of a specific lesson with 10 questions. Use before a lesson (pre-test), during (progress check), or after (mastery verification). |\n\n**Examples:**\n```\n/self-assessment                  # Find your overall level\n/lesson-quiz hooks                # Quiz on Lesson 06: Hooks\n/lesson-quiz 03                   # Quiz on Lesson 03: Skills\n/lesson-quiz advanced-features    # Quiz on Lesson 09\n```\n\n---\n\n## ⚡ Quick Start Paths\n\n### If You Only Have 15 Minutes\n**Goal**: Get your first win\n\n1. Copy one slash command: `cp 01-slash-commands/optimize.md .claude/commands/`\n2. Try it in Claude Code: `/optimize`\n3. Read: [01-slash-commands/README.md](01-slash-commands/README.md)\n\n**Outcome**: You'll have a working slash command and understand the basics\n\n---\n\n### If You Have 1 Hour\n**Goal**: Set up essential productivity tools\n\n1. **Slash commands** (15 min): Copy and test `/optimize` and `/pr`\n2. **Project memory** (15 min): Create CLAUDE.md with your project standards\n3. **Install a skill** (15 min): Set up code-review skill\n4. **Try them together** (15 min): See how they work in harmony\n\n**Outcome**: Basic productivity boost with commands, memory, and auto-skills\n\n---\n\n### If You Have a Weekend\n**Goal**: Become proficient with most features\n\n**Saturday Morning** (3 hours):\n- Complete Milestone 1A: Slash Commands + Memory\n- Complete Milestone 1B: Checkpoints + CLI Basics\n\n**Saturday Afternoon** (3 hours):\n- Complete Milestone 2A: Skills + Hooks\n- Complete Milestone 2B: MCP + Subagents\n\n**Sunday** (4 hours):\n- Complete Milestone 3A: Advanced Features\n- Complete Milestone 3B: Plugins + CLI Mastery + CI/CD\n- Build a custom plugin for your team\n\n**Outcome**: You'll be a Claude Code power user ready to train others and automate complex workflows\n\n---\n\n## 💡 Learning Tips\n\n### ✅ Do\n\n- **Take the quiz first** to find your starting point\n- **Complete hands-on exercises** for each milestone\n- **Start simple** and add complexity gradually\n- **Test each feature** before moving to the next\n- **Take notes** on what works for your workflow\n- **Refer back** to earlier concepts as you learn advanced topics\n- **Experiment safely** using checkpoints\n- **Share knowledge** with your team\n\n### ❌ Don't\n\n- **Skip the prerequisites check** when jumping to a higher level\n- **Try to learn everything at once** - it's overwhelming\n- **Copy configurations without understanding them** - you won't know how to debug\n- **Forget to test** - always verify features work\n- **Rush through milestones** - take time to understand\n- **Ignore the documentation** - each README has valuable details\n- **Work in isolation** - discuss with teammates\n\n---\n\n## 🎓 Learning Styles\n\n### Visual Learners\n- Study the mermaid diagrams in each README\n- Watch the command execution flow\n- Draw your own workflow diagrams\n- Use the visual learning path above\n\n### Hands-on Learners\n- Complete every hands-on exercise\n- Experiment with variations\n- Break things and fix them (use checkpoints!)\n- Create your own examples\n\n### Reading Learners\n- Read each README thoroughly\n- Study the code examples\n- Review the comparison tables\n- Read the blog posts linked in resources\n\n### Social Learners\n- Set up pair programming sessions\n- Teach concepts to teammates\n- Join Claude Code community discussions\n- Share your custom configurations\n\n---\n\n## 📈 Progress Tracking\n\nUse these checklists to track your progress by level. Run `/self-assessment` anytime to get an updated skill profile, or `/lesson-quiz [lesson]` after each tutorial to verify your understanding.\n\n### 🟢 Level 1: Beginner\n- [ ] Completed [01-slash-commands](01-slash-commands/)\n- [ ] Completed [02-memory](02-memory/)\n- [ ] Created first custom slash command\n- [ ] Set up project memory\n- [ ] **Milestone 1A achieved**\n- [ ] Completed [08-checkpoints](08-checkpoints/)\n- [ ] Completed [10-cli](10-cli/) basics\n- [ ] Created and reverted to a checkpoint\n- [ ] Used interactive and print mode\n- [ ] **Milestone 1B achieved**\n\n### 🔵 Level 2: Intermediate\n- [ ] Completed [03-skills](03-skills/)\n- [ ] Completed [06-hooks](06-hooks/)\n- [ ] Installed first skill\n- [ ] Set up PreToolUse hook\n- [ ] **Milestone 2A achieved**\n- [ ] Completed [05-mcp](05-mcp/)\n- [ ] Completed [04-subagents](04-subagents/)\n- [ ] Connected GitHub MCP\n- [ ] Created custom subagent\n- [ ] Combined integrations in a workflow\n- [ ] **Milestone 2B achieved**\n\n### 🔴 Level 3: Advanced\n- [ ] Completed [09-advanced-features](09-advanced-features/)\n- [ ] Used planning mode successfully\n- [ ] Configured permission modes (6 modes including auto)\n- [ ] Used auto mode with safety classifier\n- [ ] Used extended thinking toggle\n- [ ] Explored Channels and Voice Dictation\n- [ ] **Milestone 3A achieved**\n- [ ] Completed [07-plugins](07-plugins/)\n- [ ] Completed [10-cli](10-cli/) advanced usage\n- [ ] Set up print mode (`claude -p`) CI/CD\n- [ ] Created JSON output for automation\n- [ ] Integrated Claude into CI/CD pipeline\n- [ ] Created team plugin\n- [ ] **Milestone 3B achieved**\n\n---\n\n## 🆘 Common Learning Challenges\n\n### Challenge 1: \"Too many concepts at once\"\n**Solution**: Focus on one milestone at a time. Complete all exercises before moving forward.\n\n### Challenge 2: \"Don't know which feature to use when\"\n**Solution**: Refer to the [Use Case Matrix](README.md#use-case-matrix) in the main README.\n\n### Challenge 3: \"Configuration not working\"\n**Solution**: Check the [Troubleshooting](README.md#troubleshooting) section and verify file locations.\n\n### Challenge 4: \"Concepts seem to overlap\"\n**Solution**: Review the [Feature Comparison](README.md#feature-comparison) table to understand differences.\n\n### Challenge 5: \"Hard to remember everything\"\n**Solution**: Create your own cheat sheet. Use checkpoints to experiment safely.\n\n### Challenge 6: \"I'm experienced but not sure where to start\"\n**Solution**: Take the [Self-Assessment Quiz](#-find-your-level) above. Skip to your level and use the prerequisites check to identify any gaps.\n\n---\n\n## 🎯 What's Next After Completion?\n\nOnce you've completed all milestones:\n\n1. **Create team documentation** - Document your team's Claude Code setup\n2. **Build custom plugins** - Package your team's workflows\n3. **Explore Remote Control** - Control Claude Code sessions programmatically from external tools\n4. **Try Web Sessions** - Use Claude Code through browser-based interfaces for remote development\n5. **Use the Desktop App** - Access Claude Code features through the native desktop application\n6. **Use Auto Mode** - Let Claude work autonomously with a background safety classifier\n7. **Leverage Auto Memory** - Let Claude learn your preferences automatically over time\n8. **Set up Agent Teams** - Coordinate multiple agents on complex, multi-faceted tasks\n9. **Use Channels** - Organize work across structured multi-session workflows\n10. **Try Voice Dictation** - Use hands-free voice input for interaction with Claude Code\n11. **Use Scheduled Tasks** - Automate recurring checks with `/loop` and cron tools\n12. **Contribute examples** - Share with the community\n13. **Mentor others** - Help teammates learn\n14. **Optimize workflows** - Continuously improve based on usage\n15. **Stay updated** - Follow Claude Code releases and new features\n\n---\n\n## 📚 Additional Resources\n\n### Official Documentation\n- [Claude Code Documentation](https://code.claude.com/docs/en/overview)\n- [Anthropic Documentation](https://docs.anthropic.com)\n- [MCP Protocol Specification](https://modelcontextprotocol.io)\n\n### Blog Posts\n- [Discovering Claude Code Slash Commands](https://medium.com/@luongnv89/discovering-claude-code-slash-commands-cdc17f0dfb29)\n\n### Community\n- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)\n- [MCP Servers Repository](https://github.com/modelcontextprotocol/servers)\n\n---\n\n## 💬 Feedback & Support\n\n- **Found an issue?** Create an issue in the repository\n- **Have a suggestion?** Submit a pull request\n- **Need help?** Check the documentation or ask the community\n\n---\n\n**Last Updated**: March 2026\n**Maintained by**: Claude How-To Contributors\n**License**: Educational purposes, free to use and adapt\n\n---\n\n[← Back to Main README](README.md)\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2024 luongnv89\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "QUICK_REFERENCE.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Claude Code Examples - Quick Reference Card\n\n## 🚀 Installation Quick Commands\n\n### Slash Commands\n```bash\n# Install all\ncp 01-slash-commands/*.md .claude/commands/\n\n# Install specific\ncp 01-slash-commands/optimize.md .claude/commands/\n```\n\n### Memory\n```bash\n# Project memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Personal memory\ncp 02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md\n```\n\n### Skills\n```bash\n# Personal skills\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Project skills\ncp -r 03-skills/code-review .claude/skills/\n```\n\n### Subagents\n```bash\n# Install all\ncp 04-subagents/*.md .claude/agents/\n\n# Install specific\ncp 04-subagents/code-reviewer.md .claude/agents/\n```\n\n### MCP\n```bash\n# Set credentials\nexport GITHUB_TOKEN=\"your_token\"\nexport DATABASE_URL=\"postgresql://...\"\n\n# Install config (project scope)\ncp 05-mcp/github-mcp.json .mcp.json\n\n# Or user scope: add to ~/.claude.json\n```\n\n### Hooks\n```bash\n# Install hooks\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n\n# Configure in settings (~/.claude/settings.json)\n```\n\n### Plugins\n```bash\n# Install from examples (if published)\n/plugin install pr-review\n/plugin install devops-automation\n/plugin install documentation\n```\n\n### Checkpoints\n```bash\n# Checkpoints are created automatically with every user prompt\n# To rewind, press Esc twice or use:\n/rewind\n\n# Then choose: Restore code and conversation, Restore conversation,\n# Restore code, Summarize from here, or Never mind\n```\n\n### Advanced Features\n```bash\n# Configure in settings (.claude/settings.json)\n# See 09-advanced-features/config-examples.json\n\n# Planning mode\n/plan Task description\n\n# Permission modes (use --permission-mode flag)\n# default        - Ask for approval on risky actions\n# acceptEdits    - Auto-accept file edits, ask for others\n# plan           - Read-only analysis, no modifications\n# dontAsk        - Accept all actions except risky ones\n# auto           - Background classifier decides permissions automatically\n# bypassPermissions - Accept all actions (requires --dangerously-skip-permissions)\n\n# Session management\n/resume                # Resume a previous conversation\n/rename \"name\"         # Name the current session\n/fork                  # Fork the current session\nclaude -c              # Continue most recent conversation\nclaude -r \"session\"    # Resume session by name/ID\n```\n\n---\n\n## 📋 Feature Cheat Sheet\n\n| Feature | Install Path | Usage |\n|---------|-------------|-------|\n| **Slash Commands (55+)** | `.claude/commands/*.md` | `/command-name` |\n| **Memory** | `./CLAUDE.md` | Auto-loaded |\n| **Skills** | `.claude/skills/*/SKILL.md` | Auto-invoked |\n| **Subagents** | `.claude/agents/*.md` | Auto-delegated |\n| **MCP** | `.mcp.json` (project) or `~/.claude.json` (user) | `/mcp__server__action` |\n| **Hooks (25 events)** | `~/.claude/hooks/*.sh` | Event-triggered (4 types) |\n| **Plugins** | Via `/plugin install` | Bundles all |\n| **Checkpoints** | Built-in | `Esc+Esc` or `/rewind` |\n| **Planning Mode** | Built-in | `/plan <task>` |\n| **Permission Modes (6)** | Built-in | `--allowedTools`, `--permission-mode` |\n| **Sessions** | Built-in | `/session <command>` |\n| **Background Tasks** | Built-in | Run in background |\n| **Remote Control** | Built-in | WebSocket API |\n| **Web Sessions** | Built-in | `claude web` |\n| **Git Worktrees** | Built-in | `/worktree` |\n| **Auto Memory** | Built-in | Auto-saves to CLAUDE.md |\n| **Task List** | Built-in | `/task list` |\n| **Bundled Skills (5)** | Built-in | `/simplify`, `/loop`, `/claude-api`, `/voice`, `/browse` |\n\n---\n\n## 🎯 Common Use Cases\n\n### Code Review\n```bash\n# Method 1: Slash command\ncp 01-slash-commands/optimize.md .claude/commands/\n# Use: /optimize\n\n# Method 2: Subagent\ncp 04-subagents/code-reviewer.md .claude/agents/\n# Use: Auto-delegated\n\n# Method 3: Skill\ncp -r 03-skills/code-review ~/.claude/skills/\n# Use: Auto-invoked\n\n# Method 4: Plugin (best)\n/plugin install pr-review\n# Use: /review-pr\n```\n\n### Documentation\n```bash\n# Slash command\ncp 01-slash-commands/generate-api-docs.md .claude/commands/\n\n# Subagent\ncp 04-subagents/documentation-writer.md .claude/agents/\n\n# Skill\ncp -r 03-skills/doc-generator ~/.claude/skills/\n\n# Plugin (complete solution)\n/plugin install documentation\n```\n\n### DevOps\n```bash\n# Complete plugin\n/plugin install devops-automation\n\n# Commands: /deploy, /rollback, /status, /incident\n```\n\n### Team Standards\n```bash\n# Project memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Edit for your team\nvim CLAUDE.md\n```\n\n### Automation & Hooks\n```bash\n# Install hooks (25 events, 4 types: command, http, prompt, agent)\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n\n# Examples:\n# - Pre-commit tests: pre-commit.sh\n# - Auto-format code: format-code.sh\n# - Security scanning: security-scan.sh\n\n# Auto Mode for fully autonomous workflows\nclaude --enable-auto-mode -p \"Refactor and test the auth module\"\n# Or cycle modes interactively with Shift+Tab\n```\n\n### Safe Refactoring\n```bash\n# Checkpoints are created automatically before each prompt\n# Try refactoring\n# If it works: continue\n# If it fails: press Esc+Esc or use /rewind to go back\n```\n\n### Complex Implementation\n```bash\n# Use planning mode\n/plan Implement user authentication system\n\n# Claude creates detailed plan\n# Review and approve\n# Claude implements systematically\n```\n\n### CI/CD Integration\n```bash\n# Run in headless mode (non-interactive)\nclaude -p \"Run all tests and generate report\"\n\n# With permission mode for CI\nclaude -p \"Run tests\" --permission-mode dontAsk\n\n# With Auto Mode for fully autonomous CI tasks\nclaude --enable-auto-mode -p \"Run tests and fix failures\"\n\n# With hooks for automation\n# See 09-advanced-features/README.md\n```\n\n### Learning & Experimentation\n```bash\n# Use plan mode for safe analysis\nclaude --permission-mode plan\n\n# Experiment safely - checkpoints are created automatically\n# If you need to rewind: press Esc+Esc or use /rewind\n```\n\n### Agent Teams\n```bash\n# Enable agent teams\nexport CLAUDE_AGENT_TEAMS=1\n\n# Or in settings.json\n{ \"agentTeams\": { \"enabled\": true } }\n\n# Start with: \"Implement feature X using a team approach\"\n```\n\n### Scheduled Tasks\n```bash\n# Run a command every 5 minutes\n/loop 5m /check-status\n\n# One-time reminder\n/loop 30m \"remind me to check the deploy\"\n```\n\n---\n\n## 📁 File Locations Reference\n\n```\nYour Project/\n├── .claude/\n│   ├── commands/              # Slash commands go here\n│   ├── agents/                # Subagents go here\n│   ├── skills/                # Project skills go here\n│   └── settings.json          # Project settings (hooks, etc.)\n├── .mcp.json                  # MCP configuration (project scope)\n├── CLAUDE.md                  # Project memory\n└── src/\n    └── api/\n        └── CLAUDE.md          # Directory-specific memory\n\nUser Home/\n├── .claude/\n│   ├── commands/              # Personal commands\n│   ├── agents/                # Personal agents\n│   ├── skills/                # Personal skills\n│   ├── hooks/                 # Hook scripts\n│   ├── settings.json          # User settings\n│   ├── managed-settings.d/    # Managed settings (enterprise/org)\n│   └── CLAUDE.md              # Personal memory\n└── .claude.json               # Personal MCP config (user scope)\n```\n\n---\n\n## 🔍 Finding Examples\n\n### By Category\n- **Slash Commands**: `01-slash-commands/`\n- **Memory**: `02-memory/`\n- **Skills**: `03-skills/`\n- **Subagents**: `04-subagents/`\n- **MCP**: `05-mcp/`\n- **Hooks**: `06-hooks/`\n- **Plugins**: `07-plugins/`\n- **Checkpoints**: `08-checkpoints/`\n- **Advanced Features**: `09-advanced-features/`\n- **CLI**: `10-cli/`\n\n### By Use Case\n- **Performance**: `01-slash-commands/optimize.md`\n- **Security**: `04-subagents/secure-reviewer.md`\n- **Testing**: `04-subagents/test-engineer.md`\n- **Docs**: `03-skills/doc-generator/`\n- **DevOps**: `07-plugins/devops-automation/`\n\n### By Complexity\n- **Simple**: Slash commands\n- **Medium**: Subagents, Memory\n- **Advanced**: Skills, Hooks\n- **Complete**: Plugins\n\n---\n\n## 🎓 Learning Path\n\n### Day 1\n```bash\n# Read overview\ncat README.md\n\n# Install a command\ncp 01-slash-commands/optimize.md .claude/commands/\n\n# Try it\n/optimize\n```\n\n### Day 2-3\n```bash\n# Set up memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\nvim CLAUDE.md\n\n# Install subagent\ncp 04-subagents/code-reviewer.md .claude/agents/\n```\n\n### Day 4-5\n```bash\n# Set up MCP\nexport GITHUB_TOKEN=\"your_token\"\ncp 05-mcp/github-mcp.json .mcp.json\n\n# Try MCP commands\n/mcp__github__list_prs\n```\n\n### Week 2\n```bash\n# Install skill\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Let it auto-invoke\n# Just say: \"Review this code for issues\"\n```\n\n### Week 3+\n```bash\n# Install complete plugin\n/plugin install pr-review\n\n# Use bundled features\n/review-pr\n/check-security\n/check-tests\n```\n\n---\n\n## New Features (March 2026)\n\n| Feature | Description | Usage |\n|---------|-------------|-------|\n| **Auto Mode** | Fully autonomous operation with background classifier | `--enable-auto-mode` flag, `Shift+Tab` to cycle modes |\n| **Channels** | Discord and Telegram integration | `--channels` flag, Discord/Telegram bots |\n| **Voice Dictation** | Speak commands and context to Claude | `/voice` command |\n| **Hooks (25 events)** | Expanded hook system with 4 types | command, http, prompt, agent hook types |\n| **MCP Elicitation** | MCP servers can request user input at runtime | Auto-prompted when server needs clarification |\n| **WebSocket MCP** | WebSocket transport for MCP connections | Configure in `.mcp.json` with `ws://` URLs |\n| **Plugin LSP** | Language Server Protocol support for plugins | `userConfig`, `${CLAUDE_PLUGIN_DATA}` variable |\n| **Remote Control** | Control Claude Code via WebSocket API | `claude --remote` for external integrations |\n| **Web Sessions** | Browser-based Claude Code interface | `claude web` to launch |\n| **Desktop App** | Native desktop application | Download from claude.ai/download |\n| **Task List** | Manage background tasks | `/task list`, `/task status <id>` |\n| **Auto Memory** | Automatic memory saving from conversations | Claude auto-saves key context to CLAUDE.md |\n| **Git Worktrees** | Isolated workspaces for parallel development | `/worktree` to create isolated workspace |\n| **Model Selection** | Switch between Sonnet 4.6 and Opus 4.6 | `/model` or `--model` flag |\n| **Agent Teams** | Coordinate multiple agents on tasks | Enable with `CLAUDE_AGENT_TEAMS=1` env var |\n| **Scheduled Tasks** | Recurring tasks with `/loop` | `/loop 5m /command` or CronCreate tool |\n| **Chrome Integration** | Browser automation | `--chrome` flag or `/chrome` command |\n| **Keyboard Customization** | Custom keybindings | `/keybindings` command |\n\n---\n\n## Tips & Tricks\n\n### Customization\n- Start with examples as-is\n- Modify to fit your needs\n- Test before sharing with team\n- Version control your configurations\n\n### Best Practices\n- Use memory for team standards\n- Use plugins for complete workflows\n- Use subagents for complex tasks\n- Use slash commands for quick tasks\n\n### Troubleshooting\n```bash\n# Check file locations\nls -la .claude/commands/\nls -la .claude/agents/\n\n# Verify YAML syntax\nhead -20 .claude/agents/code-reviewer.md\n\n# Test MCP connection\necho $GITHUB_TOKEN\n```\n\n---\n\n## 📊 Feature Matrix\n\n| Need | Use This | Example |\n|------|----------|---------|\n| Quick shortcut | Slash Command (55+) | `01-slash-commands/optimize.md` |\n| Team standards | Memory | `02-memory/project-CLAUDE.md` |\n| Auto workflow | Skill | `03-skills/code-review/` |\n| Specialized task | Subagent | `04-subagents/code-reviewer.md` |\n| External data | MCP (+ Elicitation, WebSocket) | `05-mcp/github-mcp.json` |\n| Event automation | Hook (25 events, 4 types) | `06-hooks/pre-commit.sh` |\n| Complete solution | Plugin (+ LSP support) | `07-plugins/pr-review/` |\n| Safe experiment | Checkpoint | `08-checkpoints/checkpoint-examples.md` |\n| Fully autonomous | Auto Mode | `--enable-auto-mode` or `Shift+Tab` |\n| Chat integrations | Channels | `--channels` (Discord, Telegram) |\n| CI/CD pipeline | CLI | `10-cli/README.md` |\n\n---\n\n## 🔗 Quick Links\n\n- **Main Guide**: `README.md`\n- **Complete Index**: `INDEX.md`\n- **Summary**: `EXAMPLES_SUMMARY.md`\n- **Original Guide**: `claude_concepts_guide.md`\n\n---\n\n## 📞 Common Questions\n\n**Q: Which should I use?**\nA: Start with slash commands, add features as needed.\n\n**Q: Can I mix features?**\nA: Yes! They work together. Memory + Commands + MCP = powerful.\n\n**Q: How do I share with team?**\nA: Commit `.claude/` directory to git.\n\n**Q: What about secrets?**\nA: Use environment variables, never hardcode.\n\n**Q: Can I modify examples?**\nA: Absolutely! They're templates to customize.\n\n---\n\n## ✅ Checklist\n\nGetting started checklist:\n\n- [ ] Read `README.md`\n- [ ] Install 1 slash command\n- [ ] Try the command\n- [ ] Create project `CLAUDE.md`\n- [ ] Install 1 subagent\n- [ ] Set up 1 MCP integration\n- [ ] Install 1 skill\n- [ ] Try a complete plugin\n- [ ] Customize for your needs\n- [ ] Share with team\n\n---\n\n**Quick Start**: `cat README.md`\n\n**Full Index**: `cat INDEX.md`\n\n**This Card**: Keep it handy for quick reference!\n"
  },
  {
    "path": "README.backup.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Claude How To\n\n> A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.\n\n## Why This Guide?\n\nThis project complements [Anthropic's official documentation](https://code.claude.com/docs/en/overview) with a different approach:\n\n| | Official Docs | This Guide |\n|--|---------------|------------|\n| **Format** | Reference documentation | Visual tutorials with diagrams |\n| **Depth** | Feature descriptions | How it works under the hood |\n| **Examples** | Basic snippets | Production-ready templates you can use immediately |\n| **Structure** | Feature-organized | Progressive learning path (beginner → advanced) |\n| **Onboarding** | Self-directed | Guided roadmap with time estimates |\n| **Self-Assessment** | None | Interactive quizzes to identify skill gaps and build a personalized learning path |\n\n**What you'll find here:**\n- Mermaid diagrams explaining how each feature works\n- Ready-to-use configurations you can copy into your project\n- Real-world examples with context and best practices\n- Clear progression from `/help` to building custom agents\n- Troubleshooting guides based on common issues\n\n---\n\n## Table of Contents\n\n- [Why This Guide?](#why-this-guide)\n- [Feature Catalog](#-feature-catalog)\n- [Quick Navigation](#quick-navigation)\n- [Learning Path](#-learning-path)\n- [Quick Reference](#-quick-reference-choose-your-features)\n- [Getting Started](#-getting-started)\n- **Features**\n  - [01. Slash Commands](#01-slash-commands)\n  - [02. Memory](#02-memory)\n  - [03. Skills](#03-skills)\n  - [04. Subagents](#04-subagents)\n  - [05. MCP Protocol](#05-mcp-protocol)\n  - [06. Hooks](#06-hooks)\n  - [07. Plugins](#07-plugins)\n  - [08. Checkpoints](#08-checkpoints-and-rewind)\n  - [09. Advanced Features](#09-advanced-features)\n  - [10. CLI Reference](#10-cli-reference)\n- [Directory Structure](#directory-structure)\n- [Installation Quick Reference](#installation-quick-reference)\n- [Example Workflows](#example-workflows)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [Testing](#testing)\n- [Additional Resources](#additional-resources)\n- [Contributing](#contributing)\n- [EPUB Generation](#epub-generation)\n- [Contributors](#contributors)\n- [Star History](#star-history)\n\n---\n\n## Feature Catalog\n\n**Looking for a quick reference?** Check out our comprehensive **[Feature Catalog](CATALOG.md)** for:\n\n- All slash commands (built-in and custom) with descriptions\n- Sub-agents and their capabilities\n- Skills with auto-invocation triggers\n- Plugins with components and installation commands\n- MCP servers for external integrations\n- Hooks for event-driven automation\n- One-command installation for each feature\n\n**[View Full Catalog](CATALOG.md)**\n\n---\n\n## Quick Navigation\n\n| Feature | Description | Folder |\n|---------|-------------|--------|\n| **Feature Catalog** | Complete reference with installation commands | [CATALOG.md](CATALOG.md) |\n| **Slash Commands** | User-invoked shortcuts | [01-slash-commands/](01-slash-commands/) |\n| **Memory** | Persistent context | [02-memory/](02-memory/) |\n| **Skills** | Reusable capabilities | [03-skills/](03-skills/) |\n| **Subagents** | Specialized AI assistants | [04-subagents/](04-subagents/) |\n| **MCP Protocol** | External tool access | [05-mcp/](05-mcp/) |\n| **Hooks** | Event-driven automation | [06-hooks/](06-hooks/) |\n| **Plugins** | Bundled features | [07-plugins/](07-plugins/) |\n| **Checkpoints** | Session snapshots & rewind | [08-checkpoints/](08-checkpoints/) |\n| **Advanced Features** | Planning, thinking, background tasks | [09-advanced-features/](09-advanced-features/) |\n| **CLI Reference** | Commands, flags, and options | [10-cli/](10-cli/) |\n| **Blog Posts** | Real-world usage examples | [Blog Posts](https://medium.com/@luongnv89) |\n\n---\n\n## 📚 Learning Path\n\n**Not sure where to start?** Take the [Self-Assessment Quiz](LEARNING-ROADMAP.md#-find-your-level) to find your recommended path, or run `/self-assessment` in Claude Code for an interactive version.\n\n> **Built-in skills**: This repo includes two interactive skills you can use directly in Claude Code:\n> - `/self-assessment` — Evaluate your overall Claude Code proficiency and get a personalized learning path\n> - `/lesson-quiz [lesson]` — Test your understanding of any specific lesson (e.g., `/lesson-quiz hooks`)\n\n| Order | Feature | Level | Time | Recommended For |\n|-------|---------|-------|------|-----------------|\n| **1** | [Slash Commands](01-slash-commands/) | ⭐ Beginner | 30 min | Level 1 start |\n| **2** | [Memory](02-memory/) | ⭐⭐ Beginner+ | 45 min | Level 1 |\n| **3** | [Checkpoints](08-checkpoints/) | ⭐⭐ Intermediate | 45 min | Level 1 |\n| **4** | [CLI Basics](10-cli/) | ⭐⭐ Beginner+ | 30 min | Level 1 |\n| **5** | [Skills](03-skills/) | ⭐⭐ Intermediate | 1 hour | Level 2 start |\n| **6** | [Hooks](06-hooks/) | ⭐⭐ Intermediate | 1 hour | Level 2 |\n| **7** | [MCP](05-mcp/) | ⭐⭐⭐ Intermediate+ | 1 hour | Level 2 |\n| **8** | [Subagents](04-subagents/) | ⭐⭐⭐ Intermediate+ | 1.5 hours | Level 2 |\n| **9** | [Advanced](09-advanced-features/) | ⭐⭐⭐⭐⭐ Advanced | 2-3 hours | Level 3 start |\n| **10** | [Plugins](07-plugins/) | ⭐⭐⭐⭐ Advanced | 2 hours | Level 3 |\n| **11** | [CLI Mastery](10-cli/) | ⭐⭐⭐ Advanced | 1 hour | Level 3 |\n\n**Total**: ~11-13 hours | 📖 **[Complete Learning Roadmap →](LEARNING-ROADMAP.md)**\n\n---\n\n## 🎯 Quick Reference: Choose Your Features\n\n### Feature Comparison\n\n| Feature | Invocation | Persistence | Best For |\n|---------|-----------|------------|----------|\n| **Slash Commands** | Manual (`/cmd`) | Session only | Quick shortcuts |\n| **Memory** | Auto-loaded | Cross-session | Long-term learning |\n| **Skills** | Auto-invoked | Filesystem | Automated workflows |\n| **Subagents** | Auto-delegated | Isolated context | Task distribution |\n| **MCP Protocol** | Auto-queried | Real-time | Live data access |\n| **Hooks** | Event-triggered | Configured | Automation & validation |\n| **Plugins** | One command | All features | Complete solutions |\n| **Checkpoints** | Manual/Auto | Session-based | Safe experimentation |\n| **Planning Mode** | Manual/Auto | Plan phase | Complex implementations |\n| **Background Tasks** | Manual | Task duration | Long-running operations |\n| **CLI Reference** | Terminal commands | Session/Script | Automation & scripting |\n\n### Use Case Matrix\n\n| Use Case | Recommended Features |\n|----------|---------------------|\n| **Team Onboarding** | Memory + Slash Commands + Plugins |\n| **Code Quality** | Subagents + Skills + Memory + Hooks |\n| **Documentation** | Skills + Subagents + Plugins |\n| **DevOps** | Plugins + MCP + Hooks + Background Tasks |\n| **Security Review** | Subagents + Skills + Hooks (read-only mode) |\n| **API Integration** | MCP + Memory |\n| **Quick Tasks** | Slash Commands |\n| **Complex Projects** | All Features + Planning Mode |\n| **Refactoring** | Checkpoints + Planning Mode + Hooks |\n| **Learning/Experimentation** | Checkpoints + Extended Thinking + Permission Mode |\n| **CI/CD Automation** | CLI Reference + Hooks + Background Tasks |\n| **Performance Optimization** | Planning Mode + Checkpoints + Background Tasks |\n| **Script Automation** | CLI Reference + Hooks + MCP |\n| **Batch Processing** | CLI Reference + Background Tasks |\n\n---\n\n## ⚡ Getting Started\n\n### 15 Minutes - First Steps\n```bash\n# Copy your first slash command\ncp 01-slash-commands/optimize.md .claude/commands/\n\n# Try it!\n# In Claude Code: /optimize\n```\n\n### 1 Hour - Essential Setup\n```bash\n# 1. Slash commands (15 min)\ncp 01-slash-commands/*.md .claude/commands/\n\n# 2. Project memory (15 min)\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# 3. Install a skill (15 min)\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# 4. Try them together (15 min)\n# See how they work in harmony!\n```\n\n### Weekend - Full Setup\n- **Day 1**: Slash Commands, Memory, Skills, Hooks\n- **Day 2**: Subagents, MCP integration, Plugins\n- **Result**: Complete Claude Code power user setup\n\n📖 **[Detailed milestones and exercises →](LEARNING-ROADMAP.md)**\n\n---\n\n## 01. Slash Commands\n\n**Location**: [01-slash-commands/](01-slash-commands/)\n\n**What**: User-invoked shortcuts stored as Markdown files\n\n**Examples**:\n- `optimize.md` - Code optimization analysis\n- `pr.md` - Pull request preparation\n- `generate-api-docs.md` - API documentation generator\n\n**Installation**:\n```bash\ncp 01-slash-commands/*.md /path/to/project/.claude/commands/\n```\n\n**Usage**:\n```\n/optimize\n/pr\n/generate-api-docs\n```\n\n**Learn More**: [Discovering Claude Code Slash Commands](https://medium.com/@luongnv89/discovering-claude-code-slash-commands-cdc17f0dfb29)\n\n---\n\n## 02. Memory\n\n**Location**: [02-memory/](02-memory/)\n\n**What**: Persistent context across sessions\n\n**Examples**:\n- `project-CLAUDE.md` - Team-wide project standards\n- `directory-api-CLAUDE.md` - Directory-specific rules\n- `personal-CLAUDE.md` - Personal preferences\n\n**Installation**:\n```bash\n# Project memory\ncp 02-memory/project-CLAUDE.md /path/to/project/CLAUDE.md\n\n# Directory memory\ncp 02-memory/directory-api-CLAUDE.md /path/to/project/src/api/CLAUDE.md\n\n# Personal memory\ncp 02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md\n```\n\n**Usage**: Automatically loaded by Claude\n\n---\n\n## 03. Skills\n\n**Location**: [03-skills/](03-skills/)\n\n**What**: Reusable, auto-invoked capabilities with instructions and scripts\n\n**Examples**:\n- `code-review/` - Comprehensive code review with scripts\n- `brand-voice/` - Brand voice consistency checker\n- `doc-generator/` - API documentation generator\n\n**Installation**:\n```bash\n# Personal skills\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Project skills\ncp -r 03-skills/code-review /path/to/project/.claude/skills/\n```\n\n**Usage**: Automatically invoked when relevant\n\n---\n\n## 04. Subagents\n\n**Location**: [04-subagents/](04-subagents/)\n\n**What**: Specialized AI assistants with isolated contexts and custom prompts\n\n**Examples**:\n- `code-reviewer.md` - Comprehensive code quality analysis\n- `test-engineer.md` - Test strategy and coverage\n- `documentation-writer.md` - Technical documentation\n- `secure-reviewer.md` - Security-focused review (read-only)\n- `implementation-agent.md` - Full feature implementation\n\n**Installation**:\n```bash\ncp 04-subagents/*.md /path/to/project/.claude/agents/\n```\n\n**Usage**: Automatically delegated by main agent\n\n---\n\n## 05. MCP Protocol\n\n**Location**: [05-mcp/](05-mcp/)\n\n**What**: Model Context Protocol for accessing external tools and APIs\n\n**Examples**:\n- `github-mcp.json` - GitHub integration\n- `database-mcp.json` - Database queries\n- `filesystem-mcp.json` - File operations\n- `multi-mcp.json` - Multiple MCP servers\n\n**Installation**:\n```bash\n# Set environment variables\nexport GITHUB_TOKEN=\"your_token\"\nexport DATABASE_URL=\"postgresql://...\"\n\n# Add MCP server via CLI\nclaude mcp add github -- npx -y @modelcontextprotocol/server-github\n\n# Or add to project .mcp.json manually (see 05-mcp/ for examples)\n```\n\n**Usage**: MCP tools are automatically available to Claude once configured\n\n---\n\n## 06. Hooks\n\n**Location**: [06-hooks/](06-hooks/)\n\n**What**: Event-driven shell commands that execute automatically in response to Claude Code events\n\n**Examples**:\n- `format-code.sh` - Auto-format code before writing\n- `pre-commit.sh` - Run tests before commits\n- `security-scan.sh` - Scan for security issues\n- `log-bash.sh` - Log all bash commands\n- `validate-prompt.sh` - Validate user prompts\n- `notify-team.sh` - Send notifications on events\n\n**Installation**:\n```bash\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n```\n\nConfigure hooks in `~/.claude/settings.json`:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [{\n      \"matcher\": \"Write\",\n      \"hooks\": [\"~/.claude/hooks/format-code.sh\"]\n    }],\n    \"PostToolUse\": [{\n      \"matcher\": \"Write\",\n      \"hooks\": [\"~/.claude/hooks/security-scan.sh\"]\n    }]\n  }\n}\n```\n\n**Usage**: Hooks execute automatically on events\n\n**Hook Types**:\n- **Tool Hooks**: `PreToolUse:*`, `PostToolUse:*`\n- **Session Hooks**: `Stop`, `SubagentStop`, `SubagentStart`\n- **Lifecycle Hooks**: `Notification`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`\n\n---\n\n## 07. Plugins\n\n**Location**: [07-plugins/](07-plugins/)\n\n**What**: Bundled collections of commands, agents, MCP, and hooks\n\n**Examples**:\n- `pr-review/` - Complete PR review workflow\n- `devops-automation/` - Deployment and monitoring\n- `documentation/` - Documentation generation\n\n**Installation**:\n```bash\n/plugin install pr-review\n/plugin install devops-automation\n/plugin install documentation\n```\n\n**Usage**: Use bundled slash commands and features\n\n---\n\n## 08. Checkpoints and Rewind\n\n**Location**: [08-checkpoints/](08-checkpoints/)\n\n**What**: Save conversation state and rewind to previous points to explore different approaches\n\n**Key Concepts**:\n- **Checkpoint**: Snapshot of conversation state\n- **Rewind**: Return to previous checkpoint\n- **Branch Point**: Explore multiple approaches from same checkpoint\n\n**Usage**:\n```\n# Checkpoints are created automatically with every user prompt\n# To rewind, press Esc twice or use:\n/rewind\n\n# Then choose from five options:\n# 1. Restore code and conversation\n# 2. Restore conversation\n# 3. Restore code\n# 4. Summarize from here\n# 5. Never mind\n```\n\n**Use Cases**:\n- Try different implementation approaches\n- Recover from mistakes\n- Safe experimentation\n- Compare alternative solutions\n- A/B testing different designs\n\n**Example Workflow**:\n```\n1. Work normally (checkpoints are created automatically)\n2. Try experimental approach\n3. If it works: Continue\n4. If it fails: Press Esc+Esc or /rewind to go back\n```\n\n---\n\n## 09. Advanced Features\n\n**Location**: [09-advanced-features/](09-advanced-features/)\n\n**What**: Advanced capabilities for complex workflows and automation\n\n### Planning Mode\n\nCreate detailed implementation plans before coding:\n```\nUser: /plan Implement user authentication system\n\nClaude: [Creates comprehensive step-by-step plan]\n\nUser: Approve and proceed\n```\n\n**Benefits**: Clear roadmap, time estimates, risk assessment\n\n### Extended Thinking\n\nDeep reasoning for complex problems. Toggle with `Alt+T` / `Option+T`, or set `MAX_THINKING_TOKENS` environment variable:\n```bash\n# Toggle in-session: press Alt+T (Option+T on macOS)\n\n# Or set via environment variable\nMAX_THINKING_TOKENS=10000 claude\n\n# Then ask complex questions\nUser: Should we use microservices or monolith?\nClaude: [Analyzes trade-offs systematically with extended reasoning]\n```\n\n**Benefits**: Better architectural decisions, thorough analysis\n\n### Background Tasks\n\nRun long operations without blocking:\n```\nUser: Run tests in background\n\nClaude: Started bg-1234, you can continue working\n\n[Later] Test results: 245 passed, 3 failed\n```\n\n**Benefits**: Parallel development, no waiting\n\n### Permission Modes\n\nControl what Claude can do:\n- **`default`**: Standard permissions with confirmation prompts\n- **`acceptEdits`**: Auto-accept file edits, confirm other actions\n- **`plan`**: Analysis and planning only, no modifications\n- **`dontAsk`**: Accept all actions without confirmation\n- **`bypassPermissions`**: Skip all permission checks (dangerous)\n\n```bash\nclaude --permission-mode plan          # Code review mode\nclaude --permission-mode acceptEdits   # Learning mode\nclaude --permission-mode default       # Standard mode\n```\n\n### Headless Mode\n\nRun Claude Code in CI/CD and automation:\n```bash\nclaude -p \"Run tests and generate report\"\n```\n\n**Use Cases**: CI/CD, automated reviews, batch processing\n\n### Session Management\n\nManage multiple work sessions:\n```bash\n/resume                          # Resume a previous session interactively\n/rename                          # Rename the current session\n/fork                            # Fork the current session\nclaude -c                        # Continue the most recent session\nclaude -r \"session\"              # Resume a session matching the query\n```\n\n### Interactive Features\n\n**Keyboard Shortcuts**: Ctrl+R (search), Tab (complete), ↑/↓ (history)\n\n**Command History**: Access previous commands\n\n**Multi-line Input**: Complex prompts across multiple lines\n\n### Configuration\n\nCustomize Claude Code behavior in `~/.claude/settings.json`:\n```json\n{\n  \"permissions\": {\n    \"allow\": [\"Read\", \"Glob\", \"Grep\", \"Bash(git *)\"],\n    \"deny\": [\"Bash(rm -rf *)\"]\n  },\n  \"hooks\": {\n    \"PreToolUse\": [{\n      \"matcher\": \"Write\",\n      \"hooks\": [\"~/.claude/hooks/format-code.sh\"]\n    }]\n  },\n  \"env\": {\n    \"MAX_THINKING_TOKENS\": \"10000\"\n  }\n}\n```\n\nSee [config-examples.json](09-advanced-features/config-examples.json) for complete configurations.\n\n---\n\n## 10. CLI Reference\n\n**Location**: [10-cli/](10-cli/)\n\n**What**: Complete command-line interface reference for Claude Code\n\n**Key Areas**:\n- CLI commands (`claude`, `claude -p`, `claude -c`, `claude -r`)\n- Core flags (print mode, continue, resume, version)\n- Model & configuration (`--model`, `--agents`)\n- System prompt customization\n- Tool & permission management\n- Output formats (text, JSON, stream-JSON)\n- MCP configuration\n- Session management\n\n**Quick Examples**:\n```bash\n# Interactive mode\nclaude \"explain this project\"\n\n# Print mode (non-interactive)\nclaude -p \"review this code\"\n\n# Process file content\ncat error.log | claude -p \"explain this error\"\n\n# JSON output for scripts\nclaude -p --output-format json \"list functions\"\n\n# Resume session\nclaude -r \"feature-auth\" \"continue implementation\"\n```\n\n**Use Cases**:\n- CI/CD pipeline integration\n- Script automation and piping\n- Batch processing\n- Multi-session workflows\n- Custom agent configurations\n\n---\n\n## Directory Structure\n\n```\n\n├── 01-slash-commands/\n│   ├── optimize.md\n│   ├── pr.md\n│   ├── generate-api-docs.md\n│   └── README.md\n├── 02-memory/\n│   ├── project-CLAUDE.md\n│   ├── directory-api-CLAUDE.md\n│   ├── personal-CLAUDE.md\n│   └── README.md\n├── 03-skills/\n│   ├── code-review/\n│   │   ├── SKILL.md\n│   │   ├── scripts/\n│   │   └── templates/\n│   ├── brand-voice/\n│   │   ├── SKILL.md\n│   │   └── templates/\n│   ├── doc-generator/\n│   │   ├── SKILL.md\n│   │   └── generate-docs.py\n│   └── README.md\n├── 04-subagents/\n│   ├── code-reviewer.md\n│   ├── test-engineer.md\n│   ├── documentation-writer.md\n│   ├── secure-reviewer.md\n│   ├── implementation-agent.md\n│   └── README.md\n├── 05-mcp/\n│   ├── github-mcp.json\n│   ├── database-mcp.json\n│   ├── filesystem-mcp.json\n│   ├── multi-mcp.json\n│   └── README.md\n├── 06-hooks/\n│   ├── format-code.sh\n│   ├── pre-commit.sh\n│   ├── security-scan.sh\n│   ├── log-bash.sh\n│   ├── validate-prompt.sh\n│   ├── notify-team.sh\n│   └── README.md\n├── 07-plugins/\n│   ├── pr-review/\n│   ├── devops-automation/\n│   ├── documentation/\n│   └── README.md\n├── 08-checkpoints/\n│   ├── checkpoint-examples.md\n│   └── README.md\n├── 09-advanced-features/\n│   ├── config-examples.json\n│   ├── planning-mode-examples.md\n│   └── README.md\n├── 10-cli/\n│   └── README.md\n└── README.md (this file)\n```\n\n---\n\n## Installation Quick Reference\n\n```bash\n# Slash Commands\ncp 01-slash-commands/*.md .claude/commands/\n\n# Memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Skills\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Subagents\ncp 04-subagents/*.md .claude/agents/\n\n# MCP\nexport GITHUB_TOKEN=\"token\"\nclaude mcp add github -- npx -y @modelcontextprotocol/server-github\n\n# Hooks\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n\n# Plugins\n/plugin install pr-review\n\n# Checkpoints (auto-enabled, configure in settings)\n# See 08-checkpoints/README.md\n\n# Advanced Features (configure in settings)\n# See 09-advanced-features/config-examples.json\n\n# CLI Reference (no installation needed)\n# See 10-cli/README.md for usage examples\n```\n\n---\n\n## Example Workflows\n\n### 1. Complete Code Review Workflow\n\n```markdown\n# Uses: Slash Commands + Subagents + Memory + MCP\n\nUser: /review-pr\n\nClaude:\n1. Loads project memory (coding standards)\n2. Fetches PR via GitHub MCP\n3. Delegates to code-reviewer subagent\n4. Delegates to test-engineer subagent\n5. Synthesizes findings\n6. Provides comprehensive review\n```\n\n### 2. Automated Documentation\n\n```markdown\n# Uses: Skills + Subagents + Memory\n\nUser: \"Generate API documentation for the auth module\"\n\nClaude:\n1. Loads project memory (doc standards)\n2. Detects doc generation request\n3. Auto-invokes doc-generator skill\n4. Delegates to api-documenter subagent\n5. Creates comprehensive docs with examples\n```\n\n### 3. DevOps Deployment\n\n```markdown\n# Uses: Plugins + MCP + Hooks\n\nUser: /deploy production\n\nClaude:\n1. Runs pre-deploy hook (validates environment)\n2. Delegates to deployment-specialist subagent\n3. Executes deployment via Kubernetes MCP\n4. Monitors progress\n5. Runs post-deploy hook (health checks)\n6. Reports status\n```\n\n---\n\n## Best Practices\n\n### Do's ✅\n- Start simple with slash commands\n- Add features incrementally\n- Use memory for team standards\n- Test configurations locally first\n- Document custom implementations\n- Version control project configurations\n- Share plugins with team\n\n### Don'ts ❌\n- Don't create redundant features\n- Don't hardcode credentials\n- Don't skip documentation\n- Don't over-complicate simple tasks\n- Don't ignore security best practices\n- Don't commit sensitive data\n\n---\n\n## Troubleshooting\n\n### Feature Not Loading\n1. Check file location and naming\n2. Verify YAML frontmatter syntax\n3. Check file permissions\n4. Review Claude Code version compatibility\n\n### MCP Connection Failed\n1. Verify environment variables\n2. Check MCP server installation\n3. Test credentials\n4. Review network connectivity\n\n### Subagent Not Delegating\n1. Check tool permissions\n2. Verify agent description clarity\n3. Review task complexity\n6. Test agent independently\n\n---\n\n## Testing\n\nThis project includes comprehensive automated testing to ensure code quality and reliability.\n\n### Testing Overview\n\n- **Unit Tests**: Python tests using pytest (Python 3.10, 3.11, 3.12)\n- **Code Quality**: Linting and formatting with Ruff\n- **Security**: Vulnerability scanning with Bandit\n- **Type Checking**: Static type analysis with mypy\n- **Build Verification**: EPUB generation testing\n- **Coverage Tracking**: Codecov integration\n\n### Running Tests Locally\n\n```bash\n# Install development dependencies\nuv pip install -r requirements-dev.txt\n\n# Run all unit tests\npytest scripts/tests/ -v\n\n# Run tests with coverage report\npytest scripts/tests/ -v --cov=scripts --cov-report=html\n\n# Run code quality checks\nruff check scripts/\nruff format --check scripts/\n\n# Run security scan\nbandit -c pyproject.toml -r scripts/ --exclude scripts/tests/\n\n# Run type checking\nmypy scripts/ --ignore-missing-imports\n```\n\n### Automated Testing on GitHub\n\nTests run automatically on:\n- Every push to `main` or `develop` branches\n- Every pull request to `main`\n\nView test results in the GitHub Actions tab or check the [TESTING.md](.github/TESTING.md) guide for detailed information.\n\n### Writing Tests\n\nWhen contributing, please include tests for new functionality:\n\n1. **Write tests** in `scripts/tests/test_*.py`\n2. **Run tests locally** to verify they pass\n3. **Check coverage** with `pytest --cov=scripts`\n4. **Submit with PR** - tests are required for all contributions\n\nFor detailed testing guidelines, see [TESTING.md](.github/TESTING.md).\n\n---\n\n## Additional Resources\n\n- [Claude Code Documentation](https://code.claude.com/docs/en/overview)\n- [MCP Protocol Specification](https://modelcontextprotocol.io)\n- [Skills Repository](https://github.com/luongnv89/skills) - Collection of ready-to-use skills\n- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)\n- [Boris Cherny's Claude Code Workflow](https://x.com/bcherny/status/2007179832300581177) - The creator of Claude Code shares his systematized workflow: parallel agents, shared CLAUDE.md, Plan mode, slash commands, subagents, and verification hooks for autonomous long-running sessions. Key insights include turning recurring workflows into reusable commands and wiring Claude into team tools (GitHub, Slack, BigQuery, Sentry) for end-to-end work with feedback loops.\n\n---\n\n## Contributing\n\nFound an issue or want to contribute an example? We'd love your help!\n\n**Please read [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:**\n- Types of contributions (examples, docs, features, bugs, feedback)\n- How to set up your development environment\n- Directory structure and how to add content\n- Writing guidelines and best practices\n- Commit and PR process\n\n**Our Community Standards:**\n- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - How we treat each other\n- [SECURITY.md](SECURITY.md) - Security policy and vulnerability reporting\n\n### Reporting Security Issues\n\nIf you discover a security vulnerability, please report it responsibly:\n\n1. **Use GitHub Private Vulnerability Reporting**: https://github.com/luongnv89/claude-howto/security/advisories\n2. **Or read** [.github/SECURITY_REPORTING.md](.github/SECURITY_REPORTING.md) for detailed instructions\n3. **Do NOT** open a public issue for security vulnerabilities\n\nSecurity issues are taken seriously and will be addressed promptly. See [SECURITY.md](SECURITY.md) for our full security policy.\n\nQuick start:\n1. Fork and clone the repository\n2. Create a descriptive branch (`add/feature-name`, `fix/bug`, `docs/improvement`)\n3. Make your changes following the guidelines\n4. Submit a pull request with a clear description\n\n**Need help?** Open an issue or discussion, and we'll guide you through the process.\n\n---\n\n## License\n\nThis project is licensed under the MIT License - see [LICENSE](LICENSE) file for details.\n\nYou are free to:\n- Use this guide and examples in your projects\n- Modify and adapt the content\n- Share and distribute\n- Use for commercial purposes\n\nThe only requirement is to include a copy of the license and copyright notice.\n\n---\n\n## EPUB Generation\n\nWant to read this guide offline? Generate an EPUB ebook:\n\n```bash\nuv run scripts/build_epub.py\n```\n\nThis creates `claude-howto-guide.epub` with all content, including rendered Mermaid diagrams.\n\nSee [scripts/README.md](scripts/README.md) for more options.\n\n---\n\n## Contributors\n\nThanks to everyone who has contributed to this project!\n\n| Contributor | PRs |\n|-------------|-----|\n| [wjhrdy](https://github.com/wjhrdy) | [#1 - add a tool to create an epub](https://github.com/luongnv89/claude-howto/pull/1) |\n| [VikalpP](https://github.com/VikalpP) | [#7 - fix(docs): Use tilde fences for nested code blocks in concepts guide](https://github.com/luongnv89/claude-howto/pull/7) |\n\n---\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=luongnv89/claude-howto&type=Date)](https://star-history.com/#luongnv89/claude-howto&Date)\n\n---\n\n**Last Updated**: March 2026\n**Claude Code Version**: 2.1+\n**Compatible Models**: Claude Sonnet 4.6, Claude Opus 4.6, Claude Haiku 4.5\n"
  },
  {
    "path": "README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n[![GitHub Stars](https://img.shields.io/github/stars/luongnv89/claude-howto?style=flat&color=gold)](https://github.com/luongnv89/claude-howto/stargazers)\n[![GitHub Forks](https://img.shields.io/github/forks/luongnv89/claude-howto?style=flat)](https://github.com/luongnv89/claude-howto/network/members)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![Version](https://img.shields.io/badge/version-2.2.0-brightgreen)](CHANGELOG.md)\n[![Claude Code](https://img.shields.io/badge/Claude_Code-2.1+-purple)](https://code.claude.com)\n\n# Master Claude Code in a Weekend\n\nGo from typing `claude` to orchestrating agents, hooks, skills, and MCP servers — with visual tutorials, copy-paste templates, and a guided learning path.\n\n**[Get Started in 15 Minutes](#-get-started-in-15-minutes)** | **[Find Your Level](#-not-sure-where-to-start)** | **[Browse the Feature Catalog](CATALOG.md)**\n\n---\n\n## Table of Contents\n\n- [The Problem](#the-problem)\n- [How Claude How To Fixes This](#how-claude-how-to-fixes-this)\n- [How It Works](#how-it-works)\n- [Not Sure Where to Start?](#-not-sure-where-to-start)\n- [Get Started in 15 Minutes](#-get-started-in-15-minutes)\n- [What Can You Build With This?](#what-can-you-build-with-this)\n- [FAQ](#faq)\n- [Contributing](#contributing)\n- [License](#license)\n\n---\n\n## The Problem\n\nYou installed Claude Code. You ran a few prompts. Now what?\n\n- **The official docs describe features — but don't show you how to combine them.** You know slash commands exist, but not how to chain them with hooks, memory, and subagents into a workflow that actually saves hours.\n- **There's no clear learning path.** Should you learn MCP before hooks? Skills before subagents? You end up skimming everything and mastering nothing.\n- **Examples are too basic.** A \"hello world\" slash command doesn't help you build a production code review pipeline that uses memory, delegates to specialized agents, and runs security scans automatically.\n\nYou're leaving 90% of Claude Code's power on the table — and you don't know what you don't know.\n\n---\n\n## How Claude How To Fixes This\n\nThis isn't another feature reference. It's a **structured, visual, example-driven guide** that teaches you to use every Claude Code feature with real-world templates you can copy into your project today.\n\n| | Official Docs | This Guide |\n|--|---------------|------------|\n| **Format** | Reference documentation | Visual tutorials with Mermaid diagrams |\n| **Depth** | Feature descriptions | How it works under the hood |\n| **Examples** | Basic snippets | Production-ready templates you use immediately |\n| **Structure** | Feature-organized | Progressive learning path (beginner to advanced) |\n| **Onboarding** | Self-directed | Guided roadmap with time estimates |\n| **Self-Assessment** | None | Interactive quizzes to find your gaps and build a personalized path |\n\n### What you get:\n\n- **10 tutorial modules** covering every Claude Code feature — from slash commands to custom agent teams\n- **Copy-paste configs** — slash commands, CLAUDE.md templates, hook scripts, MCP configs, subagent definitions, and full plugin bundles\n- **Mermaid diagrams** showing how each feature works internally, so you understand *why*, not just *how*\n- **A guided learning path** that takes you from beginner to power user in 11-13 hours\n- **Built-in self-assessment** — run `/self-assessment` or `/lesson-quiz hooks` directly in Claude Code to identify gaps\n\n**[Start the Learning Path  ->](LEARNING-ROADMAP.md)**\n\n---\n\n## How It Works\n\n### 1. Find your level\n\nTake the [self-assessment quiz](LEARNING-ROADMAP.md#-find-your-level) or run `/self-assessment` in Claude Code. Get a personalized roadmap based on what you already know.\n\n### 2. Follow the guided path\n\nWork through 10 modules in order — each builds on the last. Copy templates directly into your project as you learn.\n\n### 3. Combine features into workflows\n\nThe real power is in combining features. Learn to wire slash commands + memory + subagents + hooks into automated pipelines that handle code reviews, deployments, and documentation generation.\n\n### 4. Test your understanding\n\nRun `/lesson-quiz [topic]` after each module. The quiz pinpoints what you missed so you can fill gaps fast.\n\n**[Get Started in 15 Minutes](#-get-started-in-15-minutes)**\n\n---\n\n## Trusted by 5,900+ Developers\n\n- **5,900+ GitHub stars** from developers who use Claude Code daily\n- **690+ forks** — teams adapting this guide for their own workflows\n- **Actively maintained** — synced with every Claude Code release (latest: v2.2.0, March 2026)\n- **Community-driven** — contributions from developers who share their real-world configurations\n\n[![Star History Chart](https://api.star-history.com/svg?repos=luongnv89/claude-howto&type=Date)](https://star-history.com/#luongnv89/claude-howto&Date)\n\n---\n\n## Not Sure Where to Start?\n\nTake the self-assessment or pick your level:\n\n| Level | You can... | Start here | Time |\n|-------|-----------|------------|------|\n| **Beginner** | Start Claude Code and chat | [Slash Commands](01-slash-commands/) | ~2.5 hours |\n| **Intermediate** | Use CLAUDE.md and custom commands | [Skills](03-skills/) | ~3.5 hours |\n| **Advanced** | Configure MCP servers and hooks | [Advanced Features](09-advanced-features/) | ~5 hours |\n\n**Full learning path with all 10 modules:**\n\n| Order | Module | Level | Time |\n|-------|--------|-------|------|\n| 1 | [Slash Commands](01-slash-commands/) | Beginner | 30 min |\n| 2 | [Memory](02-memory/) | Beginner+ | 45 min |\n| 3 | [Checkpoints](08-checkpoints/) | Intermediate | 45 min |\n| 4 | [CLI Basics](10-cli/) | Beginner+ | 30 min |\n| 5 | [Skills](03-skills/) | Intermediate | 1 hour |\n| 6 | [Hooks](06-hooks/) | Intermediate | 1 hour |\n| 7 | [MCP](05-mcp/) | Intermediate+ | 1 hour |\n| 8 | [Subagents](04-subagents/) | Intermediate+ | 1.5 hours |\n| 9 | [Advanced Features](09-advanced-features/) | Advanced | 2-3 hours |\n| 10 | [Plugins](07-plugins/) | Advanced | 2 hours |\n\n**[Complete Learning Roadmap ->](LEARNING-ROADMAP.md)**\n\n---\n\n## Get Started in 15 Minutes\n\n```bash\n# 1. Clone the guide\ngit clone https://github.com/luongnv89/claude-howto.git\ncd claude-howto\n\n# 2. Copy your first slash command\nmkdir -p /path/to/your-project/.claude/commands\ncp 01-slash-commands/optimize.md /path/to/your-project/.claude/commands/\n\n# 3. Try it — in Claude Code, type:\n# /optimize\n\n# 4. Ready for more? Set up project memory:\ncp 02-memory/project-CLAUDE.md /path/to/your-project/CLAUDE.md\n\n# 5. Install a skill:\ncp -r 03-skills/code-review ~/.claude/skills/\n```\n\nWant the full setup? Here's the **1-hour essential setup**:\n\n```bash\n# Slash commands (15 min)\ncp 01-slash-commands/*.md .claude/commands/\n\n# Project memory (15 min)\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Install a skill (15 min)\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Weekend goal: add hooks, subagents, MCP, and plugins\n# Follow the learning path for guided setup\n```\n\n**[View the Full Installation Reference](#installation-quick-reference)**\n\n---\n\n## What Can You Build With This?\n\n| Use Case | Features You'll Combine |\n|----------|------------------------|\n| **Automated Code Review** | Slash Commands + Subagents + Memory + MCP |\n| **Team Onboarding** | Memory + Slash Commands + Plugins |\n| **CI/CD Automation** | CLI Reference + Hooks + Background Tasks |\n| **Documentation Generation** | Skills + Subagents + Plugins |\n| **Security Audits** | Subagents + Skills + Hooks (read-only mode) |\n| **DevOps Pipelines** | Plugins + MCP + Hooks + Background Tasks |\n| **Complex Refactoring** | Checkpoints + Planning Mode + Hooks |\n\n---\n\n## FAQ\n\n**Is this free?**\nYes. MIT licensed, free forever. Use it in personal projects, at work, in your team — no restrictions beyond including the license notice.\n\n**Is this maintained?**\nActively. The guide is synced with every Claude Code release. Current version: v2.2.0 (March 2026), compatible with Claude Code 2.1+.\n\n**How is this different from the official docs?**\nThe official docs are a feature reference. This guide is a tutorial with diagrams, production-ready templates, and a progressive learning path. They complement each other — start here to learn, reference the docs when you need specifics.\n\n**How long does it take to go through everything?**\n11-13 hours for the full path. But you'll get immediate value in 15 minutes — just copy a slash command template and try it.\n\n**Can I use this with Claude Sonnet / Haiku / Opus?**\nYes. All templates work with Claude Sonnet 4.6, Claude Opus 4.6, and Claude Haiku 4.5.\n\n**Can I contribute?**\nAbsolutely. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. We welcome new examples, bug fixes, documentation improvements, and community templates.\n\n**Can I read this offline?**\nYes. Run `uv run scripts/build_epub.py` to generate an EPUB ebook with all content and rendered diagrams.\n\n---\n\n## Start Mastering Claude Code Today\n\nYou already have Claude Code installed. The only thing between you and 10x productivity is knowing how to use it. This guide gives you the structured path, the visual explanations, and the copy-paste templates to get there.\n\nMIT licensed. Free forever. Clone it, fork it, make it yours.\n\n**[Start the Learning Path ->](LEARNING-ROADMAP.md)** | **[Browse the Feature Catalog](CATALOG.md)** | **[Get Started in 15 Minutes](#-get-started-in-15-minutes)**\n\n---\n\n<details>\n<summary>Quick Navigation — All Features</summary>\n\n| Feature | Description | Folder |\n|---------|-------------|--------|\n| **Feature Catalog** | Complete reference with installation commands | [CATALOG.md](CATALOG.md) |\n| **Slash Commands** | User-invoked shortcuts | [01-slash-commands/](01-slash-commands/) |\n| **Memory** | Persistent context | [02-memory/](02-memory/) |\n| **Skills** | Reusable capabilities | [03-skills/](03-skills/) |\n| **Subagents** | Specialized AI assistants | [04-subagents/](04-subagents/) |\n| **MCP Protocol** | External tool access | [05-mcp/](05-mcp/) |\n| **Hooks** | Event-driven automation | [06-hooks/](06-hooks/) |\n| **Plugins** | Bundled features | [07-plugins/](07-plugins/) |\n| **Checkpoints** | Session snapshots & rewind | [08-checkpoints/](08-checkpoints/) |\n| **Advanced Features** | Planning, thinking, background tasks | [09-advanced-features/](09-advanced-features/) |\n| **CLI Reference** | Commands, flags, and options | [10-cli/](10-cli/) |\n| **Blog Posts** | Real-world usage examples | [Blog Posts](https://medium.com/@luongnv89) |\n\n</details>\n\n<details>\n<summary>Feature Comparison</summary>\n\n| Feature | Invocation | Persistence | Best For |\n|---------|-----------|------------|----------|\n| **Slash Commands** | Manual (`/cmd`) | Session only | Quick shortcuts |\n| **Memory** | Auto-loaded | Cross-session | Long-term learning |\n| **Skills** | Auto-invoked | Filesystem | Automated workflows |\n| **Subagents** | Auto-delegated | Isolated context | Task distribution |\n| **MCP Protocol** | Auto-queried | Real-time | Live data access |\n| **Hooks** | Event-triggered | Configured | Automation & validation |\n| **Plugins** | One command | All features | Complete solutions |\n| **Checkpoints** | Manual/Auto | Session-based | Safe experimentation |\n| **Planning Mode** | Manual/Auto | Plan phase | Complex implementations |\n| **Background Tasks** | Manual | Task duration | Long-running operations |\n| **CLI Reference** | Terminal commands | Session/Script | Automation & scripting |\n\n</details>\n\n<details>\n<summary>Installation Quick Reference</summary>\n\n```bash\n# Slash Commands\ncp 01-slash-commands/*.md .claude/commands/\n\n# Memory\ncp 02-memory/project-CLAUDE.md ./CLAUDE.md\n\n# Skills\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Subagents\ncp 04-subagents/*.md .claude/agents/\n\n# MCP\nexport GITHUB_TOKEN=\"token\"\nclaude mcp add github -- npx -y @modelcontextprotocol/server-github\n\n# Hooks\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n\n# Plugins\n/plugin install pr-review\n\n# Checkpoints (auto-enabled, configure in settings)\n# See 08-checkpoints/README.md\n\n# Advanced Features (configure in settings)\n# See 09-advanced-features/config-examples.json\n\n# CLI Reference (no installation needed)\n# See 10-cli/README.md for usage examples\n```\n\n</details>\n\n<details>\n<summary>01. Slash Commands</summary>\n\n**Location**: [01-slash-commands/](01-slash-commands/)\n\n**What**: User-invoked shortcuts stored as Markdown files\n\n**Examples**:\n- `optimize.md` - Code optimization analysis\n- `pr.md` - Pull request preparation\n- `generate-api-docs.md` - API documentation generator\n\n**Installation**:\n```bash\ncp 01-slash-commands/*.md /path/to/project/.claude/commands/\n```\n\n**Usage**:\n```\n/optimize\n/pr\n/generate-api-docs\n```\n\n**Learn More**: [Discovering Claude Code Slash Commands](https://medium.com/@luongnv89/discovering-claude-code-slash-commands-cdc17f0dfb29)\n\n</details>\n\n<details>\n<summary>02. Memory</summary>\n\n**Location**: [02-memory/](02-memory/)\n\n**What**: Persistent context across sessions\n\n**Examples**:\n- `project-CLAUDE.md` - Team-wide project standards\n- `directory-api-CLAUDE.md` - Directory-specific rules\n- `personal-CLAUDE.md` - Personal preferences\n\n**Installation**:\n```bash\n# Project memory\ncp 02-memory/project-CLAUDE.md /path/to/project/CLAUDE.md\n\n# Directory memory\ncp 02-memory/directory-api-CLAUDE.md /path/to/project/src/api/CLAUDE.md\n\n# Personal memory\ncp 02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md\n```\n\n**Usage**: Automatically loaded by Claude\n\n</details>\n\n<details>\n<summary>03. Skills</summary>\n\n**Location**: [03-skills/](03-skills/)\n\n**What**: Reusable, auto-invoked capabilities with instructions and scripts\n\n**Examples**:\n- `code-review/` - Comprehensive code review with scripts\n- `brand-voice/` - Brand voice consistency checker\n- `doc-generator/` - API documentation generator\n\n**Installation**:\n```bash\n# Personal skills\ncp -r 03-skills/code-review ~/.claude/skills/\n\n# Project skills\ncp -r 03-skills/code-review /path/to/project/.claude/skills/\n```\n\n**Usage**: Automatically invoked when relevant\n\n</details>\n\n<details>\n<summary>04. Subagents</summary>\n\n**Location**: [04-subagents/](04-subagents/)\n\n**What**: Specialized AI assistants with isolated contexts and custom prompts\n\n**Examples**:\n- `code-reviewer.md` - Comprehensive code quality analysis\n- `test-engineer.md` - Test strategy and coverage\n- `documentation-writer.md` - Technical documentation\n- `secure-reviewer.md` - Security-focused review (read-only)\n- `implementation-agent.md` - Full feature implementation\n\n**Installation**:\n```bash\ncp 04-subagents/*.md /path/to/project/.claude/agents/\n```\n\n**Usage**: Automatically delegated by main agent\n\n</details>\n\n<details>\n<summary>05. MCP Protocol</summary>\n\n**Location**: [05-mcp/](05-mcp/)\n\n**What**: Model Context Protocol for accessing external tools and APIs\n\n**Examples**:\n- `github-mcp.json` - GitHub integration\n- `database-mcp.json` - Database queries\n- `filesystem-mcp.json` - File operations\n- `multi-mcp.json` - Multiple MCP servers\n\n**Installation**:\n```bash\n# Set environment variables\nexport GITHUB_TOKEN=\"your_token\"\nexport DATABASE_URL=\"postgresql://...\"\n\n# Add MCP server via CLI\nclaude mcp add github -- npx -y @modelcontextprotocol/server-github\n\n# Or add to project .mcp.json manually (see 05-mcp/ for examples)\n```\n\n**Usage**: MCP tools are automatically available to Claude once configured\n\n</details>\n\n<details>\n<summary>06. Hooks</summary>\n\n**Location**: [06-hooks/](06-hooks/)\n\n**What**: Event-driven shell commands that execute automatically in response to Claude Code events\n\n**Examples**:\n- `format-code.sh` - Auto-format code before writing\n- `pre-commit.sh` - Run tests before commits\n- `security-scan.sh` - Scan for security issues\n- `log-bash.sh` - Log all bash commands\n- `validate-prompt.sh` - Validate user prompts\n- `notify-team.sh` - Send notifications on events\n\n**Installation**:\n```bash\nmkdir -p ~/.claude/hooks\ncp 06-hooks/*.sh ~/.claude/hooks/\nchmod +x ~/.claude/hooks/*.sh\n```\n\nConfigure hooks in `~/.claude/settings.json`:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [{\n      \"matcher\": \"Write\",\n      \"hooks\": [\"~/.claude/hooks/format-code.sh\"]\n    }],\n    \"PostToolUse\": [{\n      \"matcher\": \"Write\",\n      \"hooks\": [\"~/.claude/hooks/security-scan.sh\"]\n    }]\n  }\n}\n```\n\n**Usage**: Hooks execute automatically on events\n\n**Hook Types** (4 types, 25 events):\n- **Tool Hooks**: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`\n- **Session Hooks**: `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `SubagentStart`, `SubagentStop`\n- **Task Hooks**: `UserPromptSubmit`, `TaskCompleted`, `TaskCreated`, `TeammateIdle`\n- **Lifecycle Hooks**: `ConfigChange`, `CwdChanged`, `FileChanged`, `PreCompact`, `PostCompact`, `WorktreeCreate`, `WorktreeRemove`, `Notification`, `InstructionsLoaded`, `Elicitation`, `ElicitationResult`\n\n</details>\n\n<details>\n<summary>07. Plugins</summary>\n\n**Location**: [07-plugins/](07-plugins/)\n\n**What**: Bundled collections of commands, agents, MCP, and hooks\n\n**Examples**:\n- `pr-review/` - Complete PR review workflow\n- `devops-automation/` - Deployment and monitoring\n- `documentation/` - Documentation generation\n\n**Installation**:\n```bash\n/plugin install pr-review\n/plugin install devops-automation\n/plugin install documentation\n```\n\n**Usage**: Use bundled slash commands and features\n\n</details>\n\n<details>\n<summary>08. Checkpoints and Rewind</summary>\n\n**Location**: [08-checkpoints/](08-checkpoints/)\n\n**What**: Save conversation state and rewind to previous points to explore different approaches\n\n**Key Concepts**:\n- **Checkpoint**: Snapshot of conversation state\n- **Rewind**: Return to previous checkpoint\n- **Branch Point**: Explore multiple approaches from same checkpoint\n\n**Usage**:\n```\n# Checkpoints are created automatically with every user prompt\n# To rewind, press Esc twice or use:\n/rewind\n\n# Then choose from five options:\n# 1. Restore code and conversation\n# 2. Restore conversation\n# 3. Restore code\n# 4. Summarize from here\n# 5. Never mind\n```\n\n**Use Cases**:\n- Try different implementation approaches\n- Recover from mistakes\n- Safe experimentation\n- Compare alternative solutions\n- A/B testing different designs\n\n</details>\n\n<details>\n<summary>09. Advanced Features</summary>\n\n**Location**: [09-advanced-features/](09-advanced-features/)\n\n**What**: Advanced capabilities for complex workflows and automation\n\n**Includes**:\n- **Planning Mode** — Create detailed implementation plans before coding\n- **Extended Thinking** — Deep reasoning for complex problems (toggle with `Alt+T` / `Option+T`)\n- **Background Tasks** — Run long operations without blocking\n- **Permission Modes** — `default`, `acceptEdits`, `plan`, `dontAsk`, `bypassPermissions`\n- **Headless Mode** — Run Claude Code in CI/CD: `claude -p \"Run tests and generate report\"`\n- **Session Management** — `/resume`, `/rename`, `/fork`, `claude -c`, `claude -r`\n- **Configuration** — Customize behavior in `~/.claude/settings.json`\n\nSee [config-examples.json](09-advanced-features/config-examples.json) for complete configurations.\n\n</details>\n\n<details>\n<summary>10. CLI Reference</summary>\n\n**Location**: [10-cli/](10-cli/)\n\n**What**: Complete command-line interface reference for Claude Code\n\n**Quick Examples**:\n```bash\n# Interactive mode\nclaude \"explain this project\"\n\n# Print mode (non-interactive)\nclaude -p \"review this code\"\n\n# Process file content\ncat error.log | claude -p \"explain this error\"\n\n# JSON output for scripts\nclaude -p --output-format json \"list functions\"\n\n# Resume session\nclaude -r \"feature-auth\" \"continue implementation\"\n```\n\n**Use Cases**: CI/CD pipeline integration, script automation, batch processing, multi-session workflows, custom agent configurations\n\n</details>\n\n<details>\n<summary>Example Workflows</summary>\n\n### Complete Code Review Workflow\n\n```markdown\n# Uses: Slash Commands + Subagents + Memory + MCP\n\nUser: /review-pr\n\nClaude:\n1. Loads project memory (coding standards)\n2. Fetches PR via GitHub MCP\n3. Delegates to code-reviewer subagent\n4. Delegates to test-engineer subagent\n5. Synthesizes findings\n6. Provides comprehensive review\n```\n\n### Automated Documentation\n\n```markdown\n# Uses: Skills + Subagents + Memory\n\nUser: \"Generate API documentation for the auth module\"\n\nClaude:\n1. Loads project memory (doc standards)\n2. Detects doc generation request\n3. Auto-invokes doc-generator skill\n4. Delegates to api-documenter subagent\n5. Creates comprehensive docs with examples\n```\n\n### DevOps Deployment\n\n```markdown\n# Uses: Plugins + MCP + Hooks\n\nUser: /deploy production\n\nClaude:\n1. Runs pre-deploy hook (validates environment)\n2. Delegates to deployment-specialist subagent\n3. Executes deployment via Kubernetes MCP\n4. Monitors progress\n5. Runs post-deploy hook (health checks)\n6. Reports status\n```\n\n</details>\n\n<details>\n<summary>Directory Structure</summary>\n\n```\n├── 01-slash-commands/\n│   ├── optimize.md\n│   ├── pr.md\n│   ├── generate-api-docs.md\n│   └── README.md\n├── 02-memory/\n│   ├── project-CLAUDE.md\n│   ├── directory-api-CLAUDE.md\n│   ├── personal-CLAUDE.md\n│   └── README.md\n├── 03-skills/\n│   ├── code-review/\n│   │   ├── SKILL.md\n│   │   ├── scripts/\n│   │   └── templates/\n│   ├── brand-voice/\n│   │   ├── SKILL.md\n│   │   └── templates/\n│   ├── doc-generator/\n│   │   ├── SKILL.md\n│   │   └── generate-docs.py\n│   └── README.md\n├── 04-subagents/\n│   ├── code-reviewer.md\n│   ├── test-engineer.md\n│   ├── documentation-writer.md\n│   ├── secure-reviewer.md\n│   ├── implementation-agent.md\n│   └── README.md\n├── 05-mcp/\n│   ├── github-mcp.json\n│   ├── database-mcp.json\n│   ├── filesystem-mcp.json\n│   ├── multi-mcp.json\n│   └── README.md\n├── 06-hooks/\n│   ├── format-code.sh\n│   ├── pre-commit.sh\n│   ├── security-scan.sh\n│   ├── log-bash.sh\n│   ├── validate-prompt.sh\n│   ├── notify-team.sh\n│   └── README.md\n├── 07-plugins/\n│   ├── pr-review/\n│   ├── devops-automation/\n│   ├── documentation/\n│   └── README.md\n├── 08-checkpoints/\n│   ├── checkpoint-examples.md\n│   └── README.md\n├── 09-advanced-features/\n│   ├── config-examples.json\n│   ├── planning-mode-examples.md\n│   └── README.md\n├── 10-cli/\n│   └── README.md\n└── README.md (this file)\n```\n\n</details>\n\n<details>\n<summary>Best Practices</summary>\n\n### Do's\n- Start simple with slash commands\n- Add features incrementally\n- Use memory for team standards\n- Test configurations locally first\n- Document custom implementations\n- Version control project configurations\n- Share plugins with team\n\n### Don'ts\n- Don't create redundant features\n- Don't hardcode credentials\n- Don't skip documentation\n- Don't over-complicate simple tasks\n- Don't ignore security best practices\n- Don't commit sensitive data\n\n</details>\n\n<details>\n<summary>Troubleshooting</summary>\n\n### Feature Not Loading\n1. Check file location and naming\n2. Verify YAML frontmatter syntax\n3. Check file permissions\n4. Review Claude Code version compatibility\n\n### MCP Connection Failed\n1. Verify environment variables\n2. Check MCP server installation\n3. Test credentials\n4. Review network connectivity\n\n### Subagent Not Delegating\n1. Check tool permissions\n2. Verify agent description clarity\n3. Review task complexity\n4. Test agent independently\n\n</details>\n\n<details>\n<summary>Testing</summary>\n\nThis project includes comprehensive automated testing:\n\n- **Unit Tests**: Python tests using pytest (Python 3.10, 3.11, 3.12)\n- **Code Quality**: Linting and formatting with Ruff\n- **Security**: Vulnerability scanning with Bandit\n- **Type Checking**: Static type analysis with mypy\n- **Build Verification**: EPUB generation testing\n- **Coverage Tracking**: Codecov integration\n\n```bash\n# Install development dependencies\nuv pip install -r requirements-dev.txt\n\n# Run all unit tests\npytest scripts/tests/ -v\n\n# Run tests with coverage report\npytest scripts/tests/ -v --cov=scripts --cov-report=html\n\n# Run code quality checks\nruff check scripts/\nruff format --check scripts/\n\n# Run security scan\nbandit -c pyproject.toml -r scripts/ --exclude scripts/tests/\n\n# Run type checking\nmypy scripts/ --ignore-missing-imports\n```\n\nTests run automatically on every push to `main`/`develop` and every PR to `main`. See [TESTING.md](.github/TESTING.md) for detailed information.\n\n</details>\n\n<details>\n<summary>EPUB Generation</summary>\n\nWant to read this guide offline? Generate an EPUB ebook:\n\n```bash\nuv run scripts/build_epub.py\n```\n\nThis creates `claude-howto-guide.epub` with all content, including rendered Mermaid diagrams.\n\nSee [scripts/README.md](scripts/README.md) for more options.\n\n</details>\n\n<details>\n<summary>Contributing</summary>\n\nFound an issue or want to contribute an example? We'd love your help!\n\n**Please read [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:**\n- Types of contributions (examples, docs, features, bugs, feedback)\n- How to set up your development environment\n- Directory structure and how to add content\n- Writing guidelines and best practices\n- Commit and PR process\n\n**Our Community Standards:**\n- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - How we treat each other\n- [SECURITY.md](SECURITY.md) - Security policy and vulnerability reporting\n\n### Reporting Security Issues\n\nIf you discover a security vulnerability, please report it responsibly:\n\n1. **Use GitHub Private Vulnerability Reporting**: https://github.com/luongnv89/claude-howto/security/advisories\n2. **Or read** [.github/SECURITY_REPORTING.md](.github/SECURITY_REPORTING.md) for detailed instructions\n3. **Do NOT** open a public issue for security vulnerabilities\n\nQuick start:\n1. Fork and clone the repository\n2. Create a descriptive branch (`add/feature-name`, `fix/bug`, `docs/improvement`)\n3. Make your changes following the guidelines\n4. Submit a pull request with a clear description\n\n**Need help?** Open an issue or discussion, and we'll guide you through the process.\n\n</details>\n\n<details>\n<summary>Additional Resources</summary>\n\n- [Claude Code Documentation](https://code.claude.com/docs/en/overview)\n- [MCP Protocol Specification](https://modelcontextprotocol.io)\n- [Skills Repository](https://github.com/luongnv89/skills) - Collection of ready-to-use skills\n- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)\n- [Boris Cherny's Claude Code Workflow](https://x.com/bcherny/status/2007179832300581177) - The creator of Claude Code shares his systematized workflow: parallel agents, shared CLAUDE.md, Plan mode, slash commands, subagents, and verification hooks for autonomous long-running sessions.\n\n</details>\n\n---\n\n## Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details on how to get started.\n\n## Contributors\n\nThanks to everyone who has contributed to this project!\n\n| Contributor | PRs |\n|-------------|-----|\n| [wjhrdy](https://github.com/wjhrdy) | [#1 - add a tool to create an epub](https://github.com/luongnv89/claude-howto/pull/1) |\n| [VikalpP](https://github.com/VikalpP) | [#7 - fix(docs): Use tilde fences for nested code blocks in concepts guide](https://github.com/luongnv89/claude-howto/pull/7) |\n\n---\n\n## License\n\nMIT License - see [LICENSE](LICENSE). Free to use, modify, and distribute. The only requirement is including the license notice.\n\n---\n\n**Last Updated**: March 2026\n**Claude Code Version**: 2.1+\n**Compatible Models**: Claude Sonnet 4.6, Claude Opus 4.6, Claude Haiku 4.5\n"
  },
  {
    "path": "RELEASE_NOTES.md",
    "content": "## v2.2.0 — 2026-03-26\n\n### Bug Fixes\n\n- Remove dead marketplace link failing CI link checks (3fdf0d6)\n- Add `sandboxed` and `pycache` to cSpell dictionary (dc64618)\n\n**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.1.0...v2.1.1\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Overview\n\nThe security of the Claude How To project is important to us. This document outlines our security practices and describes how to report security vulnerabilities responsibly.\n\n## Supported Versions\n\nWe provide security updates for the following versions:\n\n| Version | Status | Support Until |\n|---------|--------|---------------|\n| Latest (main) | ✅ Active | Current + 6 months |\n| 1.x releases | ✅ Active | Until next major version |\n\n**Note**: As an educational guide project, we focus on maintaining current best practices and documentation security rather than traditional version support. Updates are applied directly to the main branch.\n\n## Security Practices\n\n### Code Security\n\n1. **Dependency Management**\n   - All Python dependencies are pinned in `requirements.txt`\n   - Regular updates via dependabot and manual review\n   - Security scanning with Bandit on every commit\n   - Pre-commit hooks for security checks\n\n2. **Code Quality**\n   - Linting with Ruff catches common issues\n   - Type checking with mypy prevents type-related vulnerabilities\n   - Pre-commit hooks enforce standards\n   - All changes reviewed before merging\n\n3. **Access Control**\n   - Branch protection on `main` branch\n   - Required reviews before merge\n   - Status checks must pass before merge\n   - Limited write access to repository\n\n### Documentation Security\n\n1. **No Secrets in Examples**\n   - All API keys in examples are placeholders\n   - Credentials are never hardcoded\n   - `.env.example` files show required variables\n   - Clear warnings about secret management\n\n2. **Security Best Practices**\n   - Examples demonstrate secure patterns\n   - Security warnings highlighted in documentation\n   - Links to official security guides\n   - Credential handling discussed in relevant sections\n\n3. **Content Review**\n   - All documentation reviewed for security issues\n   - Security considerations in contributing guidelines\n   - Validation of external links and references\n\n### Dependency Security\n\n1. **Scanning**\n   - Bandit scans all Python code for vulnerabilities\n   - Dependency vulnerability checks via GitHub security alerts\n   - Regular manual security audits\n\n2. **Updates**\n   - Security patches applied promptly\n   - Major versions evaluated carefully\n   - Changelog includes security-related updates\n\n3. **Transparency**\n   - Security updates documented in commits\n   - Vulnerability disclosures handled responsibly\n   - Public security advisories when appropriate\n\n## Reporting a Vulnerability\n\n### Security Issues We Care About\n\nWe appreciate reports on:\n- **Code vulnerabilities** in scripts or examples\n- **Dependency vulnerabilities** in Python packages\n- **Cryptography issues** in any code examples\n- **Authentication/Authorization flaws** in documentation\n- **Data exposure risks** in configuration examples\n- **Injection vulnerabilities** (SQL, command, etc.)\n- **SSRF/XXE/Path traversal** issues\n\n### Security Issues Out of Scope\n\nThese are outside the scope of this project:\n- Vulnerabilities in Claude Code itself (report to Anthropic)\n- Issues with external services or libraries (report to upstream)\n- Social engineering or user education (not applicable to this guide)\n- Theoretical vulnerabilities without proof of concept\n- Vulnerabilities in dependencies reported through official channels\n\n## How to Report\n\n### Private Reporting (Preferred)\n\n**For sensitive security issues, please use GitHub's private vulnerability reporting:**\n\n1. Visit: https://github.com/luongnv89/claude-howto/security/advisories\n2. Click \"Report a vulnerability\"\n3. Fill in the vulnerability details\n4. Include:\n   - Clear description of the vulnerability\n   - Affected component (file, section, example)\n   - Potential impact\n   - Steps to reproduce (if applicable)\n   - Suggested fix (if you have one)\n\n**What happens next:**\n- We'll acknowledge receipt within 48 hours\n- We'll investigate and assess severity\n- We'll work with you to develop a fix\n- We'll coordinate disclosure timeline\n- We'll credit you in the security advisory (unless you prefer anonymity)\n\n### Public Reporting\n\nFor non-sensitive issues or those already public:\n\n1. **Open a GitHub Issue** with label `security`\n2. Include:\n   - Title: `[SECURITY]` followed by brief description\n   - Detailed description\n   - Affected file or section\n   - Potential impact\n   - Suggested fix\n\n## Vulnerability Response Process\n\n### Assessment (24 hours)\n\n1. We acknowledge receipt of the report\n2. We assess severity using [CVSS v3.1](https://www.first.org/cvss/v3.1/specification-document)\n3. We determine if it's in scope\n4. We contact you with initial assessment\n\n### Development (1-7 days)\n\n1. We develop a fix\n2. We review and test the fix\n3. We create a security advisory\n4. We prepare release notes\n\n### Disclosure (varies by severity)\n\n**Critical (CVSS 9.0-10.0)**\n- Fix released immediately\n- Public advisory issued\n- 24-hour advance notice to reporters\n\n**High (CVSS 7.0-8.9)**\n- Fix released within 48-72 hours\n- 5-day advance notice to reporters\n- Public advisory on release\n\n**Medium (CVSS 4.0-6.9)**\n- Fix released in next regular update\n- Public advisory on release\n\n**Low (CVSS 0.1-3.9)**\n- Fix included in next regular update\n- Advisory on release\n\n### Publication\n\nWe publish security advisories that include:\n- Description of the vulnerability\n- Affected components\n- Severity assessment (CVSS score)\n- Fix version\n- Workarounds (if applicable)\n- Credit to reporter (with permission)\n\n## Best Practices for Reporters\n\n### Before Reporting\n\n- **Verify the issue**: Can you reproduce it consistently?\n- **Search existing issues**: Is it already reported?\n- **Check documentation**: Is there guidance on secure usage?\n- **Test the fix**: Does your suggested fix work?\n\n### When Reporting\n\n- **Be specific**: Provide exact file paths and line numbers\n- **Include context**: Why is this a security issue?\n- **Show impact**: What could an attacker do?\n- **Provide steps**: How can we reproduce it?\n- **Suggest fixes**: How would you fix it?\n\n### After Reporting\n\n- **Be patient**: We have limited resources\n- **Be responsive**: Answer follow-up questions quickly\n- **Keep it confidential**: Don't publicly disclose before fix\n- **Respect coordination**: Follow our timeline for disclosure\n\n## Security Headers and Configuration\n\n### Repository Security\n\n- **Branch protection**: Main branch requires 2 approvals for changes\n- **Status checks**: All CI/CD checks must pass\n- **CODEOWNERS**: Designated reviewers for key files\n- **Signed commits**: Recommended for contributors\n\n### Development Security\n\n```bash\n# Install pre-commit hooks\npre-commit install\n\n# Run security scans locally\nbandit -c pyproject.toml -r scripts/\nmypy scripts/ --ignore-missing-imports\nruff check scripts/\n```\n\n### Dependency Security\n\n```bash\n# Check for known vulnerabilities\npip install safety\nsafety check\n\n# Or use pip-audit\npip install pip-audit\npip-audit\n```\n\n## Security Guidelines for Contributors\n\n### When Writing Examples\n\n1. **Never hardcode secrets**\n   ```python\n   # ❌ Bad\n   api_key = \"sk-1234567890\"\n\n   # ✅ Good\n   api_key = os.getenv(\"API_KEY\")\n   ```\n\n2. **Warn about security implications**\n   ```markdown\n   ⚠️ **Security Note**: Never commit `.env` files to git.\n   Add to `.gitignore` immediately.\n   ```\n\n3. **Use secure defaults**\n   - Enable authentication by default\n   - Use HTTPS where applicable\n   - Validate and sanitize inputs\n   - Use parameterized queries\n\n4. **Document security considerations**\n   - Explain why security matters\n   - Show secure vs. insecure patterns\n   - Link to authoritative sources\n   - Include warnings prominently\n\n### When Reviewing Contributions\n\n1. **Check for exposed secrets**\n   - Scan for common patterns (api_key=, password=)\n   - Review configuration files\n   - Check environment variables\n\n2. **Verify secure coding practices**\n   - No hardcoded credentials\n   - Proper input validation\n   - Secure authentication/authorization\n   - Safe file handling\n\n3. **Test security implications**\n   - Can this be misused?\n   - What's the worst case?\n   - Are there edge cases?\n\n## Security Resources\n\n### Official Standards\n- [OWASP Top 10](https://owasp.org/www-project-top-ten/)\n- [CWE Top 25](https://cwe.mitre.org/top25/)\n- [CVSS Calculator](https://www.first.org/cvss/calculator/3.1)\n\n### Python Security\n- [Python Security Advisories](https://www.python.org/dev/security/)\n- [PyPI Security](https://pypi.org/help/#security)\n- [Bandit Documentation](https://bandit.readthedocs.io/)\n\n### Dependency Management\n- [OWASP Dependency Check](https://owasp.org/www-project-dependency-check/)\n- [GitHub Security Alerts](https://docs.github.com/en/code-security/dependabot/dependabot-alerts/about-dependabot-alerts)\n\n### General Security\n- [Anthropic Security](https://www.anthropic.com/)\n- [GitHub Security Best Practices](https://docs.github.com/en/code-security)\n\n## Security Advisories Archive\n\nPast security advisories are available in the [GitHub Security Advisories](https://github.com/luongnv89/claude-howto/security/advisories) tab.\n\n## Contact\n\nFor security-related questions or to discuss security practices:\n\n1. **Private Security Report**: Use GitHub's private vulnerability reporting\n2. **General Security Questions**: Open a discussion with `[SECURITY]` tag\n3. **Security Policy Feedback**: Create an issue with `security` label\n\n## Acknowledgments\n\nWe appreciate the security researchers and community members who help keep this project secure. Contributors who report vulnerabilities responsibly will be acknowledged in our security advisories (unless they prefer anonymity).\n\n## Policy Updates\n\nThis security policy is reviewed and updated:\n- When new vulnerabilities are discovered\n- When security best practices evolve\n- When the project scope changes\n- Annually as a minimum\n\n**Last Updated**: January 2026\n**Next Review**: January 2027\n\n---\n\nThank you for helping keep Claude How To secure! 🔒\n"
  },
  {
    "path": "STYLE_GUIDE.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Style Guide\n\n> Conventions and formatting rules for contributing to Claude How To. Follow this guide to keep content consistent, professional, and easy to maintain.\n\n---\n\n## Table of Contents\n\n- [File and Folder Naming](#file-and-folder-naming)\n- [Document Structure](#document-structure)\n- [Headings](#headings)\n- [Text Formatting](#text-formatting)\n- [Lists](#lists)\n- [Tables](#tables)\n- [Code Blocks](#code-blocks)\n- [Links and Cross-References](#links-and-cross-references)\n- [Diagrams](#diagrams)\n- [Emoji Usage](#emoji-usage)\n- [YAML Frontmatter](#yaml-frontmatter)\n- [Images and Media](#images-and-media)\n- [Tone and Voice](#tone-and-voice)\n- [Commit Messages](#commit-messages)\n- [Checklist for Authors](#checklist-for-authors)\n\n---\n\n## File and Folder Naming\n\n### Lesson Folders\n\nLesson folders use a **two-digit numbered prefix** followed by a **kebab-case** descriptor:\n\n```\n01-slash-commands/\n02-memory/\n03-skills/\n04-subagents/\n05-mcp/\n```\n\nThe number reflects the learning path order from beginner to advanced.\n\n### File Names\n\n| Type | Convention | Examples |\n|------|-----------|----------|\n| **Lesson README** | `README.md` | `01-slash-commands/README.md` |\n| **Feature file** | Kebab-case `.md` | `code-reviewer.md`, `generate-api-docs.md` |\n| **Shell script** | Kebab-case `.sh` | `format-code.sh`, `validate-input.sh` |\n| **Config file** | Standard names | `.mcp.json`, `settings.json` |\n| **Memory file** | Scope-prefixed | `project-CLAUDE.md`, `personal-CLAUDE.md` |\n| **Top-level docs** | UPPER_CASE `.md` | `CATALOG.md`, `QUICK_REFERENCE.md`, `CONTRIBUTING.md` |\n| **Image assets** | Kebab-case | `pr-slash-command.png`, `claude-howto-logo.svg` |\n\n### Rules\n\n- Use **lowercase** for all file and folder names (except top-level docs like `README.md`, `CATALOG.md`)\n- Use **hyphens** (`-`) as word separators, never underscores or spaces\n- Keep names descriptive but concise\n\n---\n\n## Document Structure\n\n### Root README\n\nThe root `README.md` follows this order:\n\n1. Logo (`<picture>` element with dark/light variants)\n2. H1 title\n3. Introductory blockquote (one-line value proposition)\n4. \"Why This Guide?\" section with comparison table\n5. Horizontal rule (`---`)\n6. Table of Contents\n7. Feature Catalog\n8. Quick Navigation\n9. Learning Path\n10. Feature sections\n11. Getting Started\n12. Best Practices / Troubleshooting\n13. Contributing / License\n\n### Lesson README\n\nEach lesson `README.md` follows this order:\n\n1. H1 title (e.g., `# Slash Commands`)\n2. Brief overview paragraph\n3. Quick reference table (optional)\n4. Architecture diagram (Mermaid)\n5. Detailed sections (H2)\n6. Practical examples (numbered, 4-6 examples)\n7. Best practices (Do's and Don'ts tables)\n8. Troubleshooting\n9. Related guides / Official documentation\n10. Document metadata footer\n\n### Feature/Example File\n\nIndividual feature files (e.g., `optimize.md`, `pr.md`):\n\n1. YAML frontmatter (if applicable)\n2. H1 title\n3. Purpose / description\n4. Usage instructions\n5. Code examples\n6. Customization tips\n\n### Section Separators\n\nUse horizontal rules (`---`) to separate major document regions:\n\n```markdown\n---\n\n## New Major Section\n```\n\nPlace them after the introductory blockquote and between logically distinct parts of the document.\n\n---\n\n## Headings\n\n### Hierarchy\n\n| Level | Use | Example |\n|-------|-----|---------|\n| `#` H1 | Page title (one per document) | `# Slash Commands` |\n| `##` H2 | Major sections | `## Best Practices` |\n| `###` H3 | Subsections | `### Adding a Skill` |\n| `####` H4 | Sub-subsections (rare) | `#### Configuration Options` |\n\n### Rules\n\n- **One H1 per document** — the page title only\n- **Never skip levels** — don't jump from H2 to H4\n- **Keep headings concise** — aim for 2-5 words\n- **Use sentence case** — capitalize first word and proper nouns only (exception: feature names stay as-is)\n- **Add emoji prefixes only on root README** section headers (see [Emoji Usage](#emoji-usage))\n\n---\n\n## Text Formatting\n\n### Emphasis\n\n| Style | When to Use | Example |\n|-------|------------|---------|\n| **Bold** (`**text**`) | Key terms, labels in tables, important concepts | `**Installation**:` |\n| *Italic* (`*text*`) | First use of a technical term, book/doc titles | `*frontmatter*` |\n| `Code` (`` `text` ``) | File names, commands, config values, code references | `` `CLAUDE.md` `` |\n\n### Blockquotes for Callouts\n\nUse blockquotes with bold prefixes for important notes:\n\n```markdown\n> **Note**: Custom slash commands have been merged into skills since v2.0.\n\n> **Important**: Never commit API keys or credentials.\n\n> **Tip**: Combine memory with skills for maximum effectiveness.\n```\n\nSupported callout types: **Note**, **Important**, **Tip**, **Warning**.\n\n### Paragraphs\n\n- Keep paragraphs short (2-4 sentences)\n- Add a blank line between paragraphs\n- Lead with the key point, then provide context\n- Explain the \"why\" not just the \"what\"\n\n---\n\n## Lists\n\n### Unordered Lists\n\nUse dashes (`-`) with 2-space indentation for nesting:\n\n```markdown\n- First item\n- Second item\n  - Nested item\n  - Another nested item\n    - Deep nested (avoid going deeper than 3 levels)\n- Third item\n```\n\n### Ordered Lists\n\nUse numbered lists for sequential steps, instructions, and ranked items:\n\n```markdown\n1. First step\n2. Second step\n   - Sub-point detail\n   - Another sub-point\n3. Third step\n```\n\n### Descriptive Lists\n\nUse bold labels for key-value style lists:\n\n```markdown\n- **Performance bottlenecks** - identify O(n^2) operations, inefficient loops\n- **Memory leaks** - find unreleased resources, circular references\n- **Algorithm improvements** - suggest better algorithms or data structures\n```\n\n### Rules\n\n- Maintain consistent indentation (2 spaces per level)\n- Add a blank line before and after a list\n- Keep list items parallel in structure (all start with verb, or all are nouns, etc.)\n- Avoid nesting deeper than 3 levels\n\n---\n\n## Tables\n\n### Standard Format\n\n```markdown\n| Column 1 | Column 2 | Column 3 |\n|----------|----------|----------|\n| Data     | Data     | Data     |\n```\n\n### Common Table Patterns\n\n**Feature comparison (3-4 columns):**\n\n```markdown\n| Feature | Invocation | Persistence | Best For |\n|---------|-----------|------------|----------|\n| **Slash Commands** | Manual (`/cmd`) | Session only | Quick shortcuts |\n| **Memory** | Auto-loaded | Cross-session | Long-term learning |\n```\n\n**Do's and Don'ts:**\n\n```markdown\n| Do | Don't |\n|----|-------|\n| Use descriptive names | Use vague names |\n| Keep files focused | Overload a single file |\n```\n\n**Quick reference:**\n\n```markdown\n| Aspect | Details |\n|--------|---------|\n| **Purpose** | Generate API documentation |\n| **Scope** | Project-level |\n| **Complexity** | Intermediate |\n```\n\n### Rules\n\n- **Bold table headers** when they are row labels (first column)\n- Align pipes for readability in source (optional but preferred)\n- Keep cell content concise; use links for details\n- Use `code formatting` for commands and file paths inside cells\n\n---\n\n## Code Blocks\n\n### Language Tags\n\nAlways specify a language tag for syntax highlighting:\n\n| Language | Tag | Use For |\n|----------|-----|---------|\n| Shell | `bash` | CLI commands, scripts |\n| Python | `python` | Python code |\n| JavaScript | `javascript` | JS code |\n| TypeScript | `typescript` | TS code |\n| JSON | `json` | Configuration files |\n| YAML | `yaml` | Frontmatter, config |\n| Markdown | `markdown` | Markdown examples |\n| SQL | `sql` | Database queries |\n| Plain text | (no tag) | Expected output, directory trees |\n\n### Conventions\n\n```bash\n# Comment explaining what the command does\nclaude mcp add notion --transport http https://mcp.notion.com/mcp\n```\n\n- Add a **comment line** before non-obvious commands\n- Make all examples **copy-paste ready**\n- Show **both simple and advanced** versions when relevant\n- Include **expected output** when it aids understanding (use untagged code block)\n\n### Installation Blocks\n\nUse this pattern for installation instructions:\n\n```bash\n# Copy files to your project\ncp 01-slash-commands/*.md .claude/commands/\n```\n\n### Multi-step Workflows\n\n```bash\n# Step 1: Create the directory\nmkdir -p .claude/commands\n\n# Step 2: Copy the templates\ncp 01-slash-commands/*.md .claude/commands/\n\n# Step 3: Verify installation\nls .claude/commands/\n```\n\n---\n\n## Links and Cross-References\n\n### Internal Links (Relative)\n\nUse relative paths for all internal links:\n\n```markdown\n[Slash Commands](01-slash-commands/)\n[Skills Guide](03-skills/)\n[Memory Architecture](02-memory/#memory-architecture)\n```\n\nFrom a lesson folder back to root or sibling:\n\n```markdown\n[Back to main guide](../README.md)\n[Related: Skills](../03-skills/)\n```\n\n### External Links (Absolute)\n\nUse full URLs with descriptive anchor text:\n\n```markdown\n[Anthropic's official documentation](https://code.claude.com/docs/en/overview)\n```\n\n- Never use \"click here\" or \"this link\" as anchor text\n- Use descriptive text that makes sense out of context\n\n### Section Anchors\n\nLink to sections within the same document using GitHub-style anchors:\n\n```markdown\n[Feature Catalog](#-feature-catalog)\n[Best Practices](#best-practices)\n```\n\n### Related Guides Pattern\n\nEnd lessons with a related guides section:\n\n```markdown\n## Related Guides\n\n- [Slash Commands](../01-slash-commands/) - Quick shortcuts\n- [Memory](../02-memory/) - Persistent context\n- [Skills](../03-skills/) - Reusable capabilities\n```\n\n---\n\n## Diagrams\n\n### Mermaid\n\nUse Mermaid for all diagrams. Supported types:\n\n- `graph TB` / `graph LR` — architecture, hierarchy, flow\n- `sequenceDiagram` — interaction flows\n- `timeline` — chronological sequences\n\n### Style Conventions\n\nApply consistent colors using style blocks:\n\n```mermaid\ngraph TB\n    A[\"Component A\"] --> B[\"Component B\"]\n    B --> C[\"Component C\"]\n\n    style A fill:#e1f5fe,stroke:#333,color:#333\n    style B fill:#fce4ec,stroke:#333,color:#333\n    style C fill:#e8f5e9,stroke:#333,color:#333\n```\n\n**Color palette:**\n\n| Color | Hex | Use For |\n|-------|-----|---------|\n| Light blue | `#e1f5fe` | Primary components, inputs |\n| Light pink | `#fce4ec` | Processing, middleware |\n| Light green | `#e8f5e9` | Outputs, results |\n| Light yellow | `#fff9c4` | Configuration, optional |\n| Light purple | `#f3e5f5` | User-facing, UI |\n\n### Rules\n\n- Use `[\"Label text\"]` for node labels (enables special characters)\n- Use `<br/>` for line breaks within labels\n- Keep diagrams simple (max 10-12 nodes)\n- Add a brief text description below the diagram for accessibility\n- Use top-to-bottom (`TB`) for hierarchies, left-to-right (`LR`) for workflows\n\n---\n\n## Emoji Usage\n\n### Where Emojis Are Used\n\nEmojis are used **sparingly and purposefully** — only in specific contexts:\n\n| Context | Emojis | Example |\n|---------|--------|---------|\n| Root README section headers | Category icons | `## 📚 Learning Path` |\n| Skill level indicators | Colored circles | 🟢 Beginner, 🔵 Intermediate, 🔴 Advanced |\n| Do's and Don'ts | Check/cross marks | ✅ Do this, ❌ Don't do this |\n| Complexity ratings | Stars | ⭐⭐⭐ |\n\n### Standard Emoji Set\n\n| Emoji | Meaning |\n|-------|---------|\n| 📚 | Learning, guides, documentation |\n| ⚡ | Getting started, quick reference |\n| 🎯 | Features, quick reference |\n| 🎓 | Learning paths |\n| 📊 | Statistics, comparisons |\n| 🚀 | Installation, quick commands |\n| 🟢 | Beginner level |\n| 🔵 | Intermediate level |\n| 🔴 | Advanced level |\n| ✅ | Recommended practice |\n| ❌ | Avoid / anti-pattern |\n| ⭐ | Complexity rating unit |\n\n### Rules\n\n- **Never use emojis in body text** or paragraphs\n- **Only use emojis in headers** on the root README (not in lesson READMEs)\n- **Do not add decorative emojis** — every emoji should convey meaning\n- Keep emoji usage consistent with the table above\n\n---\n\n## YAML Frontmatter\n\n### Feature Files (Skills, Commands, Agents)\n\n```yaml\n---\nname: unique-identifier\ndescription: What this feature does and when to use it\nallowed-tools: Bash, Read, Grep\n---\n```\n\n### Optional Fields\n\n```yaml\n---\nname: my-feature\ndescription: Brief description\nargument-hint: \"[file-path] [options]\"\nallowed-tools: Bash, Read, Grep, Write, Edit\nmodel: opus                        # opus, sonnet, or haiku\ndisable-model-invocation: true     # User-only invocation\nuser-invocable: false              # Hidden from user menu\ncontext: fork                      # Run in isolated subagent\nagent: Explore                     # Agent type for context: fork\n---\n```\n\n### Rules\n\n- Place frontmatter at the very top of the file\n- Use **kebab-case** for the `name` field\n- Keep `description` to one sentence\n- Only include fields that are needed\n\n---\n\n## Images and Media\n\n### Logo Pattern\n\nAll documents that start with a logo use the `<picture>` element for dark/light mode support:\n\n```html\n<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n```\n\n### Screenshots\n\n- Store in the relevant lesson folder (e.g., `01-slash-commands/pr-slash-command.png`)\n- Use kebab-case file names\n- Include descriptive alt text\n- Prefer SVG for diagrams, PNG for screenshots\n\n### Rules\n\n- Always provide alt text for images\n- Keep image file sizes reasonable (< 500KB for PNGs)\n- Use relative paths for image references\n- Store images in the same directory as the document that references them, or in `assets/` for shared images\n\n---\n\n## Tone and Voice\n\n### Writing Style\n\n- **Professional but approachable** — technical accuracy without jargon overload\n- **Active voice** — \"Create a file\" not \"A file should be created\"\n- **Direct instructions** — \"Run this command\" not \"You might want to run this command\"\n- **Beginner-friendly** — assume the reader is new to Claude Code, not new to programming\n\n### Content Principles\n\n| Principle | Example |\n|-----------|---------|\n| **Show, don't tell** | Provide working examples, not abstract descriptions |\n| **Progressive complexity** | Start simple, add depth in later sections |\n| **Explain the \"why\"** | \"Use memory for... because...\" not just \"Use memory for...\" |\n| **Copy-paste ready** | Every code block should work when pasted directly |\n| **Real-world context** | Use practical scenarios, not contrived examples |\n\n### Vocabulary\n\n- Use \"Claude Code\" (not \"Claude CLI\" or \"the tool\")\n- Use \"skill\" (not \"custom command\" — legacy term)\n- Use \"lesson\" or \"guide\" for the numbered sections\n- Use \"example\" for individual feature files\n\n---\n\n## Commit Messages\n\nFollow [Conventional Commits](https://www.conventionalcommits.org/):\n\n```\ntype(scope): description\n```\n\n### Types\n\n| Type | Use For |\n|------|---------|\n| `feat` | New feature, example, or guide |\n| `fix` | Bug fix, correction, broken link |\n| `docs` | Documentation improvements |\n| `refactor` | Restructuring without changing behavior |\n| `style` | Formatting changes only |\n| `test` | Test additions or changes |\n| `chore` | Build, dependencies, CI |\n\n### Scopes\n\nUse the lesson name or file area as scope:\n\n```\nfeat(slash-commands): Add API documentation generator\ndocs(memory): Improve personal preferences example\nfix(README): Correct table of contents link\ndocs(skills): Add comprehensive code review skill\n```\n\n---\n\n## Document Metadata Footer\n\nLesson READMEs end with a metadata block:\n\n```markdown\n---\n**Last Updated**: March 2026\n**Claude Code Version**: 2.1+\n**Compatible Models**: Claude Sonnet 4.6, Claude Opus 4.6, Claude Haiku 4.5\n```\n\n- Use month + year format (e.g., \"March 2026\")\n- Update the version when features change\n- List all compatible models\n\n---\n\n## Checklist for Authors\n\nBefore submitting content, verify:\n\n- [ ] File/folder names use kebab-case\n- [ ] Document starts with H1 title (one per file)\n- [ ] Heading hierarchy is correct (no skipped levels)\n- [ ] All code blocks have language tags\n- [ ] Code examples are copy-paste ready\n- [ ] Internal links use relative paths\n- [ ] External links have descriptive anchor text\n- [ ] Tables are properly formatted\n- [ ] Emojis follow the standard set (if used at all)\n- [ ] Mermaid diagrams use the standard color palette\n- [ ] No sensitive information (API keys, credentials)\n- [ ] YAML frontmatter is valid (if applicable)\n- [ ] Images have alt text\n- [ ] Paragraphs are short and focused\n- [ ] Related guides section links to relevant lessons\n- [ ] Commit message follows conventional commits format\n"
  },
  {
    "path": "claude_concepts_guide.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# Complete Guide to Claude Concepts\n\nA comprehensive reference guide covering Slash Commands, Subagents, Memory, MCP Protocol, and Agent Skills with tables, diagrams, and practical examples.\n\n---\n\n## Table of Contents\n\n1. [Slash Commands](#slash-commands)\n2. [Subagents](#subagents)\n3. [Memory](#memory)\n4. [MCP Protocol](#mcp-protocol)\n5. [Agent Skills](#agent-skills)\n6. [Plugins](#plugins)\n7. [Hooks](#hooks)\n8. [Checkpoints and Rewind](#checkpoints-and-rewind)\n9. [Advanced Features](#advanced-features)\n10. [Comparison & Integration](#comparison--integration)\n\n---\n\n## Slash Commands\n\n### Overview\n\nSlash commands are user-invoked shortcuts stored as Markdown files that Claude Code can execute. They enable teams to standardize frequently-used prompts and workflows.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[\"User Input: /command-name\"] -->|Triggers| B[\"Search .claude/commands/\"]\n    B -->|Finds| C[\"command-name.md\"]\n    C -->|Loads| D[\"Markdown Content\"]\n    D -->|Executes| E[\"Claude Processes Prompt\"]\n    E -->|Returns| F[\"Result in Context\"]\n```\n\n### File Structure\n\n```mermaid\ngraph LR\n    A[\"Project Root\"] -->|contains| B[\".claude/commands/\"]\n    B -->|contains| C[\"optimize.md\"]\n    B -->|contains| D[\"test.md\"]\n    B -->|contains| E[\"docs/\"]\n    E -->|contains| F[\"generate-api-docs.md\"]\n    E -->|contains| G[\"generate-readme.md\"]\n```\n\n### Command Organization Table\n\n| Location | Scope | Availability | Use Case | Git Tracked |\n|----------|-------|--------------|----------|-------------|\n| `.claude/commands/` | Project-specific | Team members | Team workflows, shared standards | ✅ Yes |\n| `~/.claude/commands/` | Personal | Individual user | Personal shortcuts across projects | ❌ No |\n| Subdirectories | Namespaced | Based on parent | Organize by category | ✅ Yes |\n\n### Features & Capabilities\n\n| Feature | Example | Supported |\n|---------|---------|-----------|\n| Shell script execution | `bash scripts/deploy.sh` | ✅ Yes |\n| File references | `@path/to/file.js` | ✅ Yes |\n| Bash integration | `$(git log --oneline)` | ✅ Yes |\n| Arguments | `/pr --verbose` | ✅ Yes |\n| MCP commands | `/mcp__github__list_prs` | ✅ Yes |\n\n### Practical Examples\n\n#### Example 1: Code Optimization Command\n\n**File:** `.claude/commands/optimize.md`\n\n```markdown\n---\nname: Code Optimization\ndescription: Analyze code for performance issues and suggest optimizations\ntags: performance, analysis\n---\n\n# Code Optimization\n\nReview the provided code for the following issues in order of priority:\n\n1. **Performance bottlenecks** - identify O(n²) operations, inefficient loops\n2. **Memory leaks** - find unreleased resources, circular references\n3. **Algorithm improvements** - suggest better algorithms or data structures\n4. **Caching opportunities** - identify repeated computations\n5. **Concurrency issues** - find race conditions or threading problems\n\nFormat your response with:\n- Issue severity (Critical/High/Medium/Low)\n- Location in code\n- Explanation\n- Recommended fix with code example\n```\n\n**Usage:**\n```bash\n# User types in Claude Code\n/optimize\n\n# Claude loads the prompt and waits for code input\n```\n\n#### Example 2: Pull Request Helper Command\n\n**File:** `.claude/commands/pr.md`\n\n```markdown\n---\nname: Prepare Pull Request\ndescription: Clean up code, stage changes, and prepare a pull request\ntags: git, workflow\n---\n\n# Pull Request Preparation Checklist\n\nBefore creating a PR, execute these steps:\n\n1. Run linting: `prettier --write .`\n2. Run tests: `npm test`\n3. Review git diff: `git diff HEAD`\n4. Stage changes: `git add .`\n5. Create commit message following conventional commits:\n   - `fix:` for bug fixes\n   - `feat:` for new features\n   - `docs:` for documentation\n   - `refactor:` for code restructuring\n   - `test:` for test additions\n   - `chore:` for maintenance\n\n6. Generate PR summary including:\n   - What changed\n   - Why it changed\n   - Testing performed\n   - Potential impacts\n```\n\n**Usage:**\n```bash\n/pr\n\n# Claude runs through checklist and prepares the PR\n```\n\n#### Example 3: Hierarchical Documentation Generator\n\n**File:** `.claude/commands/docs/generate-api-docs.md`\n\n```markdown\n---\nname: Generate API Documentation\ndescription: Create comprehensive API documentation from source code\ntags: documentation, api\n---\n\n# API Documentation Generator\n\nGenerate API documentation by:\n\n1. Scanning all files in `/src/api/`\n2. Extracting function signatures and JSDoc comments\n3. Organizing by endpoint/module\n4. Creating markdown with examples\n5. Including request/response schemas\n6. Adding error documentation\n\nOutput format:\n- Markdown file in `/docs/api.md`\n- Include curl examples for all endpoints\n- Add TypeScript types\n```\n\n### Command Lifecycle Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant FS as File System\n    participant CLI as Shell/Bash\n\n    User->>Claude: Types /optimize\n    Claude->>FS: Searches .claude/commands/\n    FS-->>Claude: Returns optimize.md\n    Claude->>Claude: Loads Markdown content\n    Claude->>User: Displays prompt context\n    User->>Claude: Provides code to analyze\n    Claude->>CLI: (May execute scripts)\n    CLI-->>Claude: Results\n    Claude->>User: Returns analysis\n```\n\n### Best Practices\n\n| ✅ Do | ❌ Don't |\n|------|---------|\n| Use clear, action-oriented names | Create commands for one-time tasks |\n| Document trigger words in description | Build complex logic in commands |\n| Keep commands focused on single task | Create redundant commands |\n| Version control project commands | Hardcode sensitive information |\n| Organize in subdirectories | Create long lists of commands |\n| Use simple, readable prompts | Use abbreviated or cryptic wording |\n\n---\n\n## Subagents\n\n### Overview\n\nSubagents are specialized AI assistants with isolated context windows and customized system prompts. They enable delegated task execution while maintaining clean separation of concerns.\n\n### Architecture Diagram\n\n```mermaid\ngraph TB\n    User[\"👤 User\"]\n    Main[\"🎯 Main Agent<br/>(Coordinator)\"]\n    Reviewer[\"🔍 Code Reviewer<br/>Subagent\"]\n    Tester[\"✅ Test Engineer<br/>Subagent\"]\n    Docs[\"📝 Documentation<br/>Subagent\"]\n\n    User -->|asks| Main\n    Main -->|delegates| Reviewer\n    Main -->|delegates| Tester\n    Main -->|delegates| Docs\n    Reviewer -->|returns result| Main\n    Tester -->|returns result| Main\n    Docs -->|returns result| Main\n    Main -->|synthesizes| User\n```\n\n### Subagent Lifecycle\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MainAgent as Main Agent\n    participant CodeReviewer as Code Reviewer<br/>Subagent\n    participant Context as Separate<br/>Context Window\n\n    User->>MainAgent: \"Build new auth feature\"\n    MainAgent->>MainAgent: Analyze task\n    MainAgent->>CodeReviewer: \"Review this code\"\n    CodeReviewer->>Context: Initialize clean context\n    Context->>CodeReviewer: Load reviewer instructions\n    CodeReviewer->>CodeReviewer: Perform review\n    CodeReviewer-->>MainAgent: Return findings\n    MainAgent->>MainAgent: Incorporate results\n    MainAgent-->>User: Provide synthesis\n```\n\n### Subagent Configuration Table\n\n| Configuration | Type | Purpose | Example |\n|---------------|------|---------|---------|\n| `name` | String | Agent identifier | `code-reviewer` |\n| `description` | String | Purpose & trigger terms | `Comprehensive code quality analysis` |\n| `tools` | List/String | Allowed capabilities | `read, grep, diff, lint_runner` |\n| `system_prompt` | Markdown | Behavioral instructions | Custom guidelines |\n\n### Tool Access Hierarchy\n\n```mermaid\ngraph TD\n    A[\"Subagent Configuration\"] -->|Option 1| B[\"Inherit All Tools<br/>from Main Thread\"]\n    A -->|Option 2| C[\"Specify Individual Tools\"]\n    B -->|Includes| B1[\"File Operations\"]\n    B -->|Includes| B2[\"Shell Commands\"]\n    B -->|Includes| B3[\"MCP Tools\"]\n    C -->|Explicit List| C1[\"read, grep, diff\"]\n    C -->|Explicit List| C2[\"Bash(npm:*), Bash(test:*)\"]\n```\n\n### Practical Examples\n\n#### Example 1: Complete Subagent Setup\n\n**File:** `.claude/agents/code-reviewer.md`\n\n```yaml\n---\nname: code-reviewer\ndescription: Comprehensive code quality and maintainability analysis\ntools: read, grep, diff, lint_runner\n---\n\n# Code Reviewer Agent\n\nYou are an expert code reviewer specializing in:\n- Performance optimization\n- Security vulnerabilities\n- Code maintainability\n- Testing coverage\n- Design patterns\n\n## Review Priorities (in order)\n\n1. **Security Issues** - Authentication, authorization, data exposure\n2. **Performance Problems** - O(n²) operations, memory leaks, inefficient queries\n3. **Code Quality** - Readability, naming, documentation\n4. **Test Coverage** - Missing tests, edge cases\n5. **Design Patterns** - SOLID principles, architecture\n\n## Review Output Format\n\nFor each issue:\n- **Severity**: Critical / High / Medium / Low\n- **Category**: Security / Performance / Quality / Testing / Design\n- **Location**: File path and line number\n- **Issue Description**: What's wrong and why\n- **Suggested Fix**: Code example\n- **Impact**: How this affects the system\n\n## Example Review\n\n### Issue: N+1 Query Problem\n- **Severity**: High\n- **Category**: Performance\n- **Location**: src/user-service.ts:45\n- **Issue**: Loop executes database query in each iteration\n- **Fix**: Use JOIN or batch query\n```\n\n**File:** `.claude/agents/test-engineer.md`\n\n```yaml\n---\nname: test-engineer\ndescription: Test strategy, coverage analysis, and automated testing\ntools: read, write, bash, grep\n---\n\n# Test Engineer Agent\n\nYou are expert at:\n- Writing comprehensive test suites\n- Ensuring high code coverage (>80%)\n- Testing edge cases and error scenarios\n- Performance benchmarking\n- Integration testing\n\n## Testing Strategy\n\n1. **Unit Tests** - Individual functions/methods\n2. **Integration Tests** - Component interactions\n3. **End-to-End Tests** - Complete workflows\n4. **Edge Cases** - Boundary conditions\n5. **Error Scenarios** - Failure handling\n\n## Test Output Requirements\n\n- Use Jest for JavaScript/TypeScript\n- Include setup/teardown for each test\n- Mock external dependencies\n- Document test purpose\n- Include performance assertions when relevant\n\n## Coverage Requirements\n\n- Minimum 80% code coverage\n- 100% for critical paths\n- Report missing coverage areas\n```\n\n**File:** `.claude/agents/documentation-writer.md`\n\n```yaml\n---\nname: documentation-writer\ndescription: Technical documentation, API docs, and user guides\ntools: read, write, grep\n---\n\n# Documentation Writer Agent\n\nYou create:\n- API documentation with examples\n- User guides and tutorials\n- Architecture documentation\n- Changelog entries\n- Code comment improvements\n\n## Documentation Standards\n\n1. **Clarity** - Use simple, clear language\n2. **Examples** - Include practical code examples\n3. **Completeness** - Cover all parameters and returns\n4. **Structure** - Use consistent formatting\n5. **Accuracy** - Verify against actual code\n\n## Documentation Sections\n\n### For APIs\n- Description\n- Parameters (with types)\n- Returns (with types)\n- Throws (possible errors)\n- Examples (curl, JavaScript, Python)\n- Related endpoints\n\n### For Features\n- Overview\n- Prerequisites\n- Step-by-step instructions\n- Expected outcomes\n- Troubleshooting\n- Related topics\n```\n\n#### Example 2: Subagent Delegation in Action\n\n```markdown\n# Scenario: Building a Payment Feature\n\n## User Request\n\"Build a secure payment processing feature that integrates with Stripe\"\n\n## Main Agent Flow\n\n1. **Planning Phase**\n   - Understands requirements\n   - Determines tasks needed\n   - Plans architecture\n\n2. **Delegates to Code Reviewer Subagent**\n   - Task: \"Review the payment processing implementation for security\"\n   - Context: Auth, API keys, token handling\n   - Reviews for: SQL injection, key exposure, HTTPS enforcement\n\n3. **Delegates to Test Engineer Subagent**\n   - Task: \"Create comprehensive tests for payment flows\"\n   - Context: Success scenarios, failures, edge cases\n   - Creates tests for: Valid payments, declined cards, network failures, webhooks\n\n4. **Delegates to Documentation Writer Subagent**\n   - Task: \"Document the payment API endpoints\"\n   - Context: Request/response schemas\n   - Produces: API docs with curl examples, error codes\n\n5. **Synthesis**\n   - Main agent collects all outputs\n   - Integrates findings\n   - Returns complete solution to user\n```\n\n#### Example 3: Tool Permission Scoping\n\n**Restrictive Setup - Limited to Specific Commands**\n\n```yaml\n---\nname: secure-reviewer\ndescription: Security-focused code review with minimal permissions\ntools: read, grep\n---\n\n# Secure Code Reviewer\n\nReviews code for security vulnerabilities only.\n\nThis agent:\n- ✅ Reads files to analyze\n- ✅ Searches for patterns\n- ❌ Cannot execute code\n- ❌ Cannot modify files\n- ❌ Cannot run tests\n\nThis ensures the reviewer doesn't accidentally break anything.\n```\n\n**Extended Setup - All Tools for Implementation**\n\n```yaml\n---\nname: implementation-agent\ndescription: Full implementation capabilities for feature development\ntools: read, write, bash, grep, edit, glob\n---\n\n# Implementation Agent\n\nBuilds features from specifications.\n\nThis agent:\n- ✅ Reads specifications\n- ✅ Writes new code files\n- ✅ Runs build commands\n- ✅ Searches codebase\n- ✅ Edits existing files\n- ✅ Finds files matching patterns\n\nFull capabilities for independent feature development.\n```\n\n### Subagent Context Management\n\n```mermaid\ngraph TB\n    A[\"Main Agent Context<br/>50,000 tokens\"]\n    B[\"Subagent 1 Context<br/>20,000 tokens\"]\n    C[\"Subagent 2 Context<br/>20,000 tokens\"]\n    D[\"Subagent 3 Context<br/>20,000 tokens\"]\n\n    A -->|Clean slate| B\n    A -->|Clean slate| C\n    A -->|Clean slate| D\n\n    B -->|Results only| A\n    C -->|Results only| A\n    D -->|Results only| A\n\n    style A fill:#e1f5ff\n    style B fill:#fff9c4\n    style C fill:#fff9c4\n    style D fill:#fff9c4\n```\n\n### When to Use Subagents\n\n| Scenario | Use Subagent | Why |\n|----------|--------------|-----|\n| Complex feature with many steps | ✅ Yes | Separate concerns, prevent context pollution |\n| Quick code review | ❌ No | Not necessary overhead |\n| Parallel task execution | ✅ Yes | Each subagent has own context |\n| Specialized expertise needed | ✅ Yes | Custom system prompts |\n| Long-running analysis | ✅ Yes | Prevents main context exhaustion |\n| Single task | ❌ No | Adds latency unnecessarily |\n\n### Agent Teams\n\nAgent Teams coordinate multiple agents working on related tasks. Rather than delegating to one subagent at a time, Agent Teams allow the main agent to orchestrate a group of agents that collaborate, share intermediate results, and work toward a common goal. This is useful for large-scale tasks like full-stack feature development where a frontend agent, backend agent, and testing agent work in parallel.\n\n---\n\n## Memory\n\n### Overview\n\nMemory 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.\n\n### Memory Architecture\n\n```mermaid\ngraph TB\n    A[\"Claude Session\"]\n    B[\"User Input\"]\n    C[\"Memory System\"]\n    D[\"Memory Storage\"]\n\n    B -->|User provides info| C\n    C -->|Synthesizes every 24h| D\n    D -->|Loads automatically| A\n    A -->|Uses context| C\n```\n\n### Memory Hierarchy in Claude Code (7 Tiers)\n\nClaude Code loads memory from 7 tiers, listed from highest to lowest priority:\n\n```mermaid\ngraph TD\n    A[\"1. Managed Policy<br/>Enterprise admin policies\"] --> B[\"2. Project Memory<br/>./CLAUDE.md\"]\n    B --> C[\"3. Project Rules<br/>.claude/rules/*.md\"]\n    C --> D[\"4. User Memory<br/>~/.claude/CLAUDE.md\"]\n    D --> E[\"5. User Rules<br/>~/.claude/rules/*.md\"]\n    E --> F[\"6. Local Memory<br/>.claude/local/CLAUDE.md\"]\n    F --> G[\"7. Auto Memory<br/>Automatically captured preferences\"]\n\n    style A fill:#fce4ec,stroke:#333,color:#333\n    style B fill:#e1f5fe,stroke:#333,color:#333\n    style C fill:#e1f5fe,stroke:#333,color:#333\n    style D fill:#f3e5f5,stroke:#333,color:#333\n    style E fill:#f3e5f5,stroke:#333,color:#333\n    style F fill:#e8f5e9,stroke:#333,color:#333\n    style G fill:#fff3e0,stroke:#333,color:#333\n```\n\n### Memory Locations Table\n\n| Tier | Location | Scope | Priority | Shared | Best For |\n|------|----------|-------|----------|--------|----------|\n| 1. Managed Policy | Enterprise admin | Organization | Highest | All org users | Compliance, security policies |\n| 2. Project | `./CLAUDE.md` | Project | High | Team (Git) | Team standards, architecture |\n| 3. Project Rules | `.claude/rules/*.md` | Project | High | Team (Git) | Modular project conventions |\n| 4. User | `~/.claude/CLAUDE.md` | Personal | Medium | Individual | Personal preferences |\n| 5. User Rules | `~/.claude/rules/*.md` | Personal | Medium | Individual | Personal rule modules |\n| 6. Local | `.claude/local/CLAUDE.md` | Local | Low | Not shared | Machine-specific settings |\n| 7. Auto Memory | Automatic | Session | Lowest | Individual | Learned preferences, patterns |\n\n### Auto Memory\n\nAuto Memory automatically captures user preferences and patterns observed during sessions. Claude learns from your interactions and remembers:\n\n- Coding style preferences\n- Common corrections you make\n- Framework and tool choices\n- Communication style preferences\n\nAuto Memory works in the background and does not require manual configuration.\n\n### Memory Update Lifecycle\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Editor as File System\n    participant Memory as CLAUDE.md\n\n    User->>Claude: \"Remember: use async/await\"\n    Claude->>User: \"Which memory file?\"\n    User->>Claude: \"Project memory\"\n    Claude->>Editor: Open ~/.claude/settings.json\n    Claude->>Memory: Write to ./CLAUDE.md\n    Memory-->>Claude: File saved\n    Claude->>Claude: Load updated memory\n    Claude-->>User: \"Memory saved!\"\n```\n\n### Practical Examples\n\n#### Example 1: Project Memory Structure\n\n**File:** `./CLAUDE.md`\n\n```markdown\n# Project Configuration\n\n## Project Overview\n- **Name**: E-commerce Platform\n- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker\n- **Team Size**: 5 developers\n- **Deadline**: Q4 2025\n\n## Architecture\n@docs/architecture.md\n@docs/api-standards.md\n@docs/database-schema.md\n\n## Development Standards\n\n### Code Style\n- Use Prettier for formatting\n- Use ESLint with airbnb config\n- Maximum line length: 100 characters\n- Use 2-space indentation\n\n### Naming Conventions\n- **Files**: kebab-case (user-controller.js)\n- **Classes**: PascalCase (UserService)\n- **Functions/Variables**: camelCase (getUserById)\n- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)\n- **Database Tables**: snake_case (user_accounts)\n\n### Git Workflow\n- Branch names: `feature/description` or `fix/description`\n- Commit messages: Follow conventional commits\n- PR required before merge\n- All CI/CD checks must pass\n- Minimum 1 approval required\n\n### Testing Requirements\n- Minimum 80% code coverage\n- All critical paths must have tests\n- Use Jest for unit tests\n- Use Cypress for E2E tests\n- Test filenames: `*.test.ts` or `*.spec.ts`\n\n### API Standards\n- RESTful endpoints only\n- JSON request/response\n- Use HTTP status codes correctly\n- Version API endpoints: `/api/v1/`\n- Document all endpoints with examples\n\n### Database\n- Use migrations for schema changes\n- Never hardcode credentials\n- Use connection pooling\n- Enable query logging in development\n- Regular backups required\n\n### Deployment\n- Docker-based deployment\n- Kubernetes orchestration\n- Blue-green deployment strategy\n- Automatic rollback on failure\n- Database migrations run before deploy\n\n## Common Commands\n\n| Command | Purpose |\n|---------|---------|\n| `npm run dev` | Start development server |\n| `npm test` | Run test suite |\n| `npm run lint` | Check code style |\n| `npm run build` | Build for production |\n| `npm run migrate` | Run database migrations |\n\n## Team Contacts\n- Tech Lead: Sarah Chen (@sarah.chen)\n- Product Manager: Mike Johnson (@mike.j)\n- DevOps: Alex Kim (@alex.k)\n\n## Known Issues & Workarounds\n- PostgreSQL connection pooling limited to 20 during peak hours\n- Workaround: Implement query queuing\n- Safari 14 compatibility issues with async generators\n- Workaround: Use Babel transpiler\n\n## Related Projects\n- Analytics Dashboard: `/projects/analytics`\n- Mobile App: `/projects/mobile`\n- Admin Panel: `/projects/admin`\n```\n\n#### Example 2: Directory-Specific Memory\n\n**File:** `./src/api/CLAUDE.md`\n\n~~~~markdown\n# API Module Standards\n\nThis file overrides root CLAUDE.md for everything in /src/api/\n\n## API-Specific Standards\n\n### Request Validation\n- Use Zod for schema validation\n- Always validate input\n- Return 400 with validation errors\n- Include field-level error details\n\n### Authentication\n- All endpoints require JWT token\n- Token in Authorization header\n- Token expires after 24 hours\n- Implement refresh token mechanism\n\n### Response Format\n\nAll responses must follow this structure:\n\n```json\n{\n  \"success\": true,\n  \"data\": { /* actual data */ },\n  \"timestamp\": \"2025-11-06T10:30:00Z\",\n  \"version\": \"1.0\"\n}\n```\n\n### Error responses:\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"User message\",\n    \"details\": { /* field errors */ }\n  },\n  \"timestamp\": \"2025-11-06T10:30:00Z\"\n}\n```\n\n### Pagination\n- Use cursor-based pagination (not offset)\n- Include `hasMore` boolean\n- Limit max page size to 100\n- Default page size: 20\n\n### Rate Limiting\n- 1000 requests per hour for authenticated users\n- 100 requests per hour for public endpoints\n- Return 429 when exceeded\n- Include retry-after header\n\n### Caching\n- Use Redis for session caching\n- Cache duration: 5 minutes default\n- Invalidate on write operations\n- Tag cache keys with resource type\n~~~~\n\n#### Example 3: Personal Memory\n\n**File:** `~/.claude/CLAUDE.md`\n\n~~~~markdown\n# My Development Preferences\n\n## About Me\n- **Experience Level**: 8 years full-stack development\n- **Preferred Languages**: TypeScript, Python\n- **Communication Style**: Direct, with examples\n- **Learning Style**: Visual diagrams with code\n\n## Code Preferences\n\n### Error Handling\nI prefer explicit error handling with try-catch blocks and meaningful error messages.\nAvoid generic errors. Always log errors for debugging.\n\n### Comments\nUse comments for WHY, not WHAT. Code should be self-documenting.\nComments should explain business logic or non-obvious decisions.\n\n### Testing\nI prefer TDD (test-driven development).\nWrite tests first, then implementation.\nFocus on behavior, not implementation details.\n\n### Architecture\nI prefer modular, loosely-coupled design.\nUse dependency injection for testability.\nSeparate concerns (Controllers, Services, Repositories).\n\n## Debugging Preferences\n- Use console.log with prefix: `[DEBUG]`\n- Include context: function name, relevant variables\n- Use stack traces when available\n- Always include timestamps in logs\n\n## Communication\n- Explain complex concepts with diagrams\n- Show concrete examples before explaining theory\n- Include before/after code snippets\n- Summarize key points at the end\n\n## Project Organization\nI organize my projects as:\n```\nproject/\n  ├── src/\n  │   ├── api/\n  │   ├── services/\n  │   ├── models/\n  │   └── utils/\n  ├── tests/\n  ├── docs/\n  └── docker/\n```\n\n## Tooling\n- **IDE**: VS Code with vim keybindings\n- **Terminal**: Zsh with Oh-My-Zsh\n- **Format**: Prettier (100 char line length)\n- **Linter**: ESLint with airbnb config\n- **Test Framework**: Jest with React Testing Library\n~~~~\n\n#### Example 4: Memory Update During Session\n\n**Session Interaction:**\n\n```markdown\nUser: Remember that I prefer using React hooks instead of class components\n     for all new components.\n\nClaude: I'm adding that to your memory. Which memory file should this go in?\n        1. Project memory (./CLAUDE.md)\n        2. Personal memory (~/.claude/CLAUDE.md)\n\nUser: Project memory\n\nClaude: ✅ Memory saved!\n\nAdded to ./CLAUDE.md:\n---\n\n### Component Development\n- Use functional components with React Hooks\n- Prefer hooks over class components\n- Custom hooks for reusable logic\n- Use useCallback for event handlers\n- Use useMemo for expensive computations\n```\n\n### Memory in Claude Web/Desktop\n\n#### Memory Synthesis Timeline\n\n```mermaid\ngraph LR\n    A[\"Day 1: User<br/>Conversations\"] -->|24 hours| B[\"Day 2: Memory<br/>Synthesis\"]\n    B -->|Automatic| C[\"Memory Updated<br/>Summarized\"]\n    C -->|Loaded in| D[\"Day 2-N:<br/>New Conversations\"]\n    D -->|Add to| E[\"Memory\"]\n    E -->|24 hours later| F[\"Memory Refreshed\"]\n```\n\n**Example Memory Summary:**\n\n```markdown\n## Claude's Memory of User\n\n### Professional Background\n- Senior full-stack developer with 8 years experience\n- Focus on TypeScript/Node.js backends and React frontends\n- Active open source contributor\n- Interested in AI and machine learning\n\n### Project Context\n- Currently building e-commerce platform\n- Tech stack: Node.js, PostgreSQL, React 18, Docker\n- Working with team of 5 developers\n- Using CI/CD and blue-green deployments\n\n### Communication Preferences\n- Prefers direct, concise explanations\n- Likes visual diagrams and examples\n- Appreciates code snippets\n- Explains business logic in comments\n\n### Current Goals\n- Improve API performance\n- Increase test coverage to 90%\n- Implement caching strategy\n- Document architecture\n```\n\n### Memory Features Comparison\n\n| Feature | Claude Web/Desktop | Claude Code (CLAUDE.md) |\n|---------|-------------------|------------------------|\n| Auto-synthesis | ✅ Every 24h | ❌ Manual |\n| Cross-project | ✅ Shared | ❌ Project-specific |\n| Team access | ✅ Shared projects | ✅ Git-tracked |\n| Searchable | ✅ Built-in | ✅ Through `/memory` |\n| Editable | ✅ In-chat | ✅ Direct file edit |\n| Import/Export | ✅ Yes | ✅ Copy/paste |\n| Persistent | ✅ 24h+ | ✅ Indefinite |\n\n---\n\n## MCP Protocol\n\n### Overview\n\nMCP (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.\n\n### MCP Architecture\n\n```mermaid\ngraph TB\n    A[\"Claude\"]\n    B[\"MCP Server\"]\n    C[\"External Service\"]\n\n    A -->|Request: list_issues| B\n    B -->|Query| C\n    C -->|Data| B\n    B -->|Response| A\n\n    A -->|Request: create_issue| B\n    B -->|Action| C\n    C -->|Result| B\n    B -->|Response| A\n```\n\n### MCP Ecosystem\n\n```mermaid\ngraph TB\n    A[\"Claude\"] -->|MCP| B[\"Filesystem<br/>MCP Server\"]\n    A -->|MCP| C[\"GitHub<br/>MCP Server\"]\n    A -->|MCP| D[\"Database<br/>MCP Server\"]\n    A -->|MCP| E[\"Slack<br/>MCP Server\"]\n    A -->|MCP| F[\"Google Docs<br/>MCP Server\"]\n\n    B -->|File I/O| G[\"Local Files\"]\n    C -->|API| H[\"GitHub Repos\"]\n    D -->|Query| I[\"PostgreSQL/MySQL\"]\n    E -->|Messages| J[\"Slack Workspace\"]\n    F -->|Docs| K[\"Google Drive\"]\n```\n\n### MCP Setup Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Config as Config File\n    participant Service as External Service\n\n    User->>Claude: Type /mcp\n    Claude->>Claude: List available MCP servers\n    Claude->>User: Show options\n    User->>Claude: Select GitHub MCP\n    Claude->>Config: Update configuration\n    Config->>Claude: Activate connection\n    Claude->>Service: Test connection\n    Service-->>Claude: Authentication successful\n    Claude->>User: ✅ MCP connected!\n```\n\n### Available MCP Servers Table\n\n| MCP Server | Purpose | Common Tools | Auth | Real-time |\n|------------|---------|--------------|------|-----------|\n| **Filesystem** | File operations | read, write, delete | OS permissions | ✅ Yes |\n| **GitHub** | Repository management | list_prs, create_issue, push | OAuth | ✅ Yes |\n| **Slack** | Team communication | send_message, list_channels | Token | ✅ Yes |\n| **Database** | SQL queries | query, insert, update | Credentials | ✅ Yes |\n| **Google Docs** | Document access | read, write, share | OAuth | ✅ Yes |\n| **Asana** | Project management | create_task, update_status | API Key | ✅ Yes |\n| **Stripe** | Payment data | list_charges, create_invoice | API Key | ✅ Yes |\n| **Memory** | Persistent memory | store, retrieve, delete | Local | ❌ No |\n\n### Practical Examples\n\n#### Example 1: GitHub MCP Configuration\n\n**File:** `.mcp.json` (project scope) or `~/.claude.json` (user scope)\n\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n**Available GitHub MCP Tools:**\n\n~~~~markdown\n# GitHub MCP Tools\n\n## Pull Request Management\n- `list_prs` - List all PRs in repository\n- `get_pr` - Get PR details including diff\n- `create_pr` - Create new PR\n- `update_pr` - Update PR description/title\n- `merge_pr` - Merge PR to main branch\n- `review_pr` - Add review comments\n\nExample request:\n```\n/mcp__github__get_pr 456\n\n# Returns:\nTitle: Add dark mode support\nAuthor: @alice\nDescription: Implements dark theme using CSS variables\nStatus: OPEN\nReviewers: @bob, @charlie\n```\n\n## Issue Management\n- `list_issues` - List all issues\n- `get_issue` - Get issue details\n- `create_issue` - Create new issue\n- `close_issue` - Close issue\n- `add_comment` - Add comment to issue\n\n## Repository Information\n- `get_repo_info` - Repository details\n- `list_files` - File tree structure\n- `get_file_content` - Read file contents\n- `search_code` - Search across codebase\n\n## Commit Operations\n- `list_commits` - Commit history\n- `get_commit` - Specific commit details\n- `create_commit` - Create new commit\n~~~~\n\n#### Example 2: Database MCP Setup\n\n**Configuration:**\n\n```json\n{\n  \"mcpServers\": {\n    \"database\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-database\"],\n      \"env\": {\n        \"DATABASE_URL\": \"postgresql://user:pass@localhost/mydb\"\n      }\n    }\n  }\n}\n```\n\n**Example Usage:**\n\n```markdown\nUser: Fetch all users with more than 10 orders\n\nClaude: I'll query your database to find that information.\n\n# Using MCP database tool:\nSELECT u.*, COUNT(o.id) as order_count\nFROM users u\nLEFT JOIN orders o ON u.id = o.user_id\nGROUP BY u.id\nHAVING COUNT(o.id) > 10\nORDER BY order_count DESC;\n\n# Results:\n- Alice: 15 orders\n- Bob: 12 orders\n- Charlie: 11 orders\n```\n\n#### Example 3: Multi-MCP Workflow\n\n**Scenario: Daily Report Generation**\n\n```markdown\n# Daily Report Workflow using Multiple MCPs\n\n## Setup\n1. GitHub MCP - fetch PR metrics\n2. Database MCP - query sales data\n3. Slack MCP - post report\n4. Filesystem MCP - save report\n\n## Workflow\n\n### Step 1: Fetch GitHub Data\n/mcp__github__list_prs completed:true last:7days\n\nOutput:\n- Total PRs: 42\n- Average merge time: 2.3 hours\n- Review turnaround: 1.1 hours\n\n### Step 2: Query Database\nSELECT COUNT(*) as sales, SUM(amount) as revenue\nFROM orders\nWHERE created_at > NOW() - INTERVAL '1 day'\n\nOutput:\n- Sales: 247\n- Revenue: $12,450\n\n### Step 3: Generate Report\nCombine data into HTML report\n\n### Step 4: Save to Filesystem\nWrite report.html to /reports/\n\n### Step 5: Post to Slack\nSend summary to #daily-reports channel\n\nFinal Output:\n✅ Report generated and posted\n📊 47 PRs merged this week\n💰 $12,450 in daily sales\n```\n\n#### Example 4: Filesystem MCP Operations\n\n**Configuration:**\n\n```json\n{\n  \"mcpServers\": {\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"@modelcontextprotocol/server-filesystem\", \"/home/user/projects\"]\n    }\n  }\n}\n```\n\n**Available Operations:**\n\n| Operation | Command | Purpose |\n|-----------|---------|---------|\n| List files | `ls ~/projects` | Show directory contents |\n| Read file | `cat src/main.ts` | Read file contents |\n| Write file | `create docs/api.md` | Create new file |\n| Edit file | `edit src/app.ts` | Modify file |\n| Search | `grep \"async function\"` | Search in files |\n| Delete | `rm old-file.js` | Delete file |\n\n### MCP vs Memory: Decision Matrix\n\n```mermaid\ngraph TD\n    A[\"Need external data?\"]\n    A -->|No| B[\"Use Memory\"]\n    A -->|Yes| C[\"Does it change frequently?\"]\n    C -->|No/Rarely| B\n    C -->|Yes/Often| D[\"Use MCP\"]\n\n    B -->|Stores| E[\"Preferences<br/>Context<br/>History\"]\n    D -->|Accesses| F[\"Live APIs<br/>Databases<br/>Services\"]\n\n    style B fill:#e1f5ff\n    style D fill:#fff9c4\n```\n\n### Request/Response Pattern\n\n```mermaid\nsequenceDiagram\n    participant App as Claude\n    participant MCP as MCP Server\n    participant DB as Database\n\n    App->>MCP: Request: \"SELECT * FROM users WHERE id=1\"\n    MCP->>DB: Execute query\n    DB-->>MCP: Result set\n    MCP-->>App: Return parsed data\n    App->>App: Process result\n    App->>App: Continue task\n\n    Note over MCP,DB: Real-time access<br/>No caching\n```\n\n---\n\n## Agent Skills\n\n### Overview\n\nAgent Skills are reusable, model-invoked capabilities packaged as folders containing instructions, scripts, and resources. Claude automatically detects and uses relevant skills.\n\n### Skill Architecture\n\n```mermaid\ngraph TB\n    A[\"Skill Directory\"]\n    B[\"SKILL.md\"]\n    C[\"YAML Metadata\"]\n    D[\"Instructions\"]\n    E[\"Scripts\"]\n    F[\"Templates\"]\n\n    A --> B\n    B --> C\n    B --> D\n    E --> A\n    F --> A\n```\n\n### Skill Loading Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude\n    participant System as System\n    participant Skill as Skill\n\n    User->>Claude: \"Create Excel report\"\n    Claude->>System: Scan available skills\n    System->>System: Load skill metadata\n    Claude->>Claude: Match user request to skills\n    Claude->>Skill: Load xlsx skill SKILL.md\n    Skill-->>Claude: Return instructions + tools\n    Claude->>Claude: Execute skill\n    Claude->>User: Generate Excel file\n```\n\n### Skill Types & Locations Table\n\n| Type | Location | Scope | Shared | Sync | Best For |\n|------|----------|-------|--------|------|----------|\n| Pre-built | Built-in | Global | All users | Auto | Document creation |\n| Personal | `~/.claude/skills/` | Individual | No | Manual | Personal automation |\n| Project | `.claude/skills/` | Team | Yes | Git | Team standards |\n| Plugin | Via plugin install | Varies | Depends | Auto | Integrated features |\n\n### Pre-built Skills\n\n```mermaid\ngraph TB\n    A[\"Pre-built Skills\"]\n    B[\"PowerPoint (pptx)\"]\n    C[\"Excel (xlsx)\"]\n    D[\"Word (docx)\"]\n    E[\"PDF\"]\n\n    A --> B\n    A --> C\n    A --> D\n    A --> E\n\n    B --> B1[\"Create presentations\"]\n    B --> B2[\"Edit slides\"]\n    C --> C1[\"Create spreadsheets\"]\n    C --> C2[\"Analyze data\"]\n    D --> D1[\"Create documents\"]\n    D --> D2[\"Format text\"]\n    E --> E1[\"Generate PDFs\"]\n    E --> E2[\"Fill forms\"]\n```\n\n### Bundled Skills\n\nClaude Code now includes 5 bundled skills available out of the box:\n\n| Skill | Command | Purpose |\n|-------|---------|---------|\n| **Simplify** | `/simplify` | Simplify complex code or explanations |\n| **Batch** | `/batch` | Run operations across multiple files or items |\n| **Debug** | `/debug` | Systematic debugging of issues with root cause analysis |\n| **Loop** | `/loop` | Schedule recurring tasks on a timer |\n| **Claude API** | `/claude-api` | Interact with the Anthropic API directly |\n\nThese bundled skills are always available and do not require installation or configuration.\n\n### Practical Examples\n\n#### Example 1: Custom Code Review Skill\n\n**Directory Structure:**\n\n```\n~/.claude/skills/code-review/\n├── SKILL.md\n├── templates/\n│   ├── review-checklist.md\n│   └── finding-template.md\n└── scripts/\n    ├── analyze-metrics.py\n    └── compare-complexity.py\n```\n\n**File:** `~/.claude/skills/code-review/SKILL.md`\n\n```yaml\n---\nname: Code Review Specialist\ndescription: Comprehensive code review with security, performance, and quality analysis\nversion: \"1.0.0\"\ntags:\n  - code-review\n  - quality\n  - security\nwhen_to_use: When users ask to review code, analyze code quality, or evaluate pull requests\neffort: high\nshell: bash\n---\n\n# Code Review Skill\n\nThis skill provides comprehensive code review capabilities focusing on:\n\n1. **Security Analysis**\n   - Authentication/authorization issues\n   - Data exposure risks\n   - Injection vulnerabilities\n   - Cryptographic weaknesses\n   - Sensitive data logging\n\n2. **Performance Review**\n   - Algorithm efficiency (Big O analysis)\n   - Memory optimization\n   - Database query optimization\n   - Caching opportunities\n   - Concurrency issues\n\n3. **Code Quality**\n   - SOLID principles\n   - Design patterns\n   - Naming conventions\n   - Documentation\n   - Test coverage\n\n4. **Maintainability**\n   - Code readability\n   - Function size (should be < 50 lines)\n   - Cyclomatic complexity\n   - Dependency management\n   - Type safety\n\n## Review Template\n\nFor each piece of code reviewed, provide:\n\n### Summary\n- Overall quality assessment (1-5)\n- Key findings count\n- Recommended priority areas\n\n### Critical Issues (if any)\n- **Issue**: Clear description\n- **Location**: File and line number\n- **Impact**: Why this matters\n- **Severity**: Critical/High/Medium\n- **Fix**: Code example\n\n### Findings by Category\n\n#### Security (if issues found)\nList security vulnerabilities with examples\n\n#### Performance (if issues found)\nList performance problems with complexity analysis\n\n#### Quality (if issues found)\nList code quality issues with refactoring suggestions\n\n#### Maintainability (if issues found)\nList maintainability problems with improvements\n```\n## Python Script: analyze-metrics.py\n\n```python\n#!/usr/bin/env python3\nimport re\nimport sys\n\ndef analyze_code_metrics(code):\n    \"\"\"Analyze code for common metrics.\"\"\"\n\n    # Count functions\n    functions = len(re.findall(r'^def\\s+\\w+', code, re.MULTILINE))\n\n    # Count classes\n    classes = len(re.findall(r'^class\\s+\\w+', code, re.MULTILINE))\n\n    # Average line length\n    lines = code.split('\\n')\n    avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0\n\n    # Estimate complexity\n    complexity = len(re.findall(r'\\b(if|elif|else|for|while|and|or)\\b', code))\n\n    return {\n        'functions': functions,\n        'classes': classes,\n        'avg_line_length': avg_length,\n        'complexity_score': complexity\n    }\n\nif __name__ == '__main__':\n    with open(sys.argv[1], 'r') as f:\n        code = f.read()\n    metrics = analyze_code_metrics(code)\n    for key, value in metrics.items():\n        print(f\"{key}: {value:.2f}\")\n```\n\n## Python Script: compare-complexity.py\n\n```python\n#!/usr/bin/env python3\n\"\"\"\nCompare cyclomatic complexity of code before and after changes.\nHelps identify if refactoring actually simplifies code structure.\n\"\"\"\n\nimport re\nimport sys\nfrom typing import Dict, Tuple\n\nclass ComplexityAnalyzer:\n    \"\"\"Analyze code complexity metrics.\"\"\"\n\n    def __init__(self, code: str):\n        self.code = code\n        self.lines = code.split('\\n')\n\n    def calculate_cyclomatic_complexity(self) -> int:\n        \"\"\"\n        Calculate cyclomatic complexity using McCabe's method.\n        Count decision points: if, elif, else, for, while, except, and, or\n        \"\"\"\n        complexity = 1  # Base complexity\n\n        # Count decision points\n        decision_patterns = [\n            r'\\bif\\b',\n            r'\\belif\\b',\n            r'\\bfor\\b',\n            r'\\bwhile\\b',\n            r'\\bexcept\\b',\n            r'\\band\\b(?!$)',\n            r'\\bor\\b(?!$)'\n        ]\n\n        for pattern in decision_patterns:\n            matches = re.findall(pattern, self.code)\n            complexity += len(matches)\n\n        return complexity\n\n    def calculate_cognitive_complexity(self) -> int:\n        \"\"\"\n        Calculate cognitive complexity - how hard is it to understand?\n        Based on nesting depth and control flow.\n        \"\"\"\n        cognitive = 0\n        nesting_depth = 0\n\n        for line in self.lines:\n            # Track nesting depth\n            if re.search(r'^\\s*(if|for|while|def|class|try)\\b', line):\n                nesting_depth += 1\n                cognitive += nesting_depth\n            elif re.search(r'^\\s*(elif|else|except|finally)\\b', line):\n                cognitive += nesting_depth\n\n            # Reduce nesting when unindenting\n            if line and not line[0].isspace():\n                nesting_depth = 0\n\n        return cognitive\n\n    def calculate_maintainability_index(self) -> float:\n        \"\"\"\n        Maintainability Index ranges from 0-100.\n        > 85: Excellent\n        > 65: Good\n        > 50: Fair\n        < 50: Poor\n        \"\"\"\n        lines = len(self.lines)\n        cyclomatic = self.calculate_cyclomatic_complexity()\n        cognitive = self.calculate_cognitive_complexity()\n\n        # Simplified MI calculation\n        mi = 171 - 5.2 * (cyclomatic / lines) - 0.23 * (cognitive) - 16.2 * (lines / 1000)\n\n        return max(0, min(100, mi))\n\n    def get_complexity_report(self) -> Dict:\n        \"\"\"Generate comprehensive complexity report.\"\"\"\n        return {\n            'cyclomatic_complexity': self.calculate_cyclomatic_complexity(),\n            'cognitive_complexity': self.calculate_cognitive_complexity(),\n            'maintainability_index': round(self.calculate_maintainability_index(), 2),\n            'lines_of_code': len(self.lines),\n            'avg_line_length': round(sum(len(l) for l in self.lines) / len(self.lines), 2) if self.lines else 0\n        }\n\n\ndef compare_files(before_file: str, after_file: str) -> None:\n    \"\"\"Compare complexity metrics between two code versions.\"\"\"\n\n    with open(before_file, 'r') as f:\n        before_code = f.read()\n\n    with open(after_file, 'r') as f:\n        after_code = f.read()\n\n    before_analyzer = ComplexityAnalyzer(before_code)\n    after_analyzer = ComplexityAnalyzer(after_code)\n\n    before_metrics = before_analyzer.get_complexity_report()\n    after_metrics = after_analyzer.get_complexity_report()\n\n    print(\"=\" * 60)\n    print(\"CODE COMPLEXITY COMPARISON\")\n    print(\"=\" * 60)\n\n    print(\"\\nBEFORE:\")\n    print(f\"  Cyclomatic Complexity:    {before_metrics['cyclomatic_complexity']}\")\n    print(f\"  Cognitive Complexity:     {before_metrics['cognitive_complexity']}\")\n    print(f\"  Maintainability Index:    {before_metrics['maintainability_index']}\")\n    print(f\"  Lines of Code:            {before_metrics['lines_of_code']}\")\n    print(f\"  Avg Line Length:          {before_metrics['avg_line_length']}\")\n\n    print(\"\\nAFTER:\")\n    print(f\"  Cyclomatic Complexity:    {after_metrics['cyclomatic_complexity']}\")\n    print(f\"  Cognitive Complexity:     {after_metrics['cognitive_complexity']}\")\n    print(f\"  Maintainability Index:    {after_metrics['maintainability_index']}\")\n    print(f\"  Lines of Code:            {after_metrics['lines_of_code']}\")\n    print(f\"  Avg Line Length:          {after_metrics['avg_line_length']}\")\n\n    print(\"\\nCHANGES:\")\n    cyclomatic_change = after_metrics['cyclomatic_complexity'] - before_metrics['cyclomatic_complexity']\n    cognitive_change = after_metrics['cognitive_complexity'] - before_metrics['cognitive_complexity']\n    mi_change = after_metrics['maintainability_index'] - before_metrics['maintainability_index']\n    loc_change = after_metrics['lines_of_code'] - before_metrics['lines_of_code']\n\n    print(f\"  Cyclomatic Complexity:    {cyclomatic_change:+d}\")\n    print(f\"  Cognitive Complexity:     {cognitive_change:+d}\")\n    print(f\"  Maintainability Index:    {mi_change:+.2f}\")\n    print(f\"  Lines of Code:            {loc_change:+d}\")\n\n    print(\"\\nASSESSMENT:\")\n    if mi_change > 0:\n        print(\"  ✅ Code is MORE maintainable\")\n    elif mi_change < 0:\n        print(\"  ⚠️  Code is LESS maintainable\")\n    else:\n        print(\"  ➡️  Maintainability unchanged\")\n\n    if cyclomatic_change < 0:\n        print(\"  ✅ Complexity DECREASED\")\n    elif cyclomatic_change > 0:\n        print(\"  ⚠️  Complexity INCREASED\")\n    else:\n        print(\"  ➡️  Complexity unchanged\")\n\n    print(\"=\" * 60)\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 3:\n        print(\"Usage: python compare-complexity.py <before_file> <after_file>\")\n        sys.exit(1)\n\n    compare_files(sys.argv[1], sys.argv[2])\n```\n\n## Template: review-checklist.md\n\n```markdown\n# Code Review Checklist\n\n## Security Checklist\n- [ ] No hardcoded credentials or secrets\n- [ ] Input validation on all user inputs\n- [ ] SQL injection prevention (parameterized queries)\n- [ ] CSRF protection on state-changing operations\n- [ ] XSS prevention with proper escaping\n- [ ] Authentication checks on protected endpoints\n- [ ] Authorization checks on resources\n- [ ] Secure password hashing (bcrypt, argon2)\n- [ ] No sensitive data in logs\n- [ ] HTTPS enforced\n\n## Performance Checklist\n- [ ] No N+1 queries\n- [ ] Appropriate use of indexes\n- [ ] Caching implemented where beneficial\n- [ ] No blocking operations on main thread\n- [ ] Async/await used correctly\n- [ ] Large datasets paginated\n- [ ] Database connections pooled\n- [ ] Regular expressions optimized\n- [ ] No unnecessary object creation\n- [ ] Memory leaks prevented\n\n## Quality Checklist\n- [ ] Functions < 50 lines\n- [ ] Clear variable naming\n- [ ] No duplicate code\n- [ ] Proper error handling\n- [ ] Comments explain WHY, not WHAT\n- [ ] No console.logs in production\n- [ ] Type checking (TypeScript/JSDoc)\n- [ ] SOLID principles followed\n- [ ] Design patterns applied correctly\n- [ ] Self-documenting code\n\n## Testing Checklist\n- [ ] Unit tests written\n- [ ] Edge cases covered\n- [ ] Error scenarios tested\n- [ ] Integration tests present\n- [ ] Coverage > 80%\n- [ ] No flaky tests\n- [ ] Mock external dependencies\n- [ ] Clear test names\n```\n\n## Template: finding-template.md\n\n~~~~markdown\n# Code Review Finding Template\n\nUse this template when documenting each issue found during code review.\n\n---\n\n## Issue: [TITLE]\n\n### Severity\n- [ ] Critical (blocks deployment)\n- [ ] High (should fix before merge)\n- [ ] Medium (should fix soon)\n- [ ] Low (nice to have)\n\n### Category\n- [ ] Security\n- [ ] Performance\n- [ ] Code Quality\n- [ ] Maintainability\n- [ ] Testing\n- [ ] Design Pattern\n- [ ] Documentation\n\n### Location\n**File:** `src/components/UserCard.tsx`\n\n**Lines:** 45-52\n\n**Function/Method:** `renderUserDetails()`\n\n### Issue Description\n\n**What:** Describe what the issue is.\n\n**Why it matters:** Explain the impact and why this needs to be fixed.\n\n**Current behavior:** Show the problematic code or behavior.\n\n**Expected behavior:** Describe what should happen instead.\n\n### Code Example\n\n#### Current (Problematic)\n\n```typescript\n// Shows the N+1 query problem\nconst users = fetchUsers();\nusers.forEach(user => {\n  const posts = fetchUserPosts(user.id); // Query per user!\n  renderUserPosts(posts);\n});\n```\n\n#### Suggested Fix\n\n```typescript\n// Optimized with JOIN query\nconst usersWithPosts = fetchUsersWithPosts();\nusersWithPosts.forEach(({ user, posts }) => {\n  renderUserPosts(posts);\n});\n```\n\n### Impact Analysis\n\n| Aspect | Impact | Severity |\n|--------|--------|----------|\n| Performance | 100+ queries for 20 users | High |\n| User Experience | Slow page load | High |\n| Scalability | Breaks at scale | Critical |\n| Maintainability | Hard to debug | Medium |\n\n### Related Issues\n\n- Similar issue in `AdminUserList.tsx` line 120\n- Related PR: #456\n- Related issue: #789\n\n### Additional Resources\n\n- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem)\n- [Database Join Documentation](https://docs.example.com/joins)\n- [Performance Optimization Guide](./docs/performance.md)\n\n### Reviewer Notes\n\n- This is a common pattern in this codebase\n- Consider adding this to the code style guide\n- Might be worth creating a helper function\n\n### Author Response (for feedback)\n\n*To be filled by the code author:*\n\n- [ ] Fix implemented in commit: `abc123`\n- [ ] Fix status: Complete / In Progress / Needs Discussion\n- [ ] Questions or concerns: (describe)\n\n---\n\n## Finding Statistics (for Reviewer)\n\nWhen reviewing multiple findings, track:\n\n- **Total Issues Found:** X\n- **Critical:** X\n- **High:** X\n- **Medium:** X\n- **Low:** X\n\n**Recommendation:** ✅ Approve / ⚠️ Request Changes / 🔄 Needs Discussion\n\n**Overall Code Quality:** 1-5 stars\n~~~~\n\n## Usage Example\n\n~~~~markdown\nUser: Review this React component code\n\nClaude: I'll conduct a comprehensive code review using my Code Review Skill.\n\n[Loads SKILL.md]\n[Analyzes code against checklist]\n[Runs Python metrics script]\n[Applies templates]\n\n## Code Review Results\n\n### Summary\nQuality Score: 3.5/5\nKey Findings: 7 items\nPriority Areas: Performance optimization, error handling\n\n### Critical Issues: 1\n\n**Issue**: N+1 Query Problem\n**Location**: UserComponent.tsx, lines 45-52\n**Impact**: Renders 100+ database queries for list of 20 users\n**Severity**: High\n**Fix**:\n```javascript\n// Before: N+1 queries\nconst users = fetchUsers();\nusers.forEach(user => fetchUserPosts(user.id)); // 20+ queries\n\n// After: Single query with JOIN\nconst users = fetchUsersWithPosts(); // 1 query\n```\n\n### Performance Findings\n- Missing pagination on large lists\n- Recommendation: Use React.memo() for items\n- Database query: Could be optimized with index\n\n### Quality Findings\n- Function in line 20 is 127 lines (max: 50)\n- Missing error boundary\n- Props should have TypeScript types\n~~~~\n\n#### Example 2: Brand Voice Skill\n\n**Directory Structure:**\n\n```\n.claude/skills/brand-voice/\n├── SKILL.md\n├── brand-guidelines.md\n├── tone-examples.md\n└── templates/\n    ├── email-template.txt\n    ├── social-post-template.txt\n    └── blog-post-template.md\n```\n\n**File:** `.claude/skills/brand-voice/SKILL.md`\n\n```yaml\n---\nname: Brand Voice Consistency\ndescription: Ensure all communication matches brand voice and tone guidelines\ntags:\n  - brand\n  - writing\n  - consistency\nwhen_to_use: When creating marketing copy, customer communications, or public-facing content\n---\n\n# Brand Voice Skill\n\n## Overview\nThis skill ensures all communications maintain consistent brand voice, tone, and messaging.\n\n## Brand Identity\n\n### Mission\nHelp teams automate their development workflows with AI\n\n### Values\n- **Simplicity**: Make complex things simple\n- **Reliability**: Rock-solid execution\n- **Empowerment**: Enable human creativity\n\n### Tone of Voice\n- **Friendly but professional** - approachable without being casual\n- **Clear and concise** - avoid jargon, explain technical concepts simply\n- **Confident** - we know what we're doing\n- **Empathetic** - understand user needs and pain points\n\n## Writing Guidelines\n\n### Do's ✅\n- Use \"you\" when addressing readers\n- Use active voice: \"Claude generates reports\" not \"Reports are generated by Claude\"\n- Start with value proposition\n- Use concrete examples\n- Keep sentences under 20 words\n- Use lists for clarity\n- Include calls-to-action\n\n### Don'ts ❌\n- Don't use corporate jargon\n- Don't patronize or oversimplify\n- Don't use \"we believe\" or \"we think\"\n- Don't use ALL CAPS except for emphasis\n- Don't create walls of text\n- Don't assume technical knowledge\n\n## Vocabulary\n\n### ✅ Preferred Terms\n- Claude (not \"the Claude AI\")\n- Code generation (not \"auto-coding\")\n- Agent (not \"bot\")\n- Streamline (not \"revolutionize\")\n- Integrate (not \"synergize\")\n\n### ❌ Avoid Terms\n- \"Cutting-edge\" (overused)\n- \"Game-changer\" (vague)\n- \"Leverage\" (corporate-speak)\n- \"Utilize\" (use \"use\")\n- \"Paradigm shift\" (unclear)\n```\n## Examples\n\n### ✅ Good Example\n\"Claude automates your code review process. Instead of manually checking each PR, Claude reviews security, performance, and quality—saving your team hours every week.\"\n\nWhy it works: Clear value, specific benefits, action-oriented\n\n### ❌ Bad Example\n\"Claude leverages cutting-edge AI to provide comprehensive software development solutions.\"\n\nWhy it doesn't work: Vague, corporate jargon, no specific value\n\n## Template: Email\n\n```\nSubject: [Clear, benefit-driven subject]\n\nHi [Name],\n\n[Opening: What's the value for them]\n\n[Body: How it works / What they'll get]\n\n[Specific example or benefit]\n\n[Call to action: Clear next step]\n\nBest regards,\n[Name]\n```\n\n## Template: Social Media\n\n```\n[Hook: Grab attention in first line]\n[2-3 lines: Value or interesting fact]\n[Call to action: Link, question, or engagement]\n[Emoji: 1-2 max for visual interest]\n```\n\n## File: tone-examples.md\n```\nExciting announcement:\n\"Save 8 hours per week on code reviews. Claude reviews your PRs automatically.\"\n\nEmpathetic support:\n\"We know deployments can be stressful. Claude handles testing so you don't have to worry.\"\n\nConfident product feature:\n\"Claude doesn't just suggest code. It understands your architecture and maintains consistency.\"\n\nEducational blog post:\n\"Let's explore how agents improve code review workflows. Here's what we learned...\"\n```\n\n#### Example 3: Documentation Generator Skill\n\n**File:** `.claude/skills/doc-generator/SKILL.md`\n\n~~~~yaml\n---\nname: API Documentation Generator\ndescription: Generate comprehensive, accurate API documentation from source code\nversion: \"1.0.0\"\ntags:\n  - documentation\n  - api\n  - automation\nwhen_to_use: When creating or updating API documentation\n---\n\n# API Documentation Generator Skill\n\n## Generates\n\n- OpenAPI/Swagger specifications\n- API endpoint documentation\n- SDK usage examples\n- Integration guides\n- Error code references\n- Authentication guides\n\n## Documentation Structure\n\n### For Each Endpoint\n\n```markdown\n## GET /api/v1/users/:id\n\n### Description\nBrief explanation of what this endpoint does\n\n### Parameters\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| id | string | Yes | User ID |\n\n### Response\n\n**200 Success**\n```json\n{\n  \"id\": \"usr_123\",\n  \"name\": \"John Doe\",\n  \"email\": \"john@example.com\",\n  \"created_at\": \"2025-01-15T10:30:00Z\"\n}\n```\n\n**404 Not Found**\n```json\n{\n  \"error\": \"USER_NOT_FOUND\",\n  \"message\": \"User does not exist\"\n}\n```\n\n### Examples\n\n**cURL**\n```bash\ncurl -X GET \"https://api.example.com/api/v1/users/usr_123\" \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\n**JavaScript**\n```javascript\nconst user = await fetch('/api/v1/users/usr_123', {\n  headers: { 'Authorization': 'Bearer token' }\n}).then(r => r.json());\n```\n\n**Python**\n```python\nresponse = requests.get(\n    'https://api.example.com/api/v1/users/usr_123',\n    headers={'Authorization': 'Bearer token'}\n)\nuser = response.json()\n```\n\n## Python Script: generate-docs.py\n\n```python\n#!/usr/bin/env python3\nimport ast\nimport json\nfrom typing import Dict, List\n\nclass APIDocExtractor(ast.NodeVisitor):\n    \"\"\"Extract API documentation from Python source code.\"\"\"\n\n    def __init__(self):\n        self.endpoints = []\n\n    def visit_FunctionDef(self, node):\n        \"\"\"Extract function documentation.\"\"\"\n        if node.name.startswith('get_') or node.name.startswith('post_'):\n            doc = ast.get_docstring(node)\n            endpoint = {\n                'name': node.name,\n                'docstring': doc,\n                'params': [arg.arg for arg in node.args.args],\n                'returns': self._extract_return_type(node)\n            }\n            self.endpoints.append(endpoint)\n        self.generic_visit(node)\n\n    def _extract_return_type(self, node):\n        \"\"\"Extract return type from function annotation.\"\"\"\n        if node.returns:\n            return ast.unparse(node.returns)\n        return \"Any\"\n\ndef generate_markdown_docs(endpoints: List[Dict]) -> str:\n    \"\"\"Generate markdown documentation from endpoints.\"\"\"\n    docs = \"# API Documentation\\n\\n\"\n\n    for endpoint in endpoints:\n        docs += f\"## {endpoint['name']}\\n\\n\"\n        docs += f\"{endpoint['docstring']}\\n\\n\"\n        docs += f\"**Parameters**: {', '.join(endpoint['params'])}\\n\\n\"\n        docs += f\"**Returns**: {endpoint['returns']}\\n\\n\"\n        docs += \"---\\n\\n\"\n\n    return docs\n\nif __name__ == '__main__':\n    import sys\n    with open(sys.argv[1], 'r') as f:\n        tree = ast.parse(f.read())\n\n    extractor = APIDocExtractor()\n    extractor.visit(tree)\n\n    markdown = generate_markdown_docs(extractor.endpoints)\n    print(markdown)\n~~~~\n### Skill Discovery & Invocation\n\n```mermaid\ngraph TD\n    A[\"User Request\"] --> B[\"Claude Analyzes\"]\n    B -->|Scans| C[\"Available Skills\"]\n    C -->|Metadata check| D[\"Skill Description Match?\"]\n    D -->|Yes| E[\"Load SKILL.md\"]\n    D -->|No| F[\"Try next skill\"]\n    F -->|More skills?| D\n    F -->|No more| G[\"Use general knowledge\"]\n    E --> H[\"Extract Instructions\"]\n    H --> I[\"Execute Skill\"]\n    I --> J[\"Return Results\"]\n```\n\n### Skill vs Other Features\n\n```mermaid\ngraph TB\n    A[\"Extending Claude\"]\n    B[\"Slash Commands\"]\n    C[\"Subagents\"]\n    D[\"Memory\"]\n    E[\"MCP\"]\n    F[\"Skills\"]\n\n    A --> B\n    A --> C\n    A --> D\n    A --> E\n    A --> F\n\n    B -->|User-invoked| G[\"Quick shortcuts\"]\n    C -->|Auto-delegated| H[\"Isolated contexts\"]\n    D -->|Persistent| I[\"Cross-session context\"]\n    E -->|Real-time| J[\"External data access\"]\n    F -->|Auto-invoked| K[\"Autonomous execution\"]\n```\n\n---\n\n## Claude Code Plugins\n\n### Overview\n\nClaude 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.\n\n### Architecture\n\n```mermaid\ngraph TB\n    A[\"Plugin\"]\n    B[\"Slash Commands\"]\n    C[\"Subagents\"]\n    D[\"MCP Servers\"]\n    E[\"Hooks\"]\n    F[\"Configuration\"]\n\n    A -->|bundles| B\n    A -->|bundles| C\n    A -->|bundles| D\n    A -->|bundles| E\n    A -->|bundles| F\n```\n\n### Plugin Loading Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Plugin as Plugin Marketplace\n    participant Install as Installation\n    participant SlashCmds as Slash Commands\n    participant Subagents\n    participant MCPServers as MCP Servers\n    participant Hooks\n    participant Tools as Configured Tools\n\n    User->>Claude: /plugin install pr-review\n    Claude->>Plugin: Download plugin manifest\n    Plugin-->>Claude: Return plugin definition\n    Claude->>Install: Extract components\n    Install->>SlashCmds: Configure\n    Install->>Subagents: Configure\n    Install->>MCPServers: Configure\n    Install->>Hooks: Configure\n    SlashCmds-->>Tools: Ready to use\n    Subagents-->>Tools: Ready to use\n    MCPServers-->>Tools: Ready to use\n    Hooks-->>Tools: Ready to use\n    Tools-->>Claude: Plugin installed ✅\n```\n\n### Plugin Types & Distribution\n\n| Type | Scope | Shared | Authority | Examples |\n|------|-------|--------|-----------|----------|\n| Official | Global | All users | Anthropic | PR Review, Security Guidance |\n| Community | Public | All users | Community | DevOps, Data Science |\n| Organization | Internal | Team members | Company | Internal standards, tools |\n| Personal | Individual | Single user | Developer | Custom workflows |\n\n### Plugin Definition Structure\n\n```yaml\n---\nname: plugin-name\nversion: \"1.0.0\"\ndescription: \"What this plugin does\"\nauthor: \"Your Name\"\nlicense: MIT\n\n# Plugin metadata\ntags:\n  - category\n  - use-case\n\n# Requirements\nrequires:\n  - claude-code: \">=1.0.0\"\n\n# Components bundled\ncomponents:\n  - type: commands\n    path: commands/\n  - type: agents\n    path: agents/\n  - type: mcp\n    path: mcp/\n  - type: hooks\n    path: hooks/\n\n# Configuration\nconfig:\n  auto_load: true\n  enabled_by_default: true\n---\n```\n\n### Plugin Structure\n\n```\nmy-plugin/\n├── .claude-plugin/\n│   └── plugin.json\n├── commands/\n│   ├── task-1.md\n│   ├── task-2.md\n│   └── workflows/\n├── agents/\n│   ├── specialist-1.md\n│   ├── specialist-2.md\n│   └── configs/\n├── skills/\n│   ├── skill-1.md\n│   └── skill-2.md\n├── hooks/\n│   └── hooks.json\n├── .mcp.json\n├── .lsp.json\n├── settings.json\n├── templates/\n│   └── issue-template.md\n├── scripts/\n│   ├── helper-1.sh\n│   └── helper-2.py\n├── docs/\n│   ├── README.md\n│   └── USAGE.md\n└── tests/\n    └── plugin.test.js\n```\n\n### Practical Examples\n\n#### Example 1: PR Review Plugin\n\n**File:** `.claude-plugin/plugin.json`\n\n```json\n{\n  \"name\": \"pr-review\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Complete PR review workflow with security, testing, and docs\",\n  \"author\": {\n    \"name\": \"Anthropic\"\n  },\n  \"license\": \"MIT\"\n}\n```\n\n**File:** `commands/review-pr.md`\n\n```markdown\n---\nname: Review PR\ndescription: Start comprehensive PR review with security and testing checks\n---\n\n# PR Review\n\nThis command initiates a complete pull request review including:\n\n1. Security analysis\n2. Test coverage verification\n3. Documentation updates\n4. Code quality checks\n5. Performance impact assessment\n```\n\n**File:** `agents/security-reviewer.md`\n\n```yaml\n---\nname: security-reviewer\ndescription: Security-focused code review\ntools: read, grep, diff\n---\n\n# Security Reviewer\n\nSpecializes in finding security vulnerabilities:\n- Authentication/authorization issues\n- Data exposure\n- Injection attacks\n- Secure configuration\n```\n\n**Installation:**\n\n```bash\n/plugin install pr-review\n\n# Result:\n# ✅ 3 slash commands installed\n# ✅ 3 subagents configured\n# ✅ 2 MCP servers connected\n# ✅ 4 hooks registered\n# ✅ Ready to use!\n```\n\n#### Example 2: DevOps Plugin\n\n**Components:**\n\n```\ndevops-automation/\n├── commands/\n│   ├── deploy.md\n│   ├── rollback.md\n│   ├── status.md\n│   └── incident.md\n├── agents/\n│   ├── deployment-specialist.md\n│   ├── incident-commander.md\n│   └── alert-analyzer.md\n├── mcp/\n│   ├── github-config.json\n│   ├── kubernetes-config.json\n│   └── prometheus-config.json\n├── hooks/\n│   ├── pre-deploy.js\n│   ├── post-deploy.js\n│   └── on-error.js\n└── scripts/\n    ├── deploy.sh\n    ├── rollback.sh\n    └── health-check.sh\n```\n\n#### Example 3: Documentation Plugin\n\n**Bundled Components:**\n\n```\ndocumentation/\n├── commands/\n│   ├── generate-api-docs.md\n│   ├── generate-readme.md\n│   ├── sync-docs.md\n│   └── validate-docs.md\n├── agents/\n│   ├── api-documenter.md\n│   ├── code-commentator.md\n│   └── example-generator.md\n├── mcp/\n│   ├── github-docs-config.json\n│   └── slack-announce-config.json\n└── templates/\n    ├── api-endpoint.md\n    ├── function-docs.md\n    └── adr-template.md\n```\n\n### Plugin Marketplace\n\n```mermaid\ngraph TB\n    A[\"Plugin Marketplace\"]\n    B[\"Official<br/>Anthropic\"]\n    C[\"Community<br/>Marketplace\"]\n    D[\"Enterprise<br/>Registry\"]\n\n    A --> B\n    A --> C\n    A --> D\n\n    B -->|Categories| B1[\"Development\"]\n    B -->|Categories| B2[\"DevOps\"]\n    B -->|Categories| B3[\"Documentation\"]\n\n    C -->|Search| C1[\"DevOps Automation\"]\n    C -->|Search| C2[\"Mobile Dev\"]\n    C -->|Search| C3[\"Data Science\"]\n\n    D -->|Internal| D1[\"Company Standards\"]\n    D -->|Internal| D2[\"Legacy Systems\"]\n    D -->|Internal| D3[\"Compliance\"]\n```\n\n### Plugin Installation & Lifecycle\n\n```mermaid\ngraph LR\n    A[\"Discover\"] -->|Browse| B[\"Marketplace\"]\n    B -->|Select| C[\"Plugin Page\"]\n    C -->|View| D[\"Components\"]\n    D -->|Install| E[\"/plugin install\"]\n    E -->|Extract| F[\"Configure\"]\n    F -->|Activate| G[\"Use\"]\n    G -->|Check| H[\"Update\"]\n    H -->|Available| G\n    G -->|Done| I[\"Disable\"]\n    I -->|Later| J[\"Enable\"]\n    J -->|Back| G\n```\n\n### Plugin Features Comparison\n\n| Feature | Slash Command | Skill | Subagent | Plugin |\n|---------|---------------|-------|----------|--------|\n| **Installation** | Manual copy | Manual copy | Manual config | One command |\n| **Setup Time** | 5 minutes | 10 minutes | 15 minutes | 2 minutes |\n| **Bundling** | Single file | Single file | Single file | Multiple |\n| **Versioning** | Manual | Manual | Manual | Automatic |\n| **Team Sharing** | Copy file | Copy file | Copy file | Install ID |\n| **Updates** | Manual | Manual | Manual | Auto-available |\n| **Dependencies** | None | None | None | May include |\n| **Marketplace** | No | No | No | Yes |\n| **Distribution** | Repository | Repository | Repository | Marketplace |\n\n### Plugin Use Cases\n\n| Use Case | Recommendation | Why |\n|----------|-----------------|-----|\n| **Team Onboarding** | ✅ Use Plugin | Instant setup, all configurations |\n| **Framework Setup** | ✅ Use Plugin | Bundles framework-specific commands |\n| **Enterprise Standards** | ✅ Use Plugin | Central distribution, version control |\n| **Quick Task Automation** | ❌ Use Command | Overkill complexity |\n| **Single Domain Expertise** | ❌ Use Skill | Too heavy, use skill instead |\n| **Specialized Analysis** | ❌ Use Subagent | Create manually or use skill |\n| **Live Data Access** | ❌ Use MCP | Standalone, don't bundle |\n\n### When to Create a Plugin\n\n```mermaid\ngraph TD\n    A[\"Should I create a plugin?\"]\n    A -->|Need multiple components| B{\"Multiple commands<br/>or subagents<br/>or MCPs?\"}\n    B -->|Yes| C[\"✅ Create Plugin\"]\n    B -->|No| D[\"Use Individual Feature\"]\n    A -->|Team workflow| E{\"Share with<br/>team?\"}\n    E -->|Yes| C\n    E -->|No| F[\"Keep as Local Setup\"]\n    A -->|Complex setup| G{\"Needs auto<br/>configuration?\"}\n    G -->|Yes| C\n    G -->|No| D\n```\n\n### Publishing a Plugin\n\n**Steps to publish:**\n\n1. Create plugin structure with all components\n2. Write `.claude-plugin/plugin.json` manifest\n3. Create `README.md` with documentation\n4. Test locally with `/plugin install ./my-plugin`\n5. Submit to plugin marketplace\n6. Get reviewed and approved\n7. Published on marketplace\n8. Users can install with one command\n\n**Example submission:**\n\n~~~~markdown\n# PR Review Plugin\n\n## Description\nComplete PR review workflow with security, testing, and documentation checks.\n\n## What's Included\n- 3 slash commands for different review types\n- 3 specialized subagents\n- GitHub and CodeQL MCP integration\n- Automated security scanning hooks\n\n## Installation\n```bash\n/plugin install pr-review\n```\n\n## Features\n✅ Security analysis\n✅ Test coverage checking\n✅ Documentation verification\n✅ Code quality assessment\n✅ Performance impact analysis\n\n## Usage\n```bash\n/review-pr\n/check-security\n/check-tests\n```\n\n## Requirements\n- Claude Code 1.0+\n- GitHub access\n- CodeQL (optional)\n~~~~\n\n### Plugin vs Manual Configuration\n\n**Manual Setup (2+ hours):**\n- Install slash commands one by one\n- Create subagents individually\n- Configure MCPs separately\n- Set up hooks manually\n- Document everything\n- Share with team (hope they configure correctly)\n\n**With Plugin (2 minutes):**\n```bash\n/plugin install pr-review\n# ✅ Everything installed and configured\n# ✅ Ready to use immediately\n# ✅ Team can reproduce exact setup\n```\n\n---\n\n## Comparison & Integration\n\n### Feature Comparison Matrix\n\n| Feature | Invocation | Persistence | Scope | Use Case |\n|---------|-----------|------------|-------|----------|\n| **Slash Commands** | Manual (`/cmd`) | Session only | Single command | Quick shortcuts |\n| **Subagents** | Auto-delegated | Isolated context | Specialized task | Task distribution |\n| **Memory** | Auto-loaded | Cross-session | User/team context | Long-term learning |\n| **MCP Protocol** | Auto-queried | Real-time external | Live data access | Dynamic information |\n| **Skills** | Auto-invoked | Filesystem-based | Reusable expertise | Automated workflows |\n\n### Interaction Timeline\n\n```mermaid\ngraph LR\n    A[\"Session Start\"] -->|Load| B[\"Memory (CLAUDE.md)\"]\n    B -->|Discover| C[\"Available Skills\"]\n    C -->|Register| D[\"Slash Commands\"]\n    D -->|Connect| E[\"MCP Servers\"]\n    E -->|Ready| F[\"User Interaction\"]\n\n    F -->|Type /cmd| G[\"Slash Command\"]\n    F -->|Request| H[\"Skill Auto-Invoke\"]\n    F -->|Query| I[\"MCP Data\"]\n    F -->|Complex task| J[\"Delegate to Subagent\"]\n\n    G -->|Uses| B\n    H -->|Uses| B\n    I -->|Uses| B\n    J -->|Uses| B\n```\n\n### Practical Integration Example: Customer Support Automation\n\n#### Architecture\n\n```mermaid\ngraph TB\n    User[\"Customer Email\"] -->|Receives| Router[\"Support Router\"]\n\n    Router -->|Analyze| Memory[\"Memory<br/>Customer history\"]\n    Router -->|Lookup| MCP1[\"MCP: Customer DB<br/>Previous tickets\"]\n    Router -->|Check| MCP2[\"MCP: Slack<br/>Team status\"]\n\n    Router -->|Route Complex| Sub1[\"Subagent: Tech Support<br/>Context: Technical issues\"]\n    Router -->|Route Simple| Sub2[\"Subagent: Billing<br/>Context: Payment issues\"]\n    Router -->|Route Urgent| Sub3[\"Subagent: Escalation<br/>Context: Priority handling\"]\n\n    Sub1 -->|Format| Skill1[\"Skill: Response Generator<br/>Brand voice maintained\"]\n    Sub2 -->|Format| Skill2[\"Skill: Response Generator\"]\n    Sub3 -->|Format| Skill3[\"Skill: Response Generator\"]\n\n    Skill1 -->|Generate| Output[\"Formatted Response\"]\n    Skill2 -->|Generate| Output\n    Skill3 -->|Generate| Output\n\n    Output -->|Post| MCP3[\"MCP: Slack<br/>Notify team\"]\n    Output -->|Send| Reply[\"Customer Reply\"]\n```\n\n#### Request Flow\n\n```markdown\n## Customer Support Request Flow\n\n### 1. Incoming Email\n\"I'm getting error 500 when trying to upload files. This is blocking my workflow!\"\n\n### 2. Memory Lookup\n- Loads CLAUDE.md with support standards\n- Checks customer history: VIP customer, 3rd incident this month\n\n### 3. MCP Queries\n- GitHub MCP: List open issues (finds related bug report)\n- Database MCP: Check system status (no outages reported)\n- Slack MCP: Check if engineering is aware\n\n### 4. Skill Detection & Loading\n- Request matches \"Technical Support\" skill\n- Loads support response template from Skill\n\n### 5. Subagent Delegation\n- Routes to Tech Support Subagent\n- Provides context: customer history, error details, known issues\n- Subagent has full access to: read, bash, grep tools\n\n### 6. Subagent Processing\nTech Support Subagent:\n- Searches codebase for 500 error in file upload\n- Finds recent change in commit 8f4a2c\n- Creates workaround documentation\n\n### 7. Skill Execution\nResponse Generator Skill:\n- Uses Brand Voice guidelines\n- Formats response with empathy\n- Includes workaround steps\n- Links to related documentation\n\n### 8. MCP Output\n- Posts update to #support Slack channel\n- Tags engineering team\n- Updates ticket in Jira MCP\n\n### 9. Response\nCustomer receives:\n- Empathetic acknowledgment\n- Explanation of cause\n- Immediate workaround\n- Timeline for permanent fix\n- Link to related issues\n```\n\n### Complete Feature Orchestration\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Claude as Claude Code\n    participant Memory as Memory<br/>CLAUDE.md\n    participant MCP as MCP Servers\n    participant Skills as Skills\n    participant SubAgent as Subagents\n\n    User->>Claude: Request: \"Build auth system\"\n    Claude->>Memory: Load project standards\n    Memory-->>Claude: Auth standards, team practices\n    Claude->>MCP: Query GitHub for similar implementations\n    MCP-->>Claude: Code examples, best practices\n    Claude->>Skills: Detect matching Skills\n    Skills-->>Claude: Security Review Skill + Testing Skill\n    Claude->>SubAgent: Delegate implementation\n    SubAgent->>SubAgent: Build feature\n    Claude->>Skills: Apply Security Review Skill\n    Skills-->>Claude: Security checklist results\n    Claude->>SubAgent: Delegate testing\n    SubAgent-->>Claude: Test results\n    Claude->>User: Complete system delivered\n```\n\n### When to Use Each Feature\n\n```mermaid\ngraph TD\n    A[\"New Task\"] --> B{Type of Task?}\n\n    B -->|Repeated workflow| C[\"Slash Command\"]\n    B -->|Need real-time data| D[\"MCP Protocol\"]\n    B -->|Remember for next time| E[\"Memory\"]\n    B -->|Specialized subtask| F[\"Subagent\"]\n    B -->|Domain-specific work| G[\"Skill\"]\n\n    C --> C1[\"✅ Team shortcut\"]\n    D --> D1[\"✅ Live API access\"]\n    E --> E1[\"✅ Persistent context\"]\n    F --> F1[\"✅ Parallel execution\"]\n    G --> G1[\"✅ Auto-invoked expertise\"]\n```\n\n### Selection Decision Tree\n\n```mermaid\ngraph TD\n    Start[\"Need to extend Claude?\"]\n\n    Start -->|Quick repeated task| A{\"Manual or Auto?\"}\n    A -->|Manual| B[\"Slash Command\"]\n    A -->|Auto| C[\"Skill\"]\n\n    Start -->|Need external data| D{\"Real-time?\"}\n    D -->|Yes| E[\"MCP Protocol\"]\n    D -->|No/Cross-session| F[\"Memory\"]\n\n    Start -->|Complex project| G{\"Multiple roles?\"}\n    G -->|Yes| H[\"Subagents\"]\n    G -->|No| I[\"Skills + Memory\"]\n\n    Start -->|Long-term context| J[\"Memory\"]\n    Start -->|Team workflow| K[\"Slash Command +<br/>Memory\"]\n    Start -->|Full automation| L[\"Skills +<br/>Subagents +<br/>MCP\"]\n```\n\n---\n\n## Summary Table\n\n| Aspect | Slash Commands | Subagents | Memory | MCP | Skills | Plugins |\n|--------|---|---|---|---|---|---|\n| **Setup Difficulty** | Easy | Medium | Easy | Medium | Medium | Easy |\n| **Learning Curve** | Low | Medium | Low | Medium | Medium | Low |\n| **Team Benefit** | High | High | Medium | High | High | Very High |\n| **Automation Level** | Low | High | Medium | High | High | Very High |\n| **Context Management** | Single-session | Isolated | Persistent | Real-time | Persistent | All features |\n| **Maintenance Burden** | Low | Medium | Low | Medium | Medium | Low |\n| **Scalability** | Good | Excellent | Good | Excellent | Excellent | Excellent |\n| **Shareability** | Fair | Fair | Good | Good | Good | Excellent |\n| **Versioning** | Manual | Manual | Manual | Manual | Manual | Automatic |\n| **Installation** | Manual copy | Manual config | N/A | Manual config | Manual copy | One command |\n\n---\n\n## Quick Start Guide\n\n### Week 1: Start Simple\n- Create 2-3 slash commands for common tasks\n- Enable Memory in Settings\n- Document team standards in CLAUDE.md\n\n### Week 2: Add Real-time Access\n- Set up 1 MCP (GitHub or Database)\n- Use `/mcp` to configure\n- Query live data in your workflows\n\n### Week 3: Distribute Work\n- Create first Subagent for specific role\n- Use `/agents` command\n- Test delegation with simple task\n\n### Week 4: Automate Everything\n- Create first Skill for repeated automation\n- Use Skill marketplace or build custom\n- Combine all features for full workflow\n\n### Ongoing\n- Review and update Memory monthly\n- Add new Skills as patterns emerge\n- Optimize MCP queries\n- Refine Subagent prompts\n\n---\n\n## Hooks\n\n### Overview\n\nHooks are event-driven shell commands that execute automatically in response to Claude Code events. They enable automation, validation, and custom workflows without manual intervention.\n\n### Hook Events\n\nClaude Code supports **25 hook events** across four hook types (command, http, prompt, agent):\n\n| Hook Event | Trigger | Use Cases |\n|------------|---------|-----------|\n| **SessionStart** | Session begins/resumes/clear/compact | Environment setup, initialization |\n| **InstructionsLoaded** | CLAUDE.md or rules file loaded | Validation, transformation, augmentation |\n| **UserPromptSubmit** | User submits prompt | Input validation, prompt filtering |\n| **PreToolUse** | Before any tool runs | Validation, approval gates, logging |\n| **PermissionRequest** | Permission dialog shown | Auto-approve/deny flows |\n| **PostToolUse** | After tool succeeds | Auto-formatting, notifications, cleanup |\n| **PostToolUseFailure** | Tool execution fails | Error handling, logging |\n| **Notification** | Notification sent | Alerting, external integrations |\n| **SubagentStart** | Subagent spawned | Context injection, initialization |\n| **SubagentStop** | Subagent finishes | Result validation, logging |\n| **Stop** | Claude finishes responding | Summary generation, cleanup tasks |\n| **StopFailure** | API error ends turn | Error recovery, logging |\n| **TeammateIdle** | Agent team teammate idle | Work distribution, coordination |\n| **TaskCompleted** | Task marked complete | Post-task processing |\n| **TaskCreated** | Task created via TaskCreate | Task tracking, logging |\n| **ConfigChange** | Config file changes | Validation, propagation |\n| **CwdChanged** | Working directory changes | Directory-specific setup |\n| **FileChanged** | Watched file changes | File monitoring, rebuild triggers |\n| **PreCompact** | Before context compaction | State preservation |\n| **PostCompact** | After compaction completes | Post-compact actions |\n| **WorktreeCreate** | Worktree being created | Environment setup, dependency install |\n| **WorktreeRemove** | Worktree being removed | Cleanup, resource deallocation |\n| **Elicitation** | MCP server requests user input | Input validation |\n| **ElicitationResult** | User responds to elicitation | Response processing |\n| **SessionEnd** | Session terminates | Cleanup, final logging |\n\n### Common Hooks\n\nHooks are configured in `~/.claude/settings.json` (user-level) or `.claude/settings.json` (project-level):\n\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"prettier --write $CLAUDE_FILE_PATH\"\n          }\n        ]\n      }\n    ],\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"eslint $CLAUDE_FILE_PATH\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Hook Environment Variables\n\n- `$CLAUDE_FILE_PATH` - Path to file being edited/written\n- `$CLAUDE_TOOL_NAME` - Name of tool being used\n- `$CLAUDE_SESSION_ID` - Current session identifier\n- `$CLAUDE_PROJECT_DIR` - Project directory path\n\n### Best Practices\n\n✅ **Do:**\n- Keep hooks fast (< 1 second)\n- Use hooks for validation and automation\n- Handle errors gracefully\n- Use absolute paths\n\n❌ **Don't:**\n- Make hooks interactive\n- Use hooks for long-running tasks\n- Hardcode credentials\n\n**See**: [06-hooks/](06-hooks/) for detailed examples\n\n---\n\n## Checkpoints and Rewind\n\n### Overview\n\nCheckpoints allow you to save conversation state and rewind to previous points, enabling safe experimentation and exploration of multiple approaches.\n\n### Key Concepts\n\n| Concept | Description |\n|---------|-------------|\n| **Checkpoint** | Snapshot of conversation state including messages, files, and context |\n| **Rewind** | Return to a previous checkpoint, discarding subsequent changes |\n| **Branch Point** | Checkpoint from which multiple approaches are explored |\n\n### Accessing Checkpoints\n\nCheckpoints are created automatically with every user prompt. To rewind:\n\n```bash\n# Press Esc twice to open the checkpoint browser\nEsc + Esc\n\n# Or use the /rewind command\n/rewind\n```\n\nWhen you select a checkpoint, you choose from five options:\n1. **Restore code and conversation** -- Revert both to that point\n2. **Restore conversation** -- Rewind messages, keep current code\n3. **Restore code** -- Revert files, keep conversation\n4. **Summarize from here** -- Compress conversation into a summary\n5. **Never mind** -- Cancel\n\n### Use Cases\n\n| Scenario | Workflow |\n|----------|----------|\n| **Exploring Approaches** | Save → Try A → Save → Rewind → Try B → Compare |\n| **Safe Refactoring** | Save → Refactor → Test → If fail: Rewind |\n| **A/B Testing** | Save → Design A → Save → Rewind → Design B → Compare |\n| **Mistake Recovery** | Notice issue → Rewind to last good state |\n\n### Configuration\n\n```json\n{\n  \"autoCheckpoint\": true\n}\n```\n\n**See**: [08-checkpoints/](08-checkpoints/) for detailed examples\n\n---\n\n## Advanced Features\n\n### Planning Mode\n\nCreate detailed implementation plans before coding.\n\n**Activation:**\n```bash\n/plan Implement user authentication system\n```\n\n**Benefits:**\n- Clear roadmap with time estimates\n- Risk assessment\n- Systematic task breakdown\n- Opportunity for review and modification\n\n### Extended Thinking\n\nDeep reasoning for complex problems.\n\n**Activation:**\n- Toggle with `Alt+T` (or `Option+T` on macOS) during a session\n- Set `MAX_THINKING_TOKENS` environment variable for programmatic control\n\n```bash\n# Enable extended thinking via environment variable\nexport MAX_THINKING_TOKENS=50000\nclaude -p \"Should we use microservices or monolith?\"\n```\n\n**Benefits:**\n- Thorough analysis of trade-offs\n- Better architectural decisions\n- Consideration of edge cases\n- Systematic evaluation\n\n### Background Tasks\n\nRun long operations without blocking the conversation.\n\n**Usage:**\n```bash\nUser: Run tests in background\n\nClaude: Started task bg-1234\n\n/task list           # Show all tasks\n/task status bg-1234 # Check progress\n/task show bg-1234   # View output\n/task cancel bg-1234 # Cancel task\n```\n\n### Permission Modes\n\nControl what Claude can do.\n\n| Mode | Description | Use Case |\n|------|-------------|----------|\n| **default** | Standard permissions with prompts for sensitive actions | General development |\n| **acceptEdits** | Automatically accept file edits without confirmation | Trusted editing workflows |\n| **plan** | Analysis and planning only, no file modifications | Code review, architecture planning |\n| **auto** | Automatically approve safe actions, prompt only for risky ones | Balanced autonomy with safety |\n| **dontAsk** | Execute all actions without confirmation prompts | Experienced users, automation |\n| **bypassPermissions** | Full unrestricted access, no safety checks | CI/CD pipelines, trusted scripts |\n\n**Usage:**\n```bash\nclaude --permission-mode plan          # Read-only analysis\nclaude --permission-mode acceptEdits   # Auto-accept edits\nclaude --permission-mode auto          # Auto-approve safe actions\nclaude --permission-mode dontAsk       # No confirmation prompts\n```\n\n### Headless Mode (Print Mode)\n\nRun Claude Code without interactive input for automation and CI/CD using the `-p` (print) flag.\n\n**Usage:**\n```bash\n# Run specific task\nclaude -p \"Run all tests\"\n\n# Pipe input for analysis\ncat error.log | claude -p \"explain this error\"\n\n# CI/CD integration (GitHub Actions)\n- name: AI Code Review\n  run: claude -p \"Review PR changes and report issues\"\n\n# JSON output for scripting\nclaude -p --output-format json \"list all functions in src/\"\n```\n\n### Scheduled Tasks\n\nRun tasks on a repeating schedule using the `/loop` command.\n\n**Usage:**\n```bash\n/loop every 30m \"Run tests and report failures\"\n/loop every 2h \"Check for dependency updates\"\n/loop every 1d \"Generate daily summary of code changes\"\n```\n\nScheduled tasks run in the background and report results when complete. They are useful for continuous monitoring, periodic checks, and automated maintenance workflows.\n\n### Chrome Integration\n\nClaude Code can integrate with the Chrome browser for web automation tasks. This enables capabilities like navigating web pages, filling forms, taking screenshots, and extracting data from websites directly within your development workflow.\n\n### Session Management\n\nManage multiple work sessions.\n\n**Commands:**\n```bash\n/resume                # Resume a previous conversation\n/rename \"Feature\"      # Name the current session\n/fork                  # Fork into a new session\nclaude -c              # Continue most recent conversation\nclaude -r \"Feature\"    # Resume session by name/ID\n```\n\n### Interactive Features\n\n**Keyboard Shortcuts:**\n- `Ctrl + R` - Search command history\n- `Tab` - Autocomplete\n- `↑ / ↓` - Command history\n- `Ctrl + L` - Clear screen\n\n**Multi-line Input:**\n```bash\nUser: \\\n> Long complex prompt\n> spanning multiple lines\n> \\end\n```\n\n### Configuration\n\nComplete configuration example:\n\n```json\n{\n  \"planning\": {\n    \"autoEnter\": true,\n    \"requireApproval\": true\n  },\n  \"extendedThinking\": {\n    \"enabled\": true,\n    \"showThinkingProcess\": true\n  },\n  \"backgroundTasks\": {\n    \"enabled\": true,\n    \"maxConcurrentTasks\": 5\n  },\n  \"permissions\": {\n    \"mode\": \"default\"\n  }\n}\n```\n\n**See**: [09-advanced-features/](09-advanced-features/) for comprehensive guide\n\n---\n\n## Resources\n\n- [Claude Code Documentation](https://code.claude.com/docs/en/overview)\n- [Anthropic Documentation](https://docs.anthropic.com)\n- [MCP GitHub Servers](https://github.com/modelcontextprotocol/servers)\n- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)\n\n---\n\n*Last updated: March 2026*\n*For Claude Haiku 4.5, Sonnet 4.6, and Opus 4.6*\n*Now includes: Hooks, Checkpoints, Planning Mode, Extended Thinking, Background Tasks, Permission Modes (6 modes), Headless Mode, Session Management, Auto Memory, Agent Teams, Scheduled Tasks, Chrome Integration, Channels, Voice Dictation, and Bundled Skills*\n"
  },
  {
    "path": "clean-code-rules.md",
    "content": "# Clean Code Rules for AI Code Generation\n\nThese rules guide code generation to produce maintainable, professional-quality code.\n\n## Meaningful Names\n- Use intention-revealing names that explain why something exists\n- Avoid disinformation and meaningless distinctions (e.g., `data`, `info`, `manager`)\n- Use pronounceable, searchable names\n- Class names: nouns (e.g., `UserAccount`, `PaymentProcessor`)\n- Method names: verbs (e.g., `calculateTotal`, `sendEmail`)\n- Avoid mental mapping and encodings (Hungarian notation, prefixes)\n\n## Functions\n- Keep functions small (< 20 lines ideal)\n- Do one thing only - Single Responsibility Principle\n- One level of abstraction per function\n- Limit arguments: 0-2 ideal, 3 maximum, avoid flag arguments\n- No side effects - function should do what its name says\n- Separate commands (change state) from queries (return info)\n- Prefer exceptions over error codes\n\n## Comments\n- Code should be self-explanatory - avoid comments when possible\n- Good comments: legal info, warnings, TODOs, public API documentation\n- Bad comments: redundant, misleading, or explaining bad code\n- Never comment out code - delete it (version control preserves history)\n- If you need a comment, consider refactoring the code instead\n\n## Formatting\n- Keep files small and focused\n- Vertical formatting: related concepts close together, blank lines separate concepts\n- Horizontal formatting: limit line length (80-120 characters)\n- Use consistent indentation and team style\n- Group related functions together\n\n## Objects and Data Structures\n- Objects: hide data behind abstractions, expose behavior through methods\n- Data structures: expose data, have minimal behavior\n- Law of Demeter: only talk to immediate friends, avoid `a.getB().getC().doSomething()`\n- Don't expose internal structure through getters/setters blindly\n\n## Error Handling\n- Use exceptions, not return codes or error flags\n- Write `try-catch-finally` first when code might fail\n- Provide context in exception messages\n- Don't return `null` - return empty collections or use Optional/Maybe\n- Don't pass `null` as arguments\n\n## Classes\n- Small classes: measured by responsibilities, not lines\n- Single Responsibility Principle: one reason to change\n- High cohesion: class variables used by many methods\n- Low coupling: minimal dependencies between classes\n- Open/Closed Principle: open for extension, closed for modification\n\n## Unit Tests\n- Fast, Independent, Repeatable, Self-validating, Timely (F.I.R.S.T.)\n- One assert per test (or one concept)\n- Test code quality equals production code quality\n- Readable test names that describe what's being tested\n- Arrange-Act-Assert pattern\n\n## Code Quality Principles\n- **DRY (Don't Repeat Yourself)**: No duplication\n- **YAGNI (You Aren't Gonna Need It)**: Don't build for hypothetical futures\n- **KISS (Keep It Simple)**: Avoid unnecessary complexity\n- **Boy Scout Rule**: Leave code cleaner than you found it\n\n## Code Smells to Avoid\n- Long functions or classes\n- Duplicate code\n- Dead code (unused variables, functions, parameters)\n- Feature envy (method more interested in other class)\n- Inappropriate intimacy (classes knowing too much about each other)\n- Long parameter lists\n- Primitive obsession (overusing primitives instead of small objects)\n- Switch/case statements (consider polymorphism)\n- Temporary fields (class variables only used sometimes)\n\n## Concurrency\n- Keep concurrent code separate from other code\n- Limit scope of synchronized/locked data\n- Use thread-safe collections\n- Keep synchronized sections small\n- Know your execution models and primitives\n\n## System Design\n- Separate construction from use (dependency injection)\n- Use factories, builders for complex object creation\n- Program to interfaces, not implementations\n- Favor composition over inheritance\n- Apply design patterns when they simplify, not to show off\n\n## Refactoring\n- Refactor continuously, not in big batches\n- Always have passing tests before and after\n- Small steps: one change at a time\n- Common refactorings: Extract Method, Rename, Move, Inline\n\n## Documentation\n- Self-documenting code > comments > external docs\n- Public APIs need clear documentation\n- Include examples in documentation\n- Keep docs close to code (ideally in code)\n\n---\n\n**Core Philosophy**: Code is read 10x more than written. Optimize for readability and maintainability, not cleverness.\n"
  },
  {
    "path": "coverage.xml",
    "content": "<?xml version=\"1.0\" ?>\n<coverage version=\"7.13.1\" timestamp=\"1767948660087\" lines-valid=\"628\" lines-covered=\"475\" line-rate=\"0.7564\" branches-covered=\"0\" branches-valid=\"0\" branch-rate=\"0\" complexity=\"0\">\n\t<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.13.1 -->\n\t<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->\n\t<sources>\n\t\t<source>/Users/montimage/buildspace/luongnv89/claude-howto/scripts</source>\n\t</sources>\n\t<packages>\n\t\t<package name=\".\" line-rate=\"0.6498\" branch-rate=\"0\" complexity=\"0\">\n\t\t\t<classes>\n\t\t\t\t<class name=\"build_epub.py\" filename=\"build_epub.py\" complexity=\"0\" line-rate=\"0.6498\" branch-rate=\"0\">\n\t\t\t\t\t<methods/>\n\t\t\t\t\t<lines>\n\t\t\t\t\t\t<line number=\"43\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"45\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"46\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"47\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"48\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"49\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"50\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"51\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"52\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"53\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"54\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"55\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"56\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"58\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"59\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"60\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"61\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"62\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"63\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"75\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"78\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"81\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"84\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"87\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"90\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"93\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"96\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"104\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"105\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"109\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"110\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"111\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"114\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"115\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"116\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"117\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"120\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"121\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"122\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"123\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"124\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"127\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"128\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"129\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"130\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"133\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"141\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"151\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"152\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"155\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"156\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"157\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"158\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"160\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"162\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"163\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"164\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"165\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"168\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"169\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"172\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"173\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"174\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"175\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"176\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"177\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"185\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"187\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"188\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"193\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"201\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"203\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"206\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"207\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"208\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"209\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"212\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"213\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"214\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"215\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"216\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"219\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"220\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"221\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"226\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"227\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"228\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"230\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"231\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"232\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"233\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"241\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"249\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"250\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"253\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"256\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"259\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"260\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"261\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"262\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"264\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"268\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"271\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"272\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"273\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"276\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"277\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"278\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"279\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"280\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"283\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"285\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"291\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"295\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"296\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"297\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"298\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"300\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"301\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"303\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"304\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"305\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"306\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"307\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"308\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"309\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"310\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"312\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"315\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"319\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"320\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"321\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"322\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"323\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"326\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"328\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"332\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"333\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"335\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"340\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"345\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"348\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"350\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"351\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"353\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"354\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"357\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"360\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"364\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"365\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"366\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"367\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"369\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"370\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"371\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"372\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"373\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"374\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"375\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"376\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"377\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"378\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"379\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"381\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"382\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"390\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"392\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"410\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"412\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"415\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"416\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"417\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"420\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"421\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"422\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"423\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"426\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"427\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"428\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"429\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"430\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"431\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"432\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"435\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"437\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"439\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"442\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"445\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"446\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"447\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"449\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"453\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"454\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"456\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"457\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"459\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"460\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"461\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"462\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"464\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"473\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"474\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"477\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"478\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"479\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"481\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"483\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"487\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"488\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"489\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"491\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"492\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"495\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"496\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"497\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"499\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"500\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"501\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"502\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"504\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"515\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"523\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"527\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"528\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"529\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"530\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"531\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"532\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"533\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"535\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"536\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"539\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"543\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"544\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"545\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"546\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"547\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"549\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"550\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"551\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"552\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"553\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"554\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"556\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"557\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"558\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"559\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"562\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"572\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"573\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"574\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"575\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"576\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"577\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"578\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"579\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"582\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"589\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"590\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"593\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"596\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"597\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"600\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"601\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"602\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"604\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"607\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"618\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"628\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"629\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"630\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"631\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"633\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"634\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"635\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"643\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"647\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"648\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"650\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"651\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"663\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"676\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"678\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"693\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"694\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"702\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"706\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"708\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"709\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"710\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"712\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"713\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"715\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"716\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"722\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"723\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"724\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"727\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"728\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"730\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"733\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"737\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"739\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"740\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"741\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"742\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"745\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"746\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"747\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"748\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"751\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"752\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"753\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"754\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"755\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"757\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"760\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"763\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"771\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"772\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"773\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"774\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"776\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"779\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"796\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"799\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"810\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"811\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"812\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"813\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"814\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"815\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"816\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"818\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"821\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"823\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"831\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"833\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"850\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"858\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"864\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"865\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"868\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"871\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"872\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"873\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"874\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"875\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"878\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"879\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"880\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"883\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"884\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"887\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"888\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"889\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"892\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"893\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"894\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"896\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"897\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"898\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"901\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"902\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"903\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"905\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"906\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"908\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"909\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"910\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"911\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"912\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"913\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"917\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"920\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"924\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"930\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"937\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"938\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"939\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"942\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"944\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"946\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"949\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"950\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"951\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"954\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"955\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"957\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"960\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"961\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"962\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"965\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"966\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"969\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"972\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"973\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"976\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"979\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"980\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"982\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"983\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"986\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"988\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"989\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"990\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"998\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"1000\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1003\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1010\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1017\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1020\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1026\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1033\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1036\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1037\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1039\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1041\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1042\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1043\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1045\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1046\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1053\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1054\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1055\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1056\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1057\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1058\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1059\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1060\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1061\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1062\" hits=\"0\"/>\n\t\t\t\t\t\t<line number=\"1065\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"1066\" hits=\"0\"/>\n\t\t\t\t\t</lines>\n\t\t\t\t</class>\n\t\t\t</classes>\n\t\t</package>\n\t\t<package name=\"tests\" line-rate=\"0.9948\" branch-rate=\"0\" complexity=\"0\">\n\t\t\t<classes>\n\t\t\t\t<class name=\"__init__.py\" filename=\"tests/__init__.py\" complexity=\"0\" line-rate=\"1\" branch-rate=\"0\">\n\t\t\t\t\t<methods/>\n\t\t\t\t\t<lines/>\n\t\t\t\t</class>\n\t\t\t\t<class name=\"conftest.py\" filename=\"tests/conftest.py\" complexity=\"0\" line-rate=\"1\" branch-rate=\"0\">\n\t\t\t\t\t<methods/>\n\t\t\t\t\t<lines>\n\t\t\t\t\t\t<line number=\"3\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"5\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"6\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"7\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"9\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"12\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"14\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"17\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"18\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"21\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"22\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"25\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"26\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"27\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"28\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"31\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"33\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"34\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"35\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"37\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"40\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"41\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"43\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"49\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"50\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"52\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"55\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"56\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"58\" hits=\"1\"/>\n\t\t\t\t\t</lines>\n\t\t\t\t</class>\n\t\t\t\t<class name=\"test_build_epub.py\" filename=\"tests/test_build_epub.py\" complexity=\"0\" line-rate=\"0.9939\" branch-rate=\"0\">\n\t\t\t\t\t<methods/>\n\t\t\t\t\t<lines>\n\t\t\t\t\t\t<line number=\"3\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"5\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"6\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"7\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"9\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"13\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"31\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"34\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"36\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"37\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"38\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"39\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"41\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"43\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"44\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"45\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"46\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"48\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"49\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"50\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"51\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"53\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"55\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"56\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"57\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"58\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"60\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"62\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"63\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"64\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"65\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"73\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"76\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"78\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"82\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"83\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"85\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"87\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"91\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"92\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"93\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"94\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"95\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"96\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"97\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"99\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"101\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"108\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"109\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"110\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"118\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"121\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"124\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"126\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"128\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"132\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"133\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"135\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"137\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"138\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"139\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"143\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"144\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"146\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"148\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"149\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"150\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"154\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"155\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"157\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"161\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"165\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"166\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"174\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"177\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"179\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"180\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"181\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"183\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"185\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"186\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"188\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"193\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"194\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"211\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"213\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"214\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"215\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"216\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"217\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"219\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"223\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"224\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"226\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"231\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"232\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"234\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"239\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"247\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"250\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"252\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"253\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"255\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"256\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"258\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"259\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"260\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"261\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"262\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"264\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"266\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"267\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"269\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"270\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"271\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"272\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"274\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"276\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"277\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"284\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"285\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"286\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"294\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"297\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"299\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"306\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"307\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"308\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"309\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"311\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"313\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"320\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"321\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"323\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"325\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"332\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"334\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"342\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"345\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"347\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"349\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"350\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"353\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"354\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"355\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"356\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"364\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"367\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"369\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"370\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"372\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"374\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"375\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"383\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"386\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"387\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"391\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"393\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"399\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"400\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"402\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"404\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"405\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"413\" hits=\"1\"/>\n\t\t\t\t\t\t<line number=\"414\" hits=\"0\"/>\n\t\t\t\t\t</lines>\n\t\t\t\t</class>\n\t\t\t</classes>\n\t\t</package>\n\t</packages>\n</coverage>\n"
  },
  {
    "path": "prompts/remotion-video.md",
    "content": "You are an expert Motion Designer and Senior React Engineer specializing in **Remotion**. Your goal is to take a product description and turn it into a high-energy, professionally animated video using React code.\n\n**START BY EXPLORING AUTONOMOUSLY:** Immediately begin exploring the codebase to gather product information. Only ask the user questions if critical information is missing or unclear after your exploration.\n\nFollow a 7-phase workflow, making smart decisions at each step based on the information you gather.\n\n---\n\n# 🔄 AUTOMATED WORKFLOW\n\n**KEY PRINCIPLES:**\n\n- **Explore First:** Always begin by automatically exploring the codebase to gather product information. Do NOT start with questions about the product.\n- **Ask Before Planning:** After exploration, present findings and ask user for video preferences (size, style, duration, customizations) BEFORE creating the plan.\n- **Product URL First:** When a product URL is found or provided, it serves as the PRIMARY source of truth. Information from the product page takes precedence over codebase findings.\n- **Value Over Tech:** Focus on value propositions, customer benefits, and features (what users gain) rather than technical specifications or implementation details.\n- **Customer-Centric:** Emphasize how the product solves problems, improves lives, or delivers benefits to users.\n- **Autonomous Execution:** After user confirms preferences, proceed autonomously through planning and implementation without further approval requests.\n\n## 📋 Phase 1: Autonomous Resource Discovery\n\n**OBJECTIVE:** Automatically explore the codebase and gather all available product information without asking the user.\n\n**ACTIONS:**\n\n1. **Automatically explore the codebase first:**\n   - Search for `README.md` for product description and value proposition\n   - Check `package.json` for product name, description, homepage URL\n   - Look for brand assets in `/assets`, `/public`, `/static`, `/images` directories\n   - Extract color schemes from CSS/Tailwind config files\n   - Find any existing marketing copy or documentation\n   - Look for any product URLs in config files, environment variables, or documentation\n\n2. **If product URL found, fetch it immediately:**\n   - Use WebFetch to extract information from the product page\n   - Product page information takes precedence over codebase findings\n   - Extract all value propositions, features, and branding\n\n3. **Synthesize all gathered information:**\n   - Product name and description\n   - Value proposition\n   - Key features and benefits\n   - Brand colors and style\n   - Target audience (inferred from tone)\n   - Any existing assets or media\n\n4. **Apply smart defaults for missing information:**\n   - **Video Format:** Landscape 1920x1080 (YouTube/web optimized)\n   - **Duration:** 30 seconds (ideal for most platforms)\n   - **Style:** Modern, clean, professional (based on brand)\n   - **Brand Colors:** Use extracted colors or complementary modern palette\n\n5. **Only ask user IF (after exploration):**\n   - Cannot determine product name or find any product information\n   - Cannot find or access product URL\n   - Critical ambiguity exists (e.g., B2B vs B2C drastically changes messaging)\n   - Conflicting information needs clarification\n\n**IMPORTANT:** Complete this entire exploration silently and autonomously. Do NOT ask \"What I need to get started\" or list requirements. Only interrupt the user if truly necessary.\n\n**OUTPUT:** Proceed immediately to Phase 2 with all gathered information.\n\n---\n\n## 🔍 Phase 2: Information Analysis & Deep Dive\n\n**OBJECTIVE:** Analyze gathered information and extract key insights for video creation.\n\n**ACTIONS:**\n\n1. **Review all information collected in Phase 1:**\n   - Product page content (if URL was found and fetched)\n   - Codebase findings (README, package.json, assets, etc.)\n   - Any brand guidelines or marketing materials\n\n2. **Extract and prioritize (FOCUS ON VALUE, NOT TECH):**\n   - **Value Proposition** (primary focus) - The main benefit to customers\n   - **Customer Benefits** (what users gain) - How it improves their lives\n   - **Key Features** (described as benefits, not technical specs)\n   - **Unique Selling Points** - What makes it different/better\n   - **Use Cases** - Real-world applications\n   - **Brand identity** (colors, fonts, style, tone)\n   - **Target audience insights** (who this is for)\n   - **Emotional appeal** and messaging (why people care)\n\n3. **Silently fill gaps with intelligent inferences:**\n   - If value prop is not explicit, infer from features and target audience\n   - If target audience is unclear, infer from product type and messaging tone\n   - If brand colors are missing, create a complementary modern palette\n   - Avoid technical implementation details unless user-facing\n\n4. **Only ask for clarification IF:**\n   - Multiple conflicting value propositions exist\n   - Cannot determine if product is B2B or B2C (drastically affects messaging)\n   - Genuinely ambiguous target audience\n\n**OUTPUT:** Clear understanding of product value, benefits, and brand for video creation.\n\n---\n\n## ✅ Phase 3: Present Findings & Gather User Preferences\n\n**OBJECTIVE:** Share what you discovered and get user input on video preferences before planning.\n\n**ACTIONS:**\n\n1. **Present a summary of discovered information:**\n\n   ```text\n   📊 DISCOVERED INFORMATION\n\n   Product: [Name]\n   Value Proposition: [Main benefit to customers]\n   Key Features: [2-3 main benefits]\n   Brand Colors: [Extracted or suggested colors]\n   Target Audience: [Who this is for]\n   ```\n\n2. **Ask user for preferences (REQUIRED BEFORE PROCEEDING):**\n\n   Use a clear, concise format:\n\n   ```text\n   Before I create your video, please let me know your preferences:\n\n   1. **Video Size/Format:**\n      - Landscape (1920x1080) - YouTube, website\n      - Portrait (1080x1920) - TikTok, Instagram Reels\n      - Square (1080x1080) - Instagram feed\n\n   2. **Video Duration:**\n      - 15 seconds - Quick social media ad\n      - 30 seconds - Standard promotional video\n      - 60 seconds - Detailed feature showcase\n      - Custom duration\n\n   3. **Video Style:**\n      - Modern & Minimal - Clean, Apple-style aesthetics\n      - Energetic & Bold - Fast-paced, social media style\n      - Professional & Corporate - Business-focused\n      - Custom style (describe your vision)\n\n   4. **Anything else to highlight or customize?**\n      (Specific features, messaging, colors, etc.)\n   ```\n\n3. **Wait for user response** before proceeding to Phase 4.\n\n4. **Acknowledge preferences and confirm:**\n   - Summarize user's choices\n   - Apply any custom requirements\n   - Proceed to structure design with confirmed direction\n\n**OUTPUT:** User-confirmed video specifications ready for planning phase.\n\n---\n\n## 📐 Phase 4: Structure Design (Post-Confirmation)\n\n**OBJECTIVE:** Create a compelling video structure using the 3-act format based on user preferences.\n\n**ACTIONS:**\n\n1. **Design video structure with user's confirmed preferences:**\n\n   ```text\n   🎬 VIDEO STRUCTURE\n\n   Act 1: The Hook (0-5 seconds)\n   - [Attention-grabbing visual concept]\n   - [Bold animation entrance]\n   - [Compelling headline/question]\n\n   Act 2: Value Demonstration (middle section)\n   - [Show key benefits in action]\n   - [Visual storytelling of customer value]\n   - [2-3 feature highlights as benefits]\n\n   Act 3: Call to Action (final section)\n   - [Clear CTA with brand reinforcement]\n   - [Memorable closing visual]\n   - [Smooth exit animation]\n   ```\n\n2. **Apply user preferences:**\n   - Use specified video size/format\n   - Match chosen style (minimal/energetic/professional)\n   - Adapt timing to specified duration\n   - Incorporate any custom requirements\n\n3. **Make creative decisions based on:**\n   - Product value proposition (what makes it compelling)\n   - Target audience (what resonates with them)\n   - User's style preferences\n   - Brand personality (visual and tonal consistency)\n\n4. **Present the structure briefly** then automatically proceed to Phase 5.\n\n**OUTPUT:** Complete video structure ready for implementation planning.\n\n---\n\n## 🛠️ Phase 5: Technical Architecture\n\n**OBJECTIVE:** Design implementation architecture and proceed directly to building.\n\n**ACTIONS:**\n\n1. **Silently design** the component architecture:\n   - Utility functions (easing, animation helpers, color utilities)\n   - Reusable components (AnimatedTitle, FeatureHighlight, etc.)\n   - Scene components (Hook, Demo, CTA scenes)\n   - Main composition structure (Video.tsx, Root.tsx)\n\n2. **Plan technical details:**\n   - Animation timing and easing curves\n   - Color palette implementation\n   - Typography hierarchy\n   - Icon and asset strategy\n   - Sequence timing breakdown\n\n3. **Proceed directly to Phase 6** implementation without requesting approval.\n\n**OUTPUT:** Internal technical blueprint ready for immediate implementation.\n\n---\n\n## 💻 Phase 6: Implementation\n\n**OBJECTIVE:** Build the complete Remotion video project autonomously.\n\n**CONSTRAINTS & TECH STACK:**\n\n1. **Framework:** Remotion (React)\n2. **Styling:** Tailwind CSS (via `className` or standard style objects)\n3. **Animation:** Use `spring`, `interpolate`, and `useCurrentFrame` for smooth motion\n4. **Code Style:** Modular components. Do not dump everything in `Root.tsx`\n5. **Best Practices:**\n   - Nothing should be static. Everything must have an entrance (opacity/scale/slide) and exit\n   - Use Lucide-React for icons if needed\n   - Use standard fonts but style them heavily (bold, tracking-tight)\n   - Do not use external images unless they are placeholders (e.g., `https://placehold.co/600x400`) or user-provided assets\n\n**ACTIONS:**\n\n1. **Build complete project structure** in this order:\n   - Utility functions (easing, animation helpers, color utilities)\n   - Reusable components (AnimatedTitle, FeatureHighlight, transitions)\n   - Scene components (HookScene, DemoScene, CTAScene)\n   - Main composition (Video.tsx with sequencing)\n   - Root configuration (Root.tsx with proper registration)\n\n2. **Work silently and efficiently:**\n   - Create all files without narrating every step\n   - Make design decisions based on gathered information\n   - Use professional animation principles\n   - Ensure smooth transitions between scenes\n\n3. **Automatically proceed to Phase 7** when implementation is complete.\n\n**OUTPUT:** Complete, production-ready Remotion project code.\n\n---\n\n## 🎥 Phase 7: Delivery & Next Steps\n\n**OBJECTIVE:** Provide rendering instructions and mark project complete.\n\n**ACTIONS:**\n\n1. **Provide rendering instructions:**\n\n   ```bash\n   # Preview the video in browser\n   npm run dev\n\n   # Render the final video\n   npm run build\n   npx remotion render Video out/video.mp4\n\n   # For specific codec/settings\n   npx remotion render Video out/video.mp4 --codec h264\n   ```\n\n2. **Deliver summary:**\n   - Brief description of what was created\n   - Key features of the video\n   - Video specifications (duration, format, dimensions)\n   - Any notable design decisions\n\n3. **User can request changes if needed:**\n   - Timing adjustments\n   - Animation modifications\n   - Content updates\n   - Style tweaks\n\n**OUTPUT:** Complete Remotion project with clear rendering instructions, ready to use.\n\n---\n\n# 🎯 QUALITY STANDARDS\n\nThroughout all phases, maintain these standards:\n\n**Visual Quality:**\n- Professional-grade animations (smooth, purposeful, on-brand)\n- Consistent spacing and alignment\n- Readable typography with proper contrast\n- Cohesive color usage\n\n**Technical Quality:**\n- Clean, modular code architecture\n- Performance-optimized (smooth 30fps playback)\n- Proper use of Remotion APIs (spring, interpolate, Sequence)\n- Type-safe (if using TypeScript)\n\n**Creative Quality:**\n- Clear narrative structure\n- Attention-grabbing opening\n- Strong call-to-action\n- Memorable visual moments\n\n---\n\n# 🚀 Getting Started\n\nI'll create a professional Remotion video project for your product. Here's my workflow:\n\n## Phase 1-2: Autonomous Exploration (I do this automatically)\n\n1. Explore your codebase for product details, brand assets, and colors\n2. Fetch and analyze product page (if URL found)\n3. Extract value propositions and key benefits\n\n## Phase 3: Your Input (I'll ask you)\n\n1. Present what I discovered\n2. Ask for your video preferences:\n   - Video size/format (landscape/portrait/square)\n   - Duration (15s/30s/60s)\n   - Style (minimal/energetic/professional)\n   - Any customizations\n\n## Phase 4-7: Autonomous Execution (I do this automatically)\n\n1. Design video structure based on your preferences\n2. Build complete Remotion project with professional animations\n3. Deliver production-ready code with rendering instructions\n\nLet's create something amazing!\n"
  },
  {
    "path": "resources/DESIGN-SYSTEM.md",
    "content": "# Claude How To - Design System\n\n## Visual Identity\n\n### Icon Design Concept: Compass with Code Bracket\n\nThe Claude How To icon uses a **compass with a `>` code bracket** to represent guided navigation through code:\n\n```\n     N (green)\n     ▲\n     │\nW ───>─── E     Compass = Guidance/Direction\n     │          > Bracket = Code/Terminal/CLI\n     ▼\n     S (black)\n```\n\nThis creates:\n- **Visual Clarity**: Immediately communicates \"code navigation guide\"\n- **Symbolic Meaning**: Compass = finding your way; `>` = code/terminal\n- **Scalability**: Works at any size from 16px to 512px\n- **Brand Alignment**: Matches the developer tool aesthetic with minimal palette\n\n---\n\n## Color System\n\n### Palette\n\n| Color | Hex | RGB | Usage |\n|-------|-----|-----|-------|\n| Black (Primary) | `#000000` | 0, 0, 0 | Main strokes, text, south needle |\n| White (Background) | `#FFFFFF` | 255, 255, 255 | Light backgrounds |\n| Gray (Secondary) | `#6B7280` | 107, 114, 128 | Minor tick marks, secondary text |\n| Bright Green (Accent) | `#22C55E` | 34, 197, 94 | North needle, center dot, accent lines |\n| Near Black (Dark BG) | `#0A0A0A` | 10, 10, 10 | Dark mode backgrounds |\n\n### Contrast Ratios (WCAG)\n\n- Black on White: **21:1** AAA\n- Gray on White: **4.6:1** AA\n- Green on White: **3.2:1** (decorative only, not for text)\n- White on Dark: **19.5:1** AAA\n\n### Accent Color Rule\n\n**Bright Green (#22C55E) is reserved for highlights only:**\n- Compass north needle\n- Center dot\n- Accent underlines/borders\n- Never as a background color\n- Never for body text\n\n---\n\n## Typography\n\n### Logo Font\n- **Family**: Inter, SF Pro Display, -apple-system, Segoe UI, sans-serif\n- **\"Claude\"**: 42px, weight 700 (bold), Black\n- **\"How-To\"**: 32px, weight 500 (medium), Gray (#6B7280)\n- **Subtitle**: 10px, weight 500, Gray, letter-spacing 1.5px, uppercase\n\n### Interface Font\n- **Family**: Inter, SF Pro, system fonts (sans-serif)\n- **Weight**: 400-600\n- **Style**: Clean, readable\n\n---\n\n## Icon Details\n\n### Compass Specifications\n\nThe compass mark is built from these geometric elements:\n\n```\nElement             | Stroke/Fill    | Color\n--------------------|----------------|------------------\nOuter ring          | 3px stroke     | Black / White (dark mode)\nNorth tick          | 2.5px stroke   | Black / White (dark mode)\nOther cardinal ticks| 2px stroke     | Gray / White 50% (dark mode)\nIntercardinal ticks | 1.5px stroke   | Gray / White 40% (dark mode)\nNorth needle        | filled polygon | #22C55E (always green)\nSouth needle        | filled polygon | Black / White (dark mode)\n> bracket           | 3px stroke     | Black / White (dark mode)\nCenter dot          | filled circle  | #22C55E (always green)\n```\n\n### Size Progression\n\n```\n16px  → Ring + needles + chevron only (minimal)\n32px  → Adds cardinal tick marks\n64px  → Adds intercardinal tick marks\n128px → Full detail, all elements crisp\n256px → Maximum detail, thick strokes\n```\n\n---\n\n## Sizing Guidelines\n\n### Logo Sizing\n\n- **Minimum**: 200px width (for web)\n- **Recommended**: 520px (native size)\n- **Maximum**: Unlimited (vector format)\n- **Aspect Ratio**: ~4.3:1 (width:height)\n\n### Icon Sizing\n\n- **Minimum**: 16px (favicon)\n- **Recommended**: 64-256px (apps, avatars)\n- **Maximum**: Unlimited (vector format)\n- **Aspect Ratio**: 1:1 (square)\n\n---\n\n## Spacing & Alignment\n\n### Logo Spacing\n\n```\n┌─────────────────────────────────────┐\n│                                     │\n│        Clear Space Minimum          │\n│         (logo height / 2)           │\n│                                     │\n│    [COMPASS]  Claude                │\n│               How-To                │\n│                                     │\n└─────────────────────────────────────┘\n```\n\n### Icon Center Point\n\nAll icons center at the midpoint of their canvas:\n- 128×128 for 256px canvas\n- 64×64 for 128px canvas\n- Maintains alignment with other UI elements\n\n---\n\n## Accessibility\n\n### Color Contrast\n- All text meets WCAG AA (4.5:1 minimum)\n- Green accent is decorative, not informational\n- No red-green color dependency\n\n### Scalability\n- Vector format ensures clarity at any size\n- Geometric shapes remain recognizable at 16px\n- Progressive detail based on available size\n\n---\n\n## Application Examples\n\n### Web Header\n- Size: 520×120px logo\n- File: `logos/claude-howto-logo.svg`\n- Background: White or dark (#0A0A0A)\n- Padding: 20px minimum\n\n### App Icon\n- Size: 256×256px\n- File: `icons/claude-howto-icon.svg`\n- Background: White or dark\n- Use: App shortcuts, avatars\n\n### Browser Favicon\n- Size: 32px (primary), 16px (fallback)\n- File: `favicons/favicon-32.svg`\n- Format: SVG for crisp display\n\n### Social Media\n- Profile: 256×256px icon\n- Banner: 520×120px logo (centered)\n\n### Documentation\n- Chapter Headers: Logo scaled to fit\n- Section Icons: 64×64px favicon\n- Inline: 32×32px favicon\n\n---\n\n## File Format Details\n\n### SVG Structure\n\nAll SVG files are flat design:\n- No gradients (solid colors only)\n- No filter effects (no blur, glow, or shadow)\n- Clean stroke and fill geometry\n- ViewBox for responsive scaling\n- Readable, commented code\n\n### Cross-Browser Compatibility\n\n- Chrome/Edge: Full support\n- Firefox: Full support\n- Safari: Full support\n- iOS Safari: Full support\n- All modern browsers: Full support\n\n---\n\n## Customization\n\n### Changing the Accent Color\n\nTo create variants with a different accent:\n\n1. Replace all instances of `#22C55E` with your accent color\n2. Ensure contrast ratio stays above 3:1 for decorative elements\n3. Keep black/white/gray structure unchanged\n\n### Scaling\n\n```css\nsvg {\n  width: 256px;\n  height: 256px;\n}\n```\n\nSVGs scale automatically via viewBox — no transforms needed.\n\n---\n\n## Version Control\n\nTrack design changes in git:\n- Version SVG files normally (they're text)\n- Tag releases with design changes\n- Include DESIGN-SYSTEM.md in commits\n\n---\n\n**Last Updated**: February 2026\n**Design System Version**: 3.0\n"
  },
  {
    "path": "resources/INDEX.txt",
    "content": "╔═══════════════════════════════════════════════════════════════════════════╗\n║           CLAUDE HOW TO - BRAND ASSETS RESOURCE LIBRARY                   ║\n║                         Complete Asset Package                            ║\n╚═══════════════════════════════════════════════════════════════════════════╝\n\n📁 DIRECTORY STRUCTURE\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nresources/\n│\n├── 📄 README.md (Complete Documentation)\n│   └─ Full guide for all assets, usage patterns, HTML integration\n│\n├── 📄 QUICK-START.md (Copy & Paste Solutions)\n│   └─ Fast setup, recommended sizes, color values\n│\n├── 📄 DESIGN-SYSTEM.md (Brand Guidelines)\n│   └─ Visual identity, color system, typography, effects\n│\n├── 📁 logos/\n│   └─ 📊 claude-howto-logo.svg (800×200px)\n│       → Main horizontal logo with terminal icon\n│       → Perfect for: Headers, marketing, print\n│\n├── 📁 icons/\n│   └─ 🔷 claude-howto-icon.svg (256×256px)\n│       → App icon with ascending hexagons\n│       → Perfect for: Apps, avatars, thumbnails\n│\n└── 📁 favicons/\n    ├─ 🔹 favicon-16.svg   (16×16px)   → Browser tabs\n    ├─ 🔹 favicon-32.svg   (32×32px)   → Standard favicon\n    ├─ 🔹 favicon-64.svg   (64×64px)   → High-DPI\n    ├─ 🔹 favicon-128.svg  (128×128px) → Apple touch icon\n    └─ 🔹 favicon-256.svg  (256×256px) → Modern browsers/PWA\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n📋 QUICK FILE REFERENCE\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nFILE                          SIZE        USE CASE\n────────────────────────────────────────────────────────────────────────────\nlogos/claude-howto-logo.svg   800×200px   Website headers, marketing\nicons/claude-howto-icon.svg   256×256px   App icons, avatars, social\nfavicons/favicon-32.svg       32×32px     Browser favicon (primary)\nfavicons/favicon-16.svg       16×16px     Browser tab (old browsers)\nfavicons/favicon-64.svg       64×64px     Bookmarks, high-DPI\nfavicons/favicon-128.svg      128×128px   Apple touch icon\nfavicons/favicon-256.svg      256×256px   Android, PWA, modern\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n🎨 DESIGN CONCEPT\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nThe icon uses ASCENDING HEXAGONS to represent learning progression:\n\n              🟢 MINT (Top)\n        Advanced Features\n        Levels 7-10\n\n          🟢 EMERALD (Middle)\n    Intermediate Skills\n    Levels 4-6\n\n      🟢 DARK EMERALD (Bottom)\n  Beginner Fundamentals\n  Levels 1-3\n\nVisual meaning: Upward progression = Learning journey from beginner to mastery\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n🎨 COLOR PALETTE\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nCOLOR               HEX         RGB             USAGE\n─────────────────────────────────────────────────────────────────────────────\nDeep Forest         #0d1f0d     13, 31, 13      Backgrounds\nEmerald (Primary)   #10b981     16, 185, 129    Main accents\nDark Emerald        #059669     5, 150, 105     Secondary accents\nForest              #047857     4, 120, 87      Tertiary accents\nMint (Highlight)    #6ee7b7     110, 231, 183   Highlights\nLight Mint          #34d399     52, 211, 153    Secondary highlights\n\nAll colors maintain WCAG AAA contrast on dark backgrounds (8.2:1+)\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n📖 DOCUMENTATION FILES\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n1. README.md\n   Complete guide covering:\n   • Asset descriptions and purposes\n   • HTML integration templates\n   • Favicon setup instructions\n   • Color palette and guidelines\n   • SVG optimization tips\n   • Accessibility considerations\n\n2. QUICK-START.md\n   Fast reference with:\n   • Copy-paste code\n   • Recommended sizes\n   • Color CSS variables\n   • Icon meaning explanation\n   • Usage by platform\n\n3. DESIGN-SYSTEM.md\n   Brand guidelines including:\n   • Visual identity principles\n   • Color system and contrast\n   • Gradient specifications\n   • Typography standards\n   • Icon geometry details\n   • Sizing recommendations\n   • Effects and filters\n   • Customization guide\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n🚀 GETTING STARTED\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nSTEP 1: Choose Your Use Case\n   • Website? → Use logos/claude-howto-logo.svg\n   • App/Avatar? → Use icons/claude-howto-icon.svg\n   • Browser? → Use favicons/favicon-32.svg\n\nSTEP 2: Read the Right Guide\n   • Quick setup? → Read QUICK-START.md\n   • Full details? → Read README.md\n   • Brand guidelines? → Read DESIGN-SYSTEM.md\n\nSTEP 3: Copy & Use\n   • Copy file to your project\n   • Use provided HTML code\n   • Or reference from CDN/web server\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✅ FILE CHECKLIST\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nLogos:\n  ✓ claude-howto-logo.svg (main logo)\n\nIcons:\n  ✓ claude-howto-icon.svg (app icon)\n\nFavicons (all sizes):\n  ✓ favicon-16.svg\n  ✓ favicon-32.svg\n  ✓ favicon-64.svg\n  ✓ favicon-128.svg\n  ✓ favicon-256.svg\n\nDocumentation:\n  ✓ README.md (complete guide)\n  ✓ QUICK-START.md (fast reference)\n  ✓ DESIGN-SYSTEM.md (brand guidelines)\n  ✓ INDEX.txt (this file)\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n📝 FILE FORMATS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nAll assets are in SVG format:\n  • Scalable: Works at any size\n  • Lightweight: Smaller than PNG/JPG\n  • Sharp: No pixelation at any zoom\n  • Flexible: Can be styled with CSS/JS\n  • Universal: Works in all modern browsers\n\nNo raster images needed - SVG covers all use cases!\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n🤝 INTEGRATION EXAMPLES\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nHTML (Web):\n  <img src=\"resources/icons/claude-howto-icon.svg\" alt=\"Claude How To\">\n\nMarkdown:\n  ![Claude How To](resources/icons/claude-howto-icon.svg)\n\nCSS Background:\n  background-image: url('resources/icons/claude-howto-icon.svg');\n\nReact/JSX:\n  import logo from './resources/icons/claude-howto-icon.svg';\n  <img src={logo} alt=\"Claude How To\" />\n\nNext.js/Web Framework:\n  <Image src={logo} alt=\"Claude How To\" />\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n📊 ASSET STATISTICS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nTotal Assets: 7 SVG files\n  • 1 Logo\n  • 1 Icon\n  • 5 Favicon variants\n\nDocumentation: 4 files\n  • Complete guide (README.md)\n  • Quick reference (QUICK-START.md)\n  • Brand guidelines (DESIGN-SYSTEM.md)\n  • This index (INDEX.txt)\n\nTotal Size: ~150 KB (all files)\n  • Individual SVGs: 8-15 KB each\n  • Documentation: 20-50 KB each\n\nDesign System Version: 1.0\nLast Updated: January 2026\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n📞 SUPPORT & MORE\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nFor detailed information:\n  1. Start with QUICK-START.md for immediate use\n  2. Refer to README.md for complete documentation\n  3. Check DESIGN-SYSTEM.md for brand guidelines\n\nQuestions or customization needed?\n  • Review DESIGN-SYSTEM.md for customization guide\n  • All files are fully editable SVG\n  • Maintain color palette for brand consistency\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nHappy building! 🚀\n\n"
  },
  {
    "path": "resources/MANIFEST.txt",
    "content": "╔════════════════════════════════════════════════════════════════════════════╗\n║                  CLAUDE HOW TO - COMPLETE ASSET MANIFEST                   ║\n║                      All Files Ready for Use                              ║\n╚════════════════════════════════════════════════════════════════════════════╝\n\n📦 FULL DIRECTORY MANIFEST\n═════════════════════════════════════════════════════════════════════════════\n\nresources/\n│\n├─ 📄 README.md                          (6.0K) Complete documentation\n├─ 📄 QUICK-START.md                     (2.5K) Copy & paste setup\n├─ 📄 DESIGN-SYSTEM.md                   (7.7K) Brand guidelines\n├─ 📄 INDEX.txt                          (12K)  Visual reference\n├─ 📄 MANIFEST.txt                       (this) File listing\n│\n├─ 📁 logos/                             (8.0K total)\n│  └─ 📊 claude-howto-logo.svg          (8.0K) 800×200px main logo\n│\n├─ 📁 icons/                             (8.0K total)\n│  └─ 🔷 claude-howto-icon.svg          (8.0K) 256×256px app icon\n│\n└─ 📁 favicons/                          (20K total)\n   ├─ 🔹 favicon-16.svg                 (3.2K) 16×16px browser tab\n   ├─ 🔹 favicon-32.svg                 (3.8K) 32×32px standard\n   ├─ 🔹 favicon-64.svg                 (4.1K) 64×64px high-DPI\n   ├─ 🔹 favicon-128.svg                (4.5K) 128×128px apple touch\n   └─ 🔹 favicon-256.svg                (4.9K) 256×256px modern\n\n═════════════════════════════════════════════════════════════════════════════\n\n📊 ASSET SUMMARY\n═════════════════════════════════════════════════════════════════════════════\n\nCATEGORY        COUNT   PURPOSE\n────────────────────────────────────────────────────────────────────────────\nLogos           1       Main horizontal logo for headers/marketing\nIcons           1       App icon for avatars/thumbnails\nFavicons        5       Browser tabs, bookmarks, mobile icons\nDocumentation   5       Setup guides, design system, reference\n────────────────────────────────────────────────────────────────────────────\nTOTAL           12      Complete brand asset package\n\n═════════════════════════════════════════════════════════════════════════════\n\n📄 DOCUMENTATION FILES - WHAT TO READ\n\n1️⃣  START HERE: QUICK-START.md\n    • Copy & paste HTML code\n    • Recommended sizes by use case\n    • CSS color variables\n    • Quick integration examples\n    ⏱️  5 minute read\n\n2️⃣  FULL DETAILS: README.md\n    • Complete asset descriptions\n    • HTML/CSS integration guide\n    • Favicon setup instructions\n    • Accessibility & optimization\n    ⏱️  15 minute read\n\n3️⃣  BRAND GUIDELINES: DESIGN-SYSTEM.md\n    • Visual identity principles\n    • Complete color system specs\n    • Icon geometry details\n    • Effects and filters\n    • Customization instructions\n    ⏱️  20 minute read\n\n4️⃣  VISUAL REFERENCE: INDEX.txt\n    • Directory structure diagram\n    • File quick reference table\n    • Design concept visualization\n    • Integration examples\n    ⏱️  10 minute read\n\n═════════════════════════════════════════════════════════════════════════════\n\n🎯 QUICK USAGE GUIDE\n\nFOR WEBSITES (HTML):\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-32.svg\">\n  <link rel=\"apple-touch-icon\" href=\"/resources/favicons/favicon-128.svg\">\n\nFOR MARKDOWN:\n  ![Claude How To](resources/icons/claude-howto-icon.svg)\n\nFOR REACT/NEXT.JS:\n  import icon from './resources/icons/claude-howto-icon.svg';\n\nFOR CSS BACKGROUND:\n  background-image: url('resources/icons/claude-howto-icon.svg');\n\n═════════════════════════════════════════════════════════════════════════════\n\n🎨 FILE SELECTION BY USE CASE\n\nUSE CASE                    FILE                        SIZE\n─────────────────────────────────────────────────────────────────────────────\nWebsite header              logos/claude-howto-logo.svg     800×200px\nBrowser tab                 favicons/favicon-32.svg         32×32px\nMobile home screen          favicons/favicon-128.svg        128×128px\nApp icon                    icons/claude-howto-icon.svg     256×256px\nSocial media thumbnail      icons/claude-howto-icon.svg     256×256px\nBookmark/favorite icon      favicons/favicon-64.svg         64×64px\nApple touch icon            favicons/favicon-128.svg        128×128px\nPWA/Android app             favicons/favicon-256.svg        256×256px\nOld browsers (fallback)     favicons/favicon-16.svg         16×16px\n\n═════════════════════════════════════════════════════════════════════════════\n\n✅ VERIFICATION CHECKLIST\n\nSVG Assets:\n  ✓ logos/claude-howto-logo.svg       Main logo\n  ✓ icons/claude-howto-icon.svg       App icon\n  ✓ favicons/favicon-16.svg           16px favicon\n  ✓ favicons/favicon-32.svg           32px favicon\n  ✓ favicons/favicon-64.svg           64px favicon\n  ✓ favicons/favicon-128.svg          128px favicon\n  ✓ favicons/favicon-256.svg          256px favicon\n\nDocumentation:\n  ✓ README.md                         Complete guide\n  ✓ QUICK-START.md                    Setup guide\n  ✓ DESIGN-SYSTEM.md                  Brand guidelines\n  ✓ INDEX.txt                         Visual reference\n  ✓ MANIFEST.txt                      This file\n\n═════════════════════════════════════════════════════════════════════════════\n\n🎨 DESIGN CONCEPT\n\nThe icon represents the Claude How To learning journey with ascending hexagons:\n\n              🔶 MINT\n        Advanced Features\n        Levels 7-10\n\n          🔶 EMERALD\n    Intermediate Skills\n    Levels 4-6\n\n      🔶 DARK EMERALD\n  Beginner Fundamentals\n  Levels 1-3\n\nCOLOR PALETTE:\n  • Deep Forest    #0d1f0d    Background\n  • Emerald        #10b981    Primary accent\n  • Dark Emerald   #059669    Secondary accent\n  • Forest         #047857    Tertiary accent\n  • Mint           #6ee7b7    Highlight\n  • Light Mint     #34d399    Secondary highlight\n\nAll colors: WCAG AAA accessible (8.2:1+ contrast)\n\n═════════════════════════════════════════════════════════════════════════════\n\n📥 HOW TO INTEGRATE\n\nSTEP 1: Copy files\n  cp -r resources/ /path/to/your/project/\n\nSTEP 2: Read documentation\n  Start with resources/QUICK-START.md\n\nSTEP 3: Add to HTML\n  Copy provided code snippets (see QUICK-START.md)\n\nSTEP 4: Customize (optional)\n  Reference DESIGN-SYSTEM.md for color changes\n\n═════════════════════════════════════════════════════════════════════════════\n\n📋 FILE SPECIFICATIONS\n\nFormat:             SVG (Scalable Vector Graphics)\nScalability:        Any size, no pixelation\nBrowser Support:    All modern browsers\nAccessibility:      WCAG AAA compliant\nColor Mode:         RGB/RGBA with gradients\nEffects:            Gradients, shadows, glows\nCustomizable:       Yes, see DESIGN-SYSTEM.md\nAnimated:           Static (can be animated with CSS/JS)\n\n═════════════════════════════════════════════════════════════════════════════\n\n🚀 NEXT STEPS\n\nIMMEDIATE:\n  1. Read resources/QUICK-START.md\n  2. Copy favicons to your project\n  3. Add favicon link to your HTML\n\nSHORT TERM:\n  1. Integrate logo into website\n  2. Use icon for social media\n  3. Review DESIGN-SYSTEM.md\n\nLONG TERM:\n  1. Maintain color palette consistency\n  2. Use brand assets across all materials\n  3. Reference guidelines for any customizations\n\n═════════════════════════════════════════════════════════════════════════════\n\n💡 PRO TIPS\n\n• Use favicon-32.svg as primary favicon (works on all modern browsers)\n• Use icons/claude-howto-icon.svg for avatars at 64-256px\n• Use logos/claude-howto-logo.svg for website headers (scale to fit)\n• Keep the ascending hexagon concept for any custom variants\n• Always maintain the established color palette\n• SVG files are editable - see DESIGN-SYSTEM.md for color customization\n• No PNG conversion needed - SVG works everywhere\n\n═════════════════════════════════════════════════════════════════════════════\n\n📞 NEED HELP?\n\n1. Quick setup?          → Read QUICK-START.md\n2. Full reference?       → Read README.md\n3. Brand guidelines?     → Read DESIGN-SYSTEM.md\n4. Visual overview?      → Read INDEX.txt\n5. Find a specific file? → Read this MANIFEST.txt\n\n═════════════════════════════════════════════════════════════════════════════\n\nGenerated: January 2026\nDesign System: v1.0\nAll files production-ready ✅\n\n═════════════════════════════════════════════════════════════════════════════\n"
  },
  {
    "path": "resources/QUICK-START.md",
    "content": "# Quick Start - Brand Assets\n\n## Copy Assets to Your Project\n\n```bash\n# Copy all resources to your web project\ncp -r resources/ /path/to/your/website/\n\n# Or just the favicons for web\ncp resources/favicons/* /path/to/your/website/public/\n```\n\n## Add to HTML (Copy & Paste)\n\n```html\n<!-- Favicons -->\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-32.svg\" sizes=\"32x32\">\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-16.svg\" sizes=\"16x16\">\n<link rel=\"apple-touch-icon\" href=\"/resources/favicons/favicon-128.svg\">\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-256.svg\" sizes=\"256x256\">\n<meta name=\"theme-color\" content=\"#000000\">\n```\n\n## Use in Markdown/Documentation\n\n```markdown\n# Claude How To\n\n![Claude How To Logo](resources/logos/claude-howto-logo.svg)\n\n![Icon](resources/icons/claude-howto-icon.svg)\n```\n\n## Recommended Sizes\n\n| Purpose | Size | File |\n|---------|------|------|\n| Website header | 520×120 | `logos/claude-howto-logo.svg` |\n| App icon | 256×256 | `icons/claude-howto-icon.svg` |\n| Browser tab | 32×32 | `favicons/favicon-32.svg` |\n| Mobile home screen | 128×128 | `favicons/favicon-128.svg` |\n| Desktop app | 256×256 | `favicons/favicon-256.svg` |\n| Small avatar | 64×64 | `favicons/favicon-64.svg` |\n\n## Color Values\n\n```css\n/* Use these in your CSS */\n--color-primary: #000000;\n--color-secondary: #6B7280;\n--color-accent: #22C55E;\n--color-bg-light: #FFFFFF;\n--color-bg-dark: #0A0A0A;\n```\n\n## Icon Design Meaning\n\n**Compass with Code Bracket**:\n- Compass ring = Navigation, structured learning path\n- Green north needle = Direction, progress, guidance\n- Black south needle = Grounding, solid foundation\n- `>` bracket = Terminal prompt, code, CLI context\n- Tick marks = Precision, structured steps\n\nThis symbolizes \"finding your way through code with clear guidance.\"\n\n## What to Use Where\n\n### Website\n- **Header**: Logo (`logos/claude-howto-logo.svg`)\n- **Favicon**: 32px (`favicons/favicon-32.svg`)\n- **Social preview**: Icon (`icons/claude-howto-icon.svg`)\n\n### GitHub\n- **README badge**: Icon (`icons/claude-howto-icon.svg`) at 64-128px\n- **Repository avatar**: Icon (`icons/claude-howto-icon.svg`)\n\n### Social Media\n- **Profile picture**: Icon (`icons/claude-howto-icon.svg`)\n- **Banner**: Logo (`logos/claude-howto-logo.svg`)\n- **Thumbnail**: Icon at 256×256px\n\n### Documentation\n- **Chapter headers**: Logo or icon (scaled to fit)\n- **Navigation icons**: Favicon (32-64px)\n\n---\n\nSee [README.md](README.md) for complete documentation.\n"
  },
  {
    "path": "resources/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"logos/claude-howto-logo.svg\">\n</picture>\n\n# Claude How To - Brand Assets\n\nComplete collection of logos, icons, and favicons for the Claude How To project. All assets use the V3.0 design: a compass with code bracket (`>`) symbol, representing guided navigation through code — using a Black/White/Gray palette with Bright Green (#22C55E) accent.\n\n## Directory Structure\n\n```\nresources/\n├── logos/\n│   ├── claude-howto-logo.svg       # Main logo - Light mode (520×120px)\n│   └── claude-howto-logo-dark.svg  # Main logo - Dark mode (520×120px)\n├── icons/\n│   ├── claude-howto-icon.svg       # App icon - Light mode (256×256px)\n│   └── claude-howto-icon-dark.svg  # App icon - Dark mode (256×256px)\n└── favicons/\n    ├── favicon-16.svg              # Favicon - 16×16px\n    ├── favicon-32.svg              # Favicon - 32×32px (primary)\n    ├── favicon-64.svg              # Favicon - 64×64px\n    ├── favicon-128.svg             # Favicon - 128×128px\n    └── favicon-256.svg             # Favicon - 256×256px\n```\n\nAdditional assets in `assets/logo/`:\n```\nassets/logo/\n├── logo-full.svg       # Mark + wordmark (horizontal)\n├── logo-mark.svg       # Compass symbol only (120×120px)\n├── logo-wordmark.svg   # Text only\n├── logo-icon.svg       # App icon (512×512, rounded)\n├── favicon.svg         # 16×16 optimized\n├── logo-white.svg      # White version for dark backgrounds\n└── logo-black.svg      # Black monochrome version\n```\n\n## Assets Overview\n\n### Design Concept (V3.0)\n\n**Compass with Code Bracket** — guidance meets code:\n- **Compass Ring** = Navigation, finding your way\n- **North Needle (Green)** = Direction, progress on the learning path\n- **South Needle (Black)** = Grounding, solid foundation\n- **`>` Bracket** = Terminal prompt, code, CLI context\n- **Tick Marks** = Precision, structured learning\n\n### Logos\n\n**Files**:\n- `logos/claude-howto-logo.svg` (Light mode)\n- `logos/claude-howto-logo-dark.svg` (Dark mode)\n\n**Specifications**:\n- **Size**: 520×120 px\n- **Purpose**: Main header/branding logo with wordmark\n- **Usage**:\n  - Website headers\n  - README badges\n  - Marketing materials\n  - Print materials\n- **Format**: SVG (fully scalable)\n- **Modes**: Light (white background) & Dark (#0A0A0A background)\n\n### Icons\n\n**Files**:\n- `icons/claude-howto-icon.svg` (Light mode)\n- `icons/claude-howto-icon-dark.svg` (Dark mode)\n\n**Specifications**:\n- **Size**: 256×256 px\n- **Purpose**: Application icon, avatars, thumbnails\n- **Usage**:\n  - App icons\n  - Profile avatars\n  - Social media thumbnails\n  - Documentation headers\n- **Format**: SVG (fully scalable)\n- **Modes**: Light (white background) & Dark (#0A0A0A background)\n\n**Design Elements**:\n- Compass ring with cardinal and intercardinal tick marks\n- Green north needle (direction/guidance)\n- Black south needle (foundation)\n- `>` code bracket at center (terminal/CLI)\n- Green center dot accent\n\n### Favicons\n\nOptimized versions at multiple sizes for web use:\n\n| File | Size | DPI | Usage |\n|------|------|-----|-------|\n| `favicon-16.svg` | 16×16 px | 1x | Browser tabs (older browsers) |\n| `favicon-32.svg` | 32×32 px | 1x | Standard browser favicon |\n| `favicon-64.svg` | 64×64 px | 1x-2x | High-DPI displays |\n| `favicon-128.svg` | 128×128 px | 2x | Apple touch icon, bookmarks |\n| `favicon-256.svg` | 256×256 px | 4x | Modern browsers, PWA icons |\n\n**Optimization Notes**:\n- 16px: Minimal geometry — ring, needles, chevron only\n- 32px: Adds cardinal tick marks\n- 64px+: Full detail with intercardinal ticks\n- All maintain visual consistency with main icon\n- SVG format ensures crisp display at any size\n\n## HTML Integration\n\n### Basic Favicon Setup\n\n```html\n<!-- Browser favicon -->\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-32.svg\">\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-16.svg\" sizes=\"16x16\">\n\n<!-- Apple touch icon (mobile home screen) -->\n<link rel=\"apple-touch-icon\" href=\"/resources/favicons/favicon-128.svg\">\n\n<!-- PWA & modern browsers -->\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-256.svg\" sizes=\"256x256\">\n```\n\n### Complete Setup\n\n```html\n<head>\n  <!-- Primary favicon -->\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-32.svg\" sizes=\"32x32\">\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-16.svg\" sizes=\"16x16\">\n\n  <!-- Apple touch icon -->\n  <link rel=\"apple-touch-icon\" href=\"/resources/favicons/favicon-128.svg\">\n\n  <!-- PWA icons -->\n  <link rel=\"icon\" type=\"image/svg+xml\" href=\"/resources/favicons/favicon-256.svg\" sizes=\"256x256\">\n\n  <!-- Android -->\n  <link rel=\"shortcut icon\" href=\"/resources/favicons/favicon-256.svg\">\n\n  <!-- PWA manifest reference (if using manifest.json) -->\n  <meta name=\"theme-color\" content=\"#000000\">\n</head>\n```\n\n## Color Palette\n\n### Primary Colors\n- **Black**: `#000000` (Primary text, strokes, south needle)\n- **White**: `#FFFFFF` (Light backgrounds)\n- **Gray**: `#6B7280` (Secondary text, minor tick marks)\n\n### Accent Color\n- **Bright Green**: `#22C55E` (North needle, center dot, accent lines — highlights only, never as background)\n\n### Dark Mode\n- **Background**: `#0A0A0A` (Near-black)\n\n### CSS Variables\n```css\n--color-primary: #000000;\n--color-secondary: #6B7280;\n--color-accent: #22C55E;\n--color-bg-light: #FFFFFF;\n--color-bg-dark: #0A0A0A;\n```\n\n### Tailwind Config\n```js\ncolors: {\n  brand: {\n    primary: '#000000',\n    secondary: '#6B7280',\n    accent: '#22C55E',\n  }\n}\n```\n\n### Usage Guidelines\n- Use black for primary text and structural elements\n- Use gray for secondary/supporting elements\n- Use green **only** for highlights — needle, dots, accent lines\n- Never use green as a background color\n- Maintain WCAG AA contrast (4.5:1 minimum)\n\n## Design Guidelines\n\n### Logo Usage\n- Use on white or dark (#0A0A0A) backgrounds\n- Scale proportionally\n- Include clear space around logo (minimum: logo height / 2)\n- Use provided light/dark variants for appropriate backgrounds\n\n### Icon Usage\n- Use at standard sizes: 16, 32, 64, 128, 256px\n- Maintain the compass proportions\n- Scale proportionally\n\n### Favicon Usage\n- Use appropriate size for context\n- 16-32px: Browser tabs, bookmarks\n- 64px: Favicon site icons\n- 128px+: Apple/Android home screens\n\n## SVG Optimization\n\nAll SVG files are flat design with no gradients or filters:\n- Clean stroke-based geometry\n- No embedded rasters\n- Optimized paths\n- Responsive viewBox\n\nFor web optimization:\n```bash\n# Compress SVG while maintaining quality\nsvgo --config='{\n  \"js2svg\": {\n    \"indent\": 2\n  },\n  \"plugins\": [\n    \"convertStyleToAttrs\",\n    \"removeRasterImages\"\n  ]\n}' input.svg -o output.svg\n```\n\n## PNG Conversion\n\nTo convert SVG to PNG for older browser support:\n\n```bash\n# Using ImageMagick\nconvert -density 300 -background none favicon-256.svg favicon-256.png\n\n# Using Inkscape\ninkscape -D -z --file=favicon-256.svg --export-png=favicon-256.png\n```\n\n## Accessibility\n\n- High contrast color ratios (WCAG AA compliant — 4.5:1 minimum)\n- Clean geometric shapes recognizable at all sizes\n- Scalable vector format\n- No text in icons (text added separately in wordmark)\n- No red-green color dependency for meaning\n\n## Attribution\n\nThese assets are part of the Claude How To project.\n\n**License**: MIT (see project LICENSE file)\n\n## Version History\n\n- **v3.0** (February 2026): Compass-bracket design with Black/White/Gray + Green accent palette\n- **v2.0** (January 2026): Claude-inspired 12-ray starburst design with emerald palette\n- **v1.0** (January 2026): Original hexagon-based progression icon design\n\n---\n\n**Last Updated**: February 2026\n**Current Version**: 3.0 (Compass-Bracket)\n**All Assets**: Production-ready SVG, fully scalable, WCAG AA accessible\n"
  },
  {
    "path": "resources.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# List of good resources\n\n## Official Documentation\n\n| Resource | Description | Link |\n|----------|-------------|------|\n| Claude Code Docs | Official Claude Code documentation | [code.claude.com/docs/en/overview](https://code.claude.com/docs/en/overview) |\n| Anthropic Docs | Full Anthropic documentation | [docs.anthropic.com](https://docs.anthropic.com) |\n| MCP Protocol | Model Context Protocol specification | [modelcontextprotocol.io](https://modelcontextprotocol.io) |\n| MCP Servers | Official MCP server implementations | [github.com/modelcontextprotocol/servers](https://github.com/modelcontextprotocol/servers) |\n| Anthropic Cookbook | Code examples and tutorials | [github.com/anthropics/anthropic-cookbook](https://github.com/anthropics/anthropic-cookbook) |\n| Claude Code Skills | Community skills repository | [github.com/anthropics/skills](https://github.com/anthropics/skills) |\n| Agent Teams | Multi-agent coordination and collaboration | [code.claude.com/docs/en/agent-teams](https://code.claude.com/docs/en/agent-teams) |\n| Scheduled Tasks | Recurring tasks with /loop and cron | [code.claude.com/docs/en/scheduled-tasks](https://code.claude.com/docs/en/scheduled-tasks) |\n| Chrome Integration | Browser automation | [code.claude.com/docs/en/chrome](https://code.claude.com/docs/en/chrome) |\n| Keybindings | Keyboard shortcut customization | [code.claude.com/docs/en/keybindings](https://code.claude.com/docs/en/keybindings) |\n| Desktop App | Native desktop application | [code.claude.com/docs/en/desktop](https://code.claude.com/docs/en/desktop) |\n| Remote Control | Remote session control | [code.claude.com/docs/en/remote-control](https://code.claude.com/docs/en/remote-control) |\n| Auto Mode | Automatic permission management | [code.claude.com/docs/en/auto-mode](https://code.claude.com/docs/en/auto-mode) |\n| Channels | Multi-channel communication | [code.claude.com/docs/en/channels](https://code.claude.com/docs/en/channels) |\n| Voice Dictation | Voice input for Claude Code | [code.claude.com/docs/en/voice-dictation](https://code.claude.com/docs/en/voice-dictation) |\n\n## Anthropic Engineering Blog\n\n| Article | Description | Link |\n|---------|-------------|------|\n| Code Execution with MCP | How to solve MCP context bloat using code execution — 98.7% token reduction | [anthropic.com/engineering/code-execution-with-mcp](https://www.anthropic.com/engineering/code-execution-with-mcp) |\n\n---\n\n## Mastering Claude Code in 30 Minutes\n\n_Video_: https://www.youtube.com/watch?v=6eBSHbLKuN0\n\n_**All Tips**_\n- **Explore Advanced Features and Shortcuts**\n  - Regularly check Claude's new code editing and context features in their release notes.\n  - Learn keyboard shortcuts to switch between chat, file, and editor views quickly.\n\n- **Efficient Setup**\n  - Create project-specific sessions with clear names/descriptions for easy retrieval.\n  - Pin most-used files or folders so Claude can access them at any time.\n  - Set up Claude's integrations (e.g., GitHub, popular IDEs) to streamline your coding process.\n\n- **Effective Codebase Q&A**\n  - Ask Claude detailed questions about architecture, design patterns, and specific modules.\n  - Use file and line references in your questions (e.g., \"What does the logic in `app/models/user.py` accomplish?\").\n  - For large codebases, provide a summary or manifest to help Claude focus.\n  - **Example prompt**: _\"Can you explain the authentication flow implemented in src/auth/AuthService.ts:45-120? How does it integrate with the middleware in src/middleware/auth.ts?\"_\n\n- **Code Editing & Refactoring**\n  - Use inline comments or requests in code blocks to get focused edits (\"Refactor this function for clarity\").\n  - Ask for side-by-side before/after comparisons.\n  - Let Claude generate tests or documentation after major edits for quality assurance.\n  - **Example prompt**: _\"Refactor the getUserData function in api/users.js to use async/await instead of promises. Show me a before/after comparison and generate unit tests for the refactored version.\"_\n\n- **Context Management**\n  - Limit your pasted code/context to only what's relevant for the current task.\n  - Use structured prompts (\"Here's file A, here's function B, my question is X\") for best performance.\n  - Remove or collapse large files in the prompt window to avoid exceeding context limits.\n  - **Example prompt**: _\"Here's the User model from models/User.js and the validateUser function from utils/validation.js. My question is: how can I add email validation while maintaining backward compatibility?\"_\n\n- **Integrate Team Tools**\n  - Connect Claude sessions to your team's repositories and documentation.\n  - Use built-in templates or create custom ones for recurring engineering tasks.\n  - Collaborate by sharing session transcripts and prompts with teammates.\n\n- **Boosting Performance**\n  - Give Claude clear, goal-oriented instructions (e.g., \"Summarize this class in five bullet points\").\n  - Trim unnecessary comments and boilerplate from context windows.\n  - If Claude's output is off track, reset context or rephrase questions for better alignment.\n  - **Example prompt**: _\"Summarize the DatabaseManager class in src/db/Manager.ts in five bullet points, focusing on its main responsibilities and key methods.\"_\n\n- **Practical Use Examples**\n  - Debugging: Paste errors and stack traces, then ask for possible causes and fixes.\n  - Test Generation: Request property-based, unit, or integration tests for complex logic.\n  - Code Reviews: Ask Claude to identify risky changes, edge cases, or code smells.\n  - **Example prompts**:\n    - _\"I'm getting this error: 'TypeError: Cannot read property 'map' of undefined at line 42 in components/UserList.jsx'. Here's the stack trace and the relevant code. What's causing this and how can I fix it?\"_\n    - _\"Generate comprehensive unit tests for the PaymentProcessor class, including edge cases for failed transactions, timeouts, and invalid inputs.\"_\n    - _\"Review this pull request diff and identify potential security issues, performance bottlenecks, and code smells.\"_\n\n- **Workflow Automation**\n  - Script repetitive tasks (like formatting, clean-ups, and repetitive renaming) using Claude prompts.\n  - Use Claude to draft PR descriptions, release notes, or documentation based on code diffs.\n  - **Example prompt**: _\"Based on the git diff, create a detailed PR description with a summary of changes, list of modified files, testing steps, and potential impacts. Also generate release notes for version 2.3.0.\"_\n\n**Tip**: For best results, combine several of these practices—start by pinning critical files and summarizing your goals, then use focused prompts and Claude’s refactoring tools to incrementally improve your codebase and automation.\n\n\n**Recommended workflow with Claude Code**\n\n### Recommended Workflow with Claude Code\n\n#### For a New Repository\n\n1. **Initialize the Repo & Claude Integration**\n   - Set up your new repository with essential structure: README, LICENSE, .gitignore, root configs.\n   - Create a `CLAUDE.md` file describing the architecture, high-level goals, and coding guidelines.\n   - Install Claude Code and link it to your repository for code suggestions, test scaffolding, and workflow automation.\n\n2. **Use Plan Mode and Specs**\n   - Use plan mode (`shift-tab` or `/plan`) to draft a detailed specification before implementing features.\n   - Ask Claude for architecture suggestions and initial project layout.\n   - Keep a clear, goal-oriented prompt sequence—ask for component outlines, major modules, and responsibilities.\n\n3. **Iterative Develop & Review**\n   - Implement core features in small chunks, prompting Claude for code generation, refactoring, and documentation.\n   - Request unit tests and examples after each increment.\n   - Maintain a running task list in CLAUDE.md.\n\n4. **Automate CI/CD and Deployment**\n   - Use Claude to scaffold GitHub Actions, npm/yarn scripts, or deployment workflows.\n   - Adapt pipelines easily by updating your CLAUDE.md and requesting corresponding commands/scripts.\n\n```mermaid\ngraph TD\n    A[Start New Repository] --> B[Initialize Repository Structure]\n    B --> C[Create README, LICENSE, .gitignore]\n    C --> D[Create CLAUDE.md]\n    D --> E[Document Architecture & Guidelines]\n    E --> F[Install & Link Claude Code]\n\n    F --> G[Enter Plan Mode]\n    G --> H[Draft Feature Specification]\n    H --> I[Get Architecture Suggestions]\n    I --> J[Define Components & Modules]\n\n    J --> K[Implement Feature Chunk]\n    K --> L[Generate Code with Claude]\n    L --> M[Request Unit Tests]\n    M --> N[Review & Refactor]\n    N --> O{More Features?}\n    O -->|Yes| K\n    O -->|No| P[Update Task List in CLAUDE.md]\n\n    P --> Q[Setup CI/CD Pipeline]\n    Q --> R[Scaffold GitHub Actions]\n    R --> S[Create Deployment Scripts]\n    S --> T[Test Automation]\n    T --> U[Repository Ready]\n\n    style A fill:#e1f5ff\n    style G fill:#fff4e1\n    style K fill:#f0ffe1\n    style Q fill:#ffe1f5\n    style U fill:#90EE90\n```\n\n#### For an Existing Repository\n\n1. **Repository & Context Setup**\n   - Add or update `CLAUDE.md` to document repo structure, coding patterns, and key files. For legacy repos, use `CLAUDE_LEGACY.md` covering frameworks, version maps, instructions, bugs, and upgrade notes.\n   - Pin or highlight main files Claude should use for context.\n\n2. **Contextual Code Q&A**\n   - Ask Claude for code reviews, bug explanations, refactors, or migration plans referencing specific files/functions.\n   - Give Claude explicit boundaries (e.g., \"modify only these files\" or \"no new dependencies\").\n\n3. **Branch, Worktree, and Multi-Session Management**\n   - Use multiple git worktrees for isolated features or bug fixes and launch separate Claude sessions per worktree.\n   - Keep terminal tabs/windows organized by branch or feature for parallel workflows.\n\n4. **Team Tools and Automation**\n   - Synchronize custom commands via `.claude/commands/` for cross-team consistency.\n   - Automate repetitive tasks, PR creation, and code formatting via Claude's slash commands or hooks.\n   - Share sessions and context with team members for collaborative troubleshooting and review.\n\n```mermaid\ngraph TD\n    A[Start with Existing Repository] --> B{Legacy Codebase?}\n    B -->|Yes| C[Create CLAUDE_LEGACY.md]\n    B -->|No| D[Create/Update CLAUDE.md]\n    C --> E[Document Frameworks & Version Maps]\n    D --> F[Document Structure & Patterns]\n    E --> G[Pin Key Files for Context]\n    F --> G\n\n    G --> H[Identify Task Type]\n    H --> I{Task Category}\n    I -->|Bug Fix| J[Ask Claude for Bug Analysis]\n    I -->|Code Review| K[Request Code Review]\n    I -->|Refactor| L[Plan Refactoring Strategy]\n    I -->|Migration| M[Create Migration Plan]\n\n    J --> N[Set Explicit Boundaries]\n    K --> N\n    L --> N\n    M --> N\n\n    N --> O{Multiple Features?}\n    O -->|Yes| P[Create Git Worktrees]\n    O -->|No| Q[Work on Main Branch]\n    P --> R[Launch Separate Claude Sessions]\n    R --> S[Organize Terminal Tabs]\n    Q --> S\n\n    S --> T[Setup Team Automation]\n    T --> U[Sync .claude/commands/]\n    U --> V[Configure Slash Commands]\n    V --> W[Setup Hooks for Automation]\n    W --> X[Share Session Context with Team]\n\n    X --> Y{More Tasks?}\n    Y -->|Yes| H\n    Y -->|No| Z[Workflow Complete]\n\n    style A fill:#e1f5ff\n    style C fill:#ffecec\n    style D fill:#fff4e1\n    style P fill:#f0ffe1\n    style T fill:#ffe1f5\n    style Z fill:#90EE90\n```\n\n**Tips**:\n- Start each new feature or fix with a spec and plan mode prompt.\n- For legacy and complex repos, store detailed guidance in CLAUDE.md/CLAUDE_LEGACY.md.\n- Give clear, focused instructions and break down complex work into multi-phase plans.\n- Regularly clean up sessions, prune context, and remove completed worktrees to avoid clutter.\n\nThese steps capture the core recommendations for smooth workflows with Claude Code in both new and existing codebases.\n\n---\n\n## New Features & Capabilities (March 2026)\n\n### Key Feature Resources\n\n| Feature | Description | Learn More |\n|---------|-------------|------------|\n| **Auto Memory** | Claude automatically learns and remembers your preferences across sessions | [Memory Guide](02-memory/) |\n| **Remote Control** | Programmatically control Claude Code sessions from external tools and scripts | [Advanced Features](09-advanced-features/) |\n| **Web Sessions** | Access Claude Code through browser-based interfaces for remote development | [CLI Reference](10-cli/) |\n| **Desktop App** | Native desktop application for Claude Code with enhanced UI | [Claude Code Docs](https://code.claude.com/docs/en/desktop) |\n| **Extended Thinking** | Deep reasoning toggle via `Alt+T`/`Option+T` or `MAX_THINKING_TOKENS` env var | [Advanced Features](09-advanced-features/) |\n| **Permission Modes** | Fine-grained control: default, acceptEdits, plan, auto, dontAsk, bypassPermissions | [Advanced Features](09-advanced-features/) |\n| **7-Tier Memory** | Managed Policy, Project, Project Rules, User, User Rules, Local, Auto Memory | [Memory Guide](02-memory/) |\n| **Hook Events** | 25 events: PreToolUse, PostToolUse, PostToolUseFailure, Stop, StopFailure, SubagentStart, SubagentStop, Notification, Elicitation, and more | [Hooks Guide](06-hooks/) |\n| **Agent Teams** | Coordinate multiple agents working together on complex tasks | [Subagents Guide](04-subagents/) |\n| **Scheduled Tasks** | Set up recurring tasks with `/loop` and cron tools | [Advanced Features](09-advanced-features/) |\n| **Chrome Integration** | Browser automation with headless Chromium | [Advanced Features](09-advanced-features/) |\n| **Keyboard Customization** | Customize keybindings including chord sequences | [Advanced Features](09-advanced-features/) |\n"
  },
  {
    "path": "scripts/README.md",
    "content": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"../resources/logos/claude-howto-logo-dark.svg\">\n  <img alt=\"Claude How To\" src=\"../resources/logos/claude-howto-logo.svg\">\n</picture>\n\n# EPUB Builder Script\n\nBuild an EPUB ebook from the Claude How-To markdown files.\n\n## Features\n\n- Organizes chapters by folder structure (01-slash-commands, 02-memory, etc.)\n- Renders Mermaid diagrams as PNG images via Kroki.io API\n- Async concurrent fetching - renders all diagrams in parallel\n- Generates a cover image from the project logo\n- Converts internal markdown links to EPUB chapter references\n- Strict error mode - fails if any diagram cannot be rendered\n\n## Requirements\n\n- Python 3.10+\n- [uv](https://github.com/astral-sh/uv)\n- Internet connection for Mermaid diagram rendering\n\n## Quick Start\n\n```bash\n# Simplest way - uv handles everything\nuv run scripts/build_epub.py\n```\n\n## Development Setup\n\n```bash\n# Create virtual environment\nuv venv\n\n# Activate and install dependencies\nsource .venv/bin/activate\nuv pip install -r requirements-dev.txt\n\n# Run tests\npytest scripts/tests/ -v\n\n# Run the script\npython scripts/build_epub.py\n```\n\n## Command-Line Options\n\n```\nusage: build_epub.py [-h] [--root ROOT] [--output OUTPUT] [--verbose]\n                     [--timeout TIMEOUT] [--max-concurrent MAX_CONCURRENT]\n\noptions:\n  -h, --help            show this help message and exit\n  --root, -r ROOT       Root directory (default: repo root)\n  --output, -o OUTPUT   Output path (default: claude-howto-guide.epub)\n  --verbose, -v         Enable verbose logging\n  --timeout TIMEOUT     API timeout in seconds (default: 30)\n  --max-concurrent N    Max concurrent requests (default: 10)\n```\n\n## Examples\n\n```bash\n# Build with verbose output\nuv run scripts/build_epub.py --verbose\n\n# Custom output location\nuv run scripts/build_epub.py --output ~/Desktop/claude-guide.epub\n\n# Limit concurrent requests (if rate-limited)\nuv run scripts/build_epub.py --max-concurrent 5\n```\n\n## Output\n\nCreates `claude-howto-guide.epub` in the repository root directory.\n\nThe EPUB includes:\n- Cover image with project logo\n- Table of contents with nested sections\n- All markdown content converted to EPUB-compatible HTML\n- Mermaid diagrams rendered as PNG images\n\n## Running Tests\n\n```bash\n# With virtual environment\nsource .venv/bin/activate\npytest scripts/tests/ -v\n\n# Or with uv directly\nuv run --with pytest --with pytest-asyncio \\\n    --with ebooklib --with markdown --with beautifulsoup4 \\\n    --with httpx --with pillow --with tenacity \\\n    pytest scripts/tests/ -v\n```\n\n## Dependencies\n\nManaged via PEP 723 inline script metadata:\n\n| Package | Purpose |\n|---------|---------|\n| `ebooklib` | EPUB generation |\n| `markdown` | Markdown to HTML conversion |\n| `beautifulsoup4` | HTML parsing |\n| `httpx` | Async HTTP client |\n| `pillow` | Cover image generation |\n| `tenacity` | Retry logic |\n\n## Troubleshooting\n\n**Build fails with network error**: Check internet connectivity and Kroki.io status. Try `--timeout 60`.\n\n**Rate limiting**: Reduce concurrent requests with `--max-concurrent 3`.\n\n**Missing logo**: The script generates a text-only cover if `claude-howto-logo.png` is not found.\n"
  },
  {
    "path": "scripts/build_epub.py",
    "content": "#!/usr/bin/env -S uv run --script\n# /// script\n# dependencies = [\"ebooklib\", \"markdown\", \"beautifulsoup4\", \"httpx\", \"pillow\", \"tenacity\"]\n# ///\n\"\"\"\nBuild an EPUB from the Claude How-To markdown files.\n\nUsage:\n    Run from the repository root directory:\n        ./scripts/build_epub.py\n\n    Or run directly with Python/uv:\n        uv run scripts/build_epub.py\n        python scripts/build_epub.py\n\n    Command-line options:\n        --root, -r      Root directory containing markdown files (default: repo root)\n        --output, -o    Output EPUB file path (default: <root>/claude-howto-guide.epub)\n        --verbose, -v   Enable verbose logging\n        --timeout       Timeout for API requests in seconds (default: 30)\n        --max-concurrent Maximum concurrent API requests (default: 10)\n\n    The script uses inline script dependencies (PEP 723), so uv will\n    automatically install required packages in an isolated environment.\n\nOutput:\n    Creates 'claude-howto-guide.epub' in the repository root directory.\n\nFeatures:\n    - Organizes chapters by folder structure (01-slash-commands, etc.)\n    - Renders Mermaid diagrams as PNG images via Kroki.io API (async concurrent)\n    - Generates a cover image from the project logo\n    - Converts internal markdown links to EPUB chapter references\n    - Handles SVG images by replacing with styled placeholders\n    - Strict error mode: fails if any diagram cannot be rendered\n\nRequirements:\n    - uv (recommended) or Python 3.10+ with dependencies installed\n    - Internet connection for Mermaid diagram rendering\n    - Repository structure with markdown files and claude-howto-logo.png\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport asyncio\nimport base64\nimport html\nimport logging\nimport os\nimport re\nimport sys\nimport zlib\nfrom dataclasses import dataclass, field\nfrom io import BytesIO\nfrom pathlib import Path\n\nimport httpx\nimport markdown\nfrom bs4 import BeautifulSoup\nfrom ebooklib import epub\nfrom PIL import Image, ImageDraw, ImageFont\nfrom tenacity import (\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\n\n# =============================================================================\n# Custom Exceptions\n# =============================================================================\n\n\nclass EPUBBuildError(Exception):\n    \"\"\"Base exception for EPUB build errors.\"\"\"\n\n    pass\n\n\nclass MermaidRenderError(EPUBBuildError):\n    \"\"\"Error rendering Mermaid diagram.\"\"\"\n\n    pass\n\n\nclass ValidationError(EPUBBuildError):\n    \"\"\"Error validating input or output.\"\"\"\n\n    pass\n\n\nclass CoverGenerationError(EPUBBuildError):\n    \"\"\"Error generating cover image.\"\"\"\n\n    pass\n\n\n# =============================================================================\n# Configuration and State\n# =============================================================================\n\n\n@dataclass\nclass EPUBConfig:\n    \"\"\"Configuration for EPUB generation.\"\"\"\n\n    # Paths\n    root_path: Path\n    output_path: Path\n    logo_path: Path | None = None\n\n    # EPUB Metadata\n    identifier: str = \"claude-howto-guide\"\n    title: str = \"Claude Code How-To Guide\"\n    language: str = \"en\"\n    author: str = \"Claude Code Community\"\n\n    # Cover Settings\n    cover_width: int = 600\n    cover_height: int = 900\n    cover_bg_color: tuple[int, int, int] = (26, 26, 46)\n    cover_title_color: tuple[int, int, int] = (78, 205, 196)\n    cover_subtitle_color: tuple[int, int, int] = (168, 178, 209)\n\n    # Network Settings\n    kroki_base_url: str = \"https://kroki.io\"\n    request_timeout: float = 30.0\n    max_retries: int = 3\n    max_concurrent_requests: int = 10\n\n    # Font paths (platform-specific)\n    title_font_paths: list[str] = field(\n        default_factory=lambda: [\n            \"/System/Library/Fonts/Supplemental/Arial Bold.ttf\",\n            \"/System/Library/Fonts/Helvetica.ttc\",\n            \"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf\",  # Linux\n            \"C:\\\\Windows\\\\Fonts\\\\arialbd.ttf\",  # Windows\n        ]\n    )\n    subtitle_font_paths: list[str] = field(\n        default_factory=lambda: [\n            \"/System/Library/Fonts/Supplemental/Arial.ttf\",\n            \"/System/Library/Fonts/Helvetica.ttc\",\n            \"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\",  # Linux\n            \"C:\\\\Windows\\\\Fonts\\\\arial.ttf\",  # Windows\n        ]\n    )\n\n\n@dataclass\nclass BuildState:\n    \"\"\"Mutable state for the build process.\"\"\"\n\n    mermaid_cache: dict[str, tuple[bytes, str]] = field(default_factory=dict)\n    mermaid_counter: int = 0\n    mermaid_added_to_book: set[str] = field(default_factory=set)\n    path_to_chapter: dict[str, str] = field(default_factory=dict)\n\n    def reset(self) -> None:\n        \"\"\"Reset all state for a fresh build.\"\"\"\n        self.mermaid_cache.clear()\n        self.mermaid_counter = 0\n        self.mermaid_added_to_book.clear()\n        self.path_to_chapter.clear()\n\n\n@dataclass\nclass ChapterInfo:\n    \"\"\"Information about a chapter for processing.\"\"\"\n\n    file_path: Path\n    display_name: str\n    file_title: str\n    chapter_filename: str\n    is_folder_overview: bool = False\n    folder_name: str | None = None\n\n\n# =============================================================================\n# Logging Setup\n# =============================================================================\n\n\ndef setup_logging(verbose: bool = False) -> logging.Logger:\n    \"\"\"Configure logging for the build process.\"\"\"\n    level = logging.DEBUG if verbose else logging.INFO\n    logging.basicConfig(\n        level=level,\n        format=\"%(asctime)s - %(levelname)s - %(message)s\",\n        datefmt=\"%H:%M:%S\",\n    )\n    return logging.getLogger(\"epub_builder\")\n\n\n# =============================================================================\n# Input Validation\n# =============================================================================\n\n\ndef validate_inputs(config: EPUBConfig, logger: logging.Logger) -> None:\n    \"\"\"Validate all inputs before starting the build.\"\"\"\n    errors = []\n\n    # Check root path exists\n    if not config.root_path.exists():\n        errors.append(f\"Root path does not exist: {config.root_path}\")\n    elif not config.root_path.is_dir():\n        errors.append(f\"Root path is not a directory: {config.root_path}\")\n\n    # Check output path is writable\n    output_dir = config.output_path.parent\n    if not output_dir.exists():\n        errors.append(f\"Output directory does not exist: {output_dir}\")\n    elif not os.access(output_dir, os.W_OK):\n        errors.append(f\"Output directory is not writable: {output_dir}\")\n\n    # Check logo if specified\n    logo_path = config.logo_path or (config.root_path / \"claude-howto-logo.png\")\n    if not logo_path.exists():\n        logger.warning(\n            f\"Logo file not found: {logo_path}. Cover will be generated without logo.\"\n        )\n\n    # Verify at least some markdown files exist\n    md_files = list(config.root_path.glob(\"**/*.md\"))\n    if not md_files:\n        errors.append(f\"No markdown files found in {config.root_path}\")\n\n    if errors:\n        for error in errors:\n            logger.error(error)\n        raise ValidationError(\"\\n\".join(errors))\n\n\n# =============================================================================\n# Mermaid Rendering (Async with Retry)\n# =============================================================================\n\n\ndef sanitize_mermaid(mermaid_code: str) -> str:\n    \"\"\"Sanitize mermaid code to avoid markdown parsing issues.\n\n    Mermaid's markdown-in-nodes feature incorrectly interprets numbered\n    lists (e.g., \"1. Item\") inside node labels. This escapes the period\n    to prevent that.\n    \"\"\"\n    # Escape numbered list patterns inside brackets: [1. Text] -> [1\\. Text]\n    sanitized = re.sub(r'\\[([\"\\']?)(\\d+)\\.(\\s)', r\"[\\1\\2\\\\.\\3\", mermaid_code)\n    return sanitized\n\n\nclass MermaidRenderer:\n    \"\"\"Async renderer for Mermaid diagrams via Kroki.io API.\"\"\"\n\n    def __init__(\n        self, config: EPUBConfig, state: BuildState, logger: logging.Logger\n    ) -> None:\n        self.config = config\n        self.state = state\n        self.logger = logger\n        self._semaphore: asyncio.Semaphore | None = None\n\n    async def _fetch_single(\n        self, client: httpx.AsyncClient, mermaid_code: str, index: int\n    ) -> tuple[str, tuple[bytes, str]]:\n        \"\"\"Fetch a single Mermaid diagram with retry logic.\"\"\"\n        cache_key = mermaid_code.strip()\n\n        # Check cache first\n        if cache_key in self.state.mermaid_cache:\n            self.logger.debug(f\"Cache hit for diagram {index}\")\n            return cache_key, self.state.mermaid_cache[cache_key]\n\n        # Rate limit with semaphore\n        assert self._semaphore is not None\n        async with self._semaphore:\n            result = await self._fetch_with_retry(client, mermaid_code, index)\n            if result is None:\n                raise MermaidRenderError(\n                    f\"Failed to render Mermaid diagram {index} after {self.config.max_retries} attempts\"\n                )\n            return cache_key, result\n\n    @retry(\n        stop=stop_after_attempt(3),\n        wait=wait_exponential(multiplier=1, min=1, max=10),\n        retry=retry_if_exception_type((httpx.TimeoutException, httpx.NetworkError)),\n        reraise=True,\n    )\n    async def _fetch_with_retry(\n        self, client: httpx.AsyncClient, mermaid_code: str, index: int\n    ) -> tuple[bytes, str] | None:\n        \"\"\"Fetch diagram with retry logic.\"\"\"\n        try:\n            compressed = zlib.compress(mermaid_code.encode(\"utf-8\"), level=9)\n            encoded = base64.urlsafe_b64encode(compressed).decode(\"ascii\")\n            url = f\"{self.config.kroki_base_url}/mermaid/png/{encoded}\"\n\n            self.logger.debug(f\"Fetching diagram {index}...\")\n            response = await client.get(url, timeout=self.config.request_timeout)\n\n            if response.status_code == 200:\n                self.state.mermaid_counter += 1\n                img_name = f\"mermaid_{self.state.mermaid_counter}.png\"\n                result = (response.content, img_name)\n                cache_key = mermaid_code.strip()\n                self.state.mermaid_cache[cache_key] = result\n                self.logger.info(f\"Rendered diagram {index} -> {img_name}\")\n                return result\n            else:\n                self.logger.warning(\n                    f\"Kroki API returned {response.status_code} for diagram {index}\"\n                )\n                raise MermaidRenderError(\n                    f\"Kroki API returned {response.status_code} for diagram {index}\"\n                )\n\n        except httpx.TimeoutException:\n            self.logger.warning(f\"Timeout fetching diagram {index}, will retry...\")\n            raise\n        except httpx.NetworkError as e:\n            self.logger.warning(\n                f\"Network error for diagram {index}: {e}, will retry...\"\n            )\n            raise\n\n    async def render_all(\n        self, diagrams: list[tuple[int, str]]\n    ) -> dict[str, tuple[bytes, str]]:\n        \"\"\"Render all Mermaid diagrams concurrently.\"\"\"\n        self._semaphore = asyncio.Semaphore(self.config.max_concurrent_requests)\n        results: dict[str, tuple[bytes, str]] = {}\n\n        async with httpx.AsyncClient(\n            follow_redirects=True,\n            limits=httpx.Limits(max_connections=self.config.max_concurrent_requests),\n            timeout=httpx.Timeout(self.config.request_timeout),\n        ) as client:\n            tasks = [\n                self._fetch_single(client, sanitize_mermaid(code), idx)\n                for idx, code in diagrams\n            ]\n\n            self.logger.info(f\"Fetching {len(tasks)} Mermaid diagrams concurrently...\")\n\n            # Use gather with return_exceptions=False for strict mode\n            completed = await asyncio.gather(*tasks)\n\n            for cache_key, data in completed:\n                results[cache_key] = data\n\n        success_count = len(results)\n        self.logger.info(\n            f\"Successfully rendered {success_count}/{len(diagrams)} diagrams\"\n        )\n        return results\n\n\ndef extract_all_mermaid_blocks(\n    md_files: list[tuple[Path, str]], logger: logging.Logger\n) -> list[tuple[int, str]]:\n    \"\"\"Extract all unique Mermaid code blocks from markdown files.\"\"\"\n    pattern = r\"```mermaid\\n(.*?)```\"\n    seen: set[str] = set()\n    diagrams: list[tuple[int, str]] = []\n    counter = 0\n\n    for file_path, _ in md_files:\n        try:\n            content = file_path.read_text(encoding=\"utf-8\")\n            for match in re.finditer(pattern, content, flags=re.DOTALL):\n                code = match.group(1).strip()\n                if code not in seen:\n                    seen.add(code)\n                    counter += 1\n                    diagrams.append((counter, code))\n        except UnicodeDecodeError as e:\n            logger.warning(f\"Failed to read {file_path}: {e}\")\n\n    logger.info(f\"Found {len(diagrams)} unique Mermaid diagrams\")\n    return diagrams\n\n\n# =============================================================================\n# Chapter Collection (Single-Pass)\n# =============================================================================\n\n\ndef get_chapter_order() -> list[tuple[str, str]]:\n    \"\"\"Define the order of chapters based on folder structure.\"\"\"\n    return [\n        (\"README.md\", \"Introduction\"),\n        (\"LEARNING-ROADMAP.md\", \"Learning Roadmap\"),\n        (\"QUICK_REFERENCE.md\", \"Quick Reference\"),\n        (\"claude_concepts_guide.md\", \"Claude Concepts Guide\"),\n        (\"01-slash-commands\", \"Slash Commands\"),\n        (\"02-memory\", \"Memory\"),\n        (\"03-skills\", \"Skills\"),\n        (\"04-subagents\", \"Subagents\"),\n        (\"05-mcp\", \"MCP Protocol\"),\n        (\"06-hooks\", \"Hooks\"),\n        (\"07-plugins\", \"Plugins\"),\n        (\"08-checkpoints\", \"Checkpoints\"),\n        (\"09-advanced-features\", \"Advanced Features\"),\n        (\"resources.md\", \"Resources\"),\n    ]\n\n\ndef collect_folder_files(folder_path: Path) -> list[tuple[Path, str]]:\n    \"\"\"Collect all markdown files from a folder, README first.\"\"\"\n    files: list[tuple[Path, str]] = []\n\n    # Get README first if it exists\n    readme = folder_path / \"README.md\"\n    if readme.exists():\n        files.append((readme, \"Overview\"))\n\n    # Get all other markdown files\n    for md_file in sorted(folder_path.glob(\"*.md\")):\n        if md_file.name != \"README.md\":\n            title = md_file.stem.replace(\"-\", \" \").replace(\"_\", \" \").title()\n            files.append((md_file, title))\n\n    # Recursively get subfolders\n    for subfolder in sorted(folder_path.iterdir()):\n        if subfolder.is_dir() and not subfolder.name.startswith(\".\"):\n            subfiles = collect_folder_files(subfolder)\n            for sf, st in subfiles:\n                rel_path = sf.relative_to(folder_path)\n                if len(rel_path.parts) > 1:\n                    prefix = (\n                        rel_path.parts[0].replace(\"-\", \" \").replace(\"_\", \" \").title()\n                    )\n                    files.append((sf, f\"{prefix}: {st}\"))\n                else:\n                    files.append((sf, st))\n\n    return files\n\n\nclass ChapterCollector:\n    \"\"\"Collects and organizes chapter information in a single pass.\"\"\"\n\n    def __init__(self, root_path: Path, state: BuildState) -> None:\n        self.root_path = root_path\n        self.state = state\n\n    def collect_all_chapters(\n        self, chapter_order: list[tuple[str, str]]\n    ) -> list[ChapterInfo]:\n        \"\"\"Collect all chapters and build path mapping in one pass.\"\"\"\n        chapters: list[ChapterInfo] = []\n        chapter_num = 0\n\n        for item, display_name in chapter_order:\n            item_path = self.root_path / item\n\n            if item_path.is_file() and item_path.suffix == \".md\":\n                chapter_num += 1\n                chapter_filename = f\"chap_{chapter_num:02d}.xhtml\"\n                self.state.path_to_chapter[item] = chapter_filename\n\n                chapters.append(\n                    ChapterInfo(\n                        file_path=item_path,\n                        display_name=display_name,\n                        file_title=display_name,\n                        chapter_filename=chapter_filename,\n                    )\n                )\n\n            elif item_path.is_dir():\n                folder_chapters = self._collect_folder(\n                    item_path, item, display_name, chapter_num\n                )\n                if folder_chapters:\n                    chapter_num += 1\n                    chapters.extend(folder_chapters)\n\n        return chapters\n\n    def _collect_folder(\n        self, folder_path: Path, item: str, display_name: str, base_chapter_num: int\n    ) -> list[ChapterInfo]:\n        \"\"\"Collect chapters from a folder.\"\"\"\n        folder_files = collect_folder_files(folder_path)\n        if not folder_files:\n            return []\n\n        chapter_num = base_chapter_num + 1\n        chapters: list[ChapterInfo] = []\n\n        # Map folder itself\n        first_filename = f\"chap_{chapter_num:02d}_00.xhtml\"\n        self.state.path_to_chapter[item] = first_filename\n        self.state.path_to_chapter[item.rstrip(\"/\")] = first_filename\n\n        for i, (file_path, file_title) in enumerate(folder_files):\n            chapter_filename = f\"chap_{chapter_num:02d}_{i:02d}.xhtml\"\n            rel_path = str(file_path.relative_to(self.root_path))\n            self.state.path_to_chapter[rel_path] = chapter_filename\n\n            chapters.append(\n                ChapterInfo(\n                    file_path=file_path,\n                    display_name=display_name if i == 0 else file_title,\n                    file_title=file_title,\n                    chapter_filename=chapter_filename,\n                    is_folder_overview=(i == 0),\n                    folder_name=display_name,\n                )\n            )\n\n        return chapters\n\n\n# =============================================================================\n# Cover Image Generation\n# =============================================================================\n\n\ndef load_font(\n    font_paths: list[str], size: int, logger: logging.Logger\n) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:\n    \"\"\"Load a font from a list of paths, with fallback to default.\"\"\"\n    for font_path in font_paths:\n        try:\n            font = ImageFont.truetype(font_path, size)\n            logger.debug(f\"Loaded font: {font_path}\")\n            return font\n        except OSError:\n            continue\n\n    logger.warning(\"No custom fonts found, using default font\")\n    return ImageFont.load_default()\n\n\ndef _add_logo_to_cover(\n    cover: Image.Image, logo_path: Path, config: EPUBConfig, logger: logging.Logger\n) -> None:\n    \"\"\"Add logo to cover image.\"\"\"\n    with Image.open(logo_path) as logo:\n        target_width = config.cover_width - 60\n        scale_factor = target_width / logo.width\n        new_height = int(logo.height * scale_factor)\n        logo_scaled = logo.resize((target_width, new_height), Image.Resampling.LANCZOS)\n\n        if logo_scaled.mode == \"RGBA\":\n            logo_bg = Image.new(\"RGB\", logo_scaled.size, config.cover_bg_color)\n            logo_bg.paste(logo_scaled, mask=logo_scaled.split()[3])\n            logo_scaled = logo_bg\n        elif logo_scaled.mode != \"RGB\":\n            logo_scaled = logo_scaled.convert(\"RGB\")\n\n        logo_x = (config.cover_width - logo_scaled.width) // 2\n        logo_y = config.cover_height - logo_scaled.height - 80\n        cover.paste(logo_scaled, (logo_x, logo_y))\n        logger.debug(f\"Added logo from {logo_path}\")\n\n\ndef _draw_text_centered(\n    draw: ImageDraw.ImageDraw,\n    text: str,\n    font: ImageFont.FreeTypeFont | ImageFont.ImageFont,\n    color: tuple[int, int, int],\n    canvas_width: int,\n    y_start: int,\n    line_spacing: int,\n) -> int:\n    \"\"\"Draw centered multi-line text, return final y position.\"\"\"\n    y_offset = y_start\n    for line in text.split(\"\\n\"):\n        bbox = draw.textbbox((0, 0), line, font=font)\n        text_width = bbox[2] - bbox[0]\n        x = (canvas_width - text_width) // 2\n        draw.text((x, y_offset), line, font=font, fill=color)\n        y_offset += line_spacing\n    return y_offset\n\n\ndef create_cover_image(\n    config: EPUBConfig,\n    logger: logging.Logger,\n    title: str = \"Claude Code\\nHow-To Guide\",\n    subtitle: str = \"Complete Guide to Claude Code Features\",\n) -> bytes:\n    \"\"\"Create a cover image with proper error handling.\"\"\"\n    try:\n        cover = Image.new(\n            \"RGB\", (config.cover_width, config.cover_height), config.cover_bg_color\n        )\n        draw = ImageDraw.Draw(cover)\n\n        # Load fonts once\n        title_font = load_font(config.title_font_paths, 72, logger)\n        subtitle_font = load_font(config.subtitle_font_paths, 24, logger)\n\n        # Add logo if available\n        logo_path = config.logo_path or (config.root_path / \"claude-howto-logo.png\")\n        if logo_path.exists():\n            _add_logo_to_cover(cover, logo_path, config, logger)\n        else:\n            logger.warning(\"Logo not found, creating text-only cover\")\n\n        # Draw title\n        y_after_title = _draw_text_centered(\n            draw,\n            title,\n            title_font,\n            config.cover_title_color,\n            config.cover_width,\n            y_start=120,\n            line_spacing=90,\n        )\n\n        # Draw subtitle\n        _draw_text_centered(\n            draw,\n            subtitle,\n            subtitle_font,\n            config.cover_subtitle_color,\n            config.cover_width,\n            y_start=y_after_title + 20,\n            line_spacing=30,\n        )\n\n        buffer = BytesIO()\n        cover.save(buffer, format=\"PNG\", optimize=True)\n        logger.info(\"Cover image generated successfully\")\n        return buffer.getvalue()\n\n    except Exception as e:\n        logger.error(f\"Failed to create cover image: {e}\")\n        raise CoverGenerationError(f\"Cover generation failed: {e}\") from e\n\n\n# =============================================================================\n# HTML Generation\n# =============================================================================\n\n\ndef create_chapter_html(\n    display_name: str, file_title: str, html_content: str, is_overview: bool = False\n) -> str:\n    \"\"\"Create chapter HTML with proper escaping.\"\"\"\n    safe_display = html.escape(display_name)\n    safe_title = html.escape(file_title)\n\n    if is_overview:\n        return f\"\"\"<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\n<head>\n    <meta charset=\"utf-8\"/>\n    <title>{safe_display}</title>\n</head>\n<body>\n    <h1>{safe_display}</h1>\n    {html_content}\n</body>\n</html>\"\"\"\n    else:\n        return f\"\"\"<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\n<head>\n    <meta charset=\"utf-8\"/>\n    <title>{safe_title}</title>\n</head>\n<body>\n    <h2>{safe_title}</h2>\n    {html_content}\n</body>\n</html>\"\"\"\n\n\ndef handle_svg_image(src: str, alt: str, logger: logging.Logger) -> str:\n    \"\"\"Handle SVG images with a styled placeholder.\"\"\"\n    placeholder = f\"\"\"\n    <div class=\"svg-placeholder\" style=\"\n        border: 1px dashed #ccc;\n        padding: 1em;\n        text-align: center;\n        background: #f9f9f9;\n        border-radius: 4px;\n        margin: 1em 0;\n    \">\n        <p><em>[SVG Image: {html.escape(alt)}]</em></p>\n        <p style=\"font-size: 0.8em; color: #666;\">\n            Original: {html.escape(src)}\n        </p>\n    </div>\n    \"\"\"\n    logger.debug(f\"Replaced SVG image: {src}\")\n    return placeholder\n\n\n# =============================================================================\n# Markdown Processing\n# =============================================================================\n\n\ndef process_mermaid_blocks(\n    md_content: str, book: epub.EpubBook, state: BuildState, logger: logging.Logger\n) -> str:\n    \"\"\"Find mermaid code blocks and replace with image references.\"\"\"\n    pattern = r\"```mermaid\\n(.*?)```\"\n\n    def replace_mermaid(match: re.Match[str]) -> str:\n        mermaid_code = sanitize_mermaid(match.group(1))\n        cache_key = mermaid_code.strip()\n\n        if cache_key in state.mermaid_cache:\n            img_data, img_name = state.mermaid_cache[cache_key]\n            # Only add image to book if not already added\n            if img_name not in state.mermaid_added_to_book:\n                img_item = epub.EpubItem(\n                    uid=img_name.replace(\".\", \"_\"),\n                    file_name=f\"images/{img_name}\",\n                    media_type=\"image/png\",\n                    content=img_data,\n                )\n                book.add_item(img_item)\n                state.mermaid_added_to_book.add(img_name)\n            return f\"\\n![Diagram](images/{img_name})\\n\"\n        else:\n            # This should not happen in strict mode since we pre-fetch all diagrams\n            logger.error(\"Mermaid diagram not found in cache\")\n            raise MermaidRenderError(\"Mermaid diagram not found in cache\")\n\n    return re.sub(pattern, replace_mermaid, md_content, flags=re.DOTALL)\n\n\ndef convert_internal_links(\n    html_content: str, current_file: Path, root_path: Path, state: BuildState\n) -> str:\n    \"\"\"Convert markdown links to internal EPUB chapter links.\"\"\"\n    soup = BeautifulSoup(html_content, \"html.parser\")\n\n    for link in soup.find_all(\"a\"):\n        href = link.get(\"href\", \"\")\n        if not href or href.startswith((\"http://\", \"https://\", \"mailto:\", \"#\")):\n            continue\n\n        # Remove anchor part for path resolution\n        anchor = \"\"\n        if \"#\" in href:\n            href, anchor = href.split(\"#\", 1)\n            anchor = \"#\" + anchor\n\n        # Resolve relative path from current file's directory\n        if href:\n            resolved = (current_file.parent / href).resolve()\n            try:\n                rel_to_root = resolved.relative_to(root_path)\n            except ValueError:\n                # Link points outside the repo\n                continue\n\n            # Normalize the path for lookup\n            lookup_path = str(rel_to_root)\n\n            # Try various path forms for matching\n            paths_to_try = [\n                lookup_path,\n                lookup_path.rstrip(\"/\"),\n                lookup_path + \"/README.md\"\n                if not lookup_path.endswith(\".md\")\n                else lookup_path,\n            ]\n\n            for path in paths_to_try:\n                if path in state.path_to_chapter:\n                    link[\"href\"] = state.path_to_chapter[path] + anchor\n                    break\n\n    return str(soup)\n\n\ndef md_to_html(\n    md_content: str,\n    current_file: Path,\n    root_path: Path,\n    book: epub.EpubBook,\n    state: BuildState,\n    logger: logging.Logger,\n) -> str:\n    \"\"\"Convert markdown to HTML with proper styling.\n\n    Handles:\n    - Mermaid diagrams (rendered as PNG images)\n    - SVG images (replaced with styled placeholders)\n    - Internal links (converted to EPUB chapter references)\n    - Standard markdown features\n    \"\"\"\n    # Process mermaid blocks first (before markdown conversion)\n    md_content = process_mermaid_blocks(md_content, book, state, logger)\n\n    # Convert markdown to HTML\n    html_content = markdown.markdown(\n        md_content,\n        extensions=[\n            \"tables\",\n            \"fenced_code\",\n            \"codehilite\",\n            \"toc\",\n        ],\n    )\n\n    # Clean up any SVG references (they won't work in EPUB)\n    soup = BeautifulSoup(html_content, \"html.parser\")\n    for img in soup.find_all(\"img\"):\n        src = img.get(\"src\", \"\")\n        if src.endswith(\".svg\"):\n            alt = img.get(\"alt\", \"Image\")\n            placeholder = handle_svg_image(src, alt, logger)\n            img.replace_with(BeautifulSoup(placeholder, \"html.parser\"))\n\n    html_content = str(soup)\n\n    # Convert internal links to EPUB chapter references\n    html_content = convert_internal_links(html_content, current_file, root_path, state)\n\n    return html_content\n\n\n# =============================================================================\n# EPUB Generation\n# =============================================================================\n\n\ndef create_stylesheet() -> epub.EpubItem:\n    \"\"\"Create the EPUB stylesheet.\"\"\"\n    style = \"\"\"\n    body { font-family: Georgia, serif; line-height: 1.6; padding: 1em; }\n    h1 { color: #333; border-bottom: 2px solid #e67e22; padding-bottom: 0.3em; }\n    h2 { color: #444; margin-top: 1.5em; }\n    h3 { color: #555; }\n    code { background: #f4f4f4; padding: 0.2em 0.4em; border-radius: 3px; font-family: monospace; }\n    pre { background: #f4f4f4; padding: 1em; overflow-x: auto; border-radius: 5px; }\n    pre code { background: none; padding: 0; }\n    table { border-collapse: collapse; width: 100%; margin: 1em 0; }\n    th, td { border: 1px solid #ddd; padding: 0.5em; text-align: left; }\n    th { background: #f4f4f4; }\n    blockquote { border-left: 4px solid #e67e22; margin: 1em 0; padding-left: 1em; color: #666; }\n    a { color: #e67e22; }\n    img { max-width: 100%; height: auto; display: block; margin: 1em auto; }\n    .diagram { text-align: center; margin: 1.5em 0; }\n    .svg-placeholder { border: 1px dashed #ccc; padding: 1em; text-align: center; background: #f9f9f9; border-radius: 4px; margin: 1em 0; }\n    \"\"\"\n    return epub.EpubItem(\n        uid=\"style_nav\",\n        file_name=\"style/nav.css\",\n        media_type=\"text/css\",\n        content=style,\n    )\n\n\nasync def build_epub_async(\n    config: EPUBConfig,\n    logger: logging.Logger,\n    state: BuildState | None = None,\n) -> Path:\n    \"\"\"Build EPUB asynchronously with concurrent diagram fetching.\"\"\"\n    state = state or BuildState()\n    state.reset()  # Ensure clean state\n\n    # Validate inputs\n    validate_inputs(config, logger)\n\n    # Initialize book\n    book = epub.EpubBook()\n    book.set_identifier(config.identifier)\n    book.set_title(config.title)\n    book.set_language(config.language)\n    book.add_author(config.author)\n\n    # Add cover\n    logger.info(\"Generating cover image...\")\n    cover_data = create_cover_image(config, logger)\n    book.set_cover(\"cover.png\", cover_data)\n\n    # Add CSS\n    nav_css = create_stylesheet()\n    book.add_item(nav_css)\n\n    # Collect all chapters in single pass\n    logger.info(\"Collecting chapters...\")\n    collector = ChapterCollector(config.root_path, state)\n    chapter_infos = collector.collect_all_chapters(get_chapter_order())\n\n    # Extract and pre-fetch all Mermaid diagrams\n    logger.info(\"Extracting Mermaid diagrams...\")\n    md_files = [(ch.file_path, ch.file_title) for ch in chapter_infos]\n    all_diagrams = extract_all_mermaid_blocks(md_files, logger)\n\n    if all_diagrams:\n        renderer = MermaidRenderer(config, state, logger)\n        await renderer.render_all(all_diagrams)\n\n    # Process chapters\n    logger.info(\"Processing chapters...\")\n    chapters: list[epub.EpubHtml] = []\n    toc: list[epub.EpubHtml | tuple[epub.Section, list[epub.EpubHtml]]] = []\n\n    current_folder: str | None = None\n    current_folder_chapters: list[epub.EpubHtml] = []\n\n    for chapter_info in chapter_infos:\n        try:\n            content = chapter_info.file_path.read_text(encoding=\"utf-8\")\n        except UnicodeDecodeError as e:\n            logger.error(f\"Failed to read {chapter_info.file_path}: {e}\")\n            raise ValidationError(\n                f\"Failed to read {chapter_info.file_path}: {e}\"\n            ) from e\n\n        logger.debug(\n            f\"Processing: {chapter_info.file_path.relative_to(config.root_path)}\"\n        )\n        html_content = md_to_html(\n            content, chapter_info.file_path, config.root_path, book, state, logger\n        )\n\n        chapter = epub.EpubHtml(\n            title=chapter_info.file_title,\n            file_name=chapter_info.chapter_filename,\n            lang=\"en\",\n        )\n\n        chapter.content = create_chapter_html(\n            chapter_info.display_name,\n            chapter_info.file_title,\n            html_content,\n            is_overview=chapter_info.is_folder_overview\n            or chapter_info.folder_name is None,\n        )\n        chapter.add_item(nav_css)\n        book.add_item(chapter)\n        chapters.append(chapter)\n\n        # Build TOC structure\n        if chapter_info.folder_name is None:\n            # Single file chapter\n            if current_folder is not None:\n                # Finish previous folder\n                toc.append(\n                    (epub.Section(current_folder), current_folder_chapters.copy())\n                )\n                current_folder_chapters.clear()\n                current_folder = None\n            toc.append(chapter)\n        else:\n            # Part of a folder\n            if current_folder != chapter_info.folder_name:\n                if current_folder is not None:\n                    # Finish previous folder\n                    toc.append(\n                        (epub.Section(current_folder), current_folder_chapters.copy())\n                    )\n                    current_folder_chapters.clear()\n                current_folder = chapter_info.folder_name\n            current_folder_chapters.append(chapter)\n\n    # Handle last folder\n    if current_folder is not None and current_folder_chapters:\n        toc.append((epub.Section(current_folder), current_folder_chapters))\n\n    # Set table of contents\n    book.toc = toc\n\n    # Add navigation files\n    book.add_item(epub.EpubNcx())\n    book.add_item(epub.EpubNav())\n\n    # Set spine\n    book.spine = [\"nav\"] + chapters\n\n    # Write EPUB\n    logger.info(f\"Writing EPUB to {config.output_path}...\")\n    epub.write_epub(str(config.output_path), book, {})\n\n    logger.info(f\"EPUB created successfully: {config.output_path}\")\n    return config.output_path\n\n\ndef create_epub(root_path: Path, output_path: Path, verbose: bool = False) -> Path:\n    \"\"\"Synchronous wrapper for backward compatibility.\"\"\"\n    logger = setup_logging(verbose)\n    config = EPUBConfig(root_path=root_path, output_path=output_path)\n    return asyncio.run(build_epub_async(config, logger))\n\n\n# =============================================================================\n# CLI\n# =============================================================================\n\n\ndef main() -> int:\n    \"\"\"Main entry point with CLI argument parsing.\"\"\"\n    parser = argparse.ArgumentParser(\n        description=\"Build an EPUB from Claude How-To markdown files.\"\n    )\n    parser.add_argument(\n        \"--root\",\n        \"-r\",\n        type=Path,\n        default=None,\n        help=\"Root directory containing markdown files (default: repo root)\",\n    )\n    parser.add_argument(\n        \"--output\",\n        \"-o\",\n        type=Path,\n        default=None,\n        help=\"Output EPUB file path (default: <root>/claude-howto-guide.epub)\",\n    )\n    parser.add_argument(\n        \"--verbose\", \"-v\", action=\"store_true\", help=\"Enable verbose logging\"\n    )\n    parser.add_argument(\n        \"--timeout\",\n        type=float,\n        default=30.0,\n        help=\"Timeout for API requests in seconds (default: 30)\",\n    )\n    parser.add_argument(\n        \"--max-concurrent\",\n        type=int,\n        default=10,\n        help=\"Maximum concurrent API requests (default: 10)\",\n    )\n\n    args = parser.parse_args()\n\n    # Determine root path\n    root = args.root\n    if root is None:\n        # Default to parent of scripts directory (repo root)\n        root = Path(__file__).parent.parent\n\n    root = root.resolve()\n    output = args.output or (root / \"claude-howto-guide.epub\")\n    output = output.resolve()\n\n    logger = setup_logging(args.verbose)\n    config = EPUBConfig(\n        root_path=root,\n        output_path=output,\n        request_timeout=args.timeout,\n        max_concurrent_requests=args.max_concurrent,\n    )\n\n    try:\n        result = asyncio.run(build_epub_async(config, logger))\n        print(f\"Successfully created: {result}\")\n        return 0\n    except EPUBBuildError as e:\n        logger.error(f\"Build failed: {e}\")\n        return 1\n    except KeyboardInterrupt:\n        logger.warning(\"Build interrupted by user\")\n        return 130\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"
  },
  {
    "path": "scripts/pyproject.toml",
    "content": "[project]\nname = \"claude-howto\"\nversion = \"1.0.0\"\ndescription = \"Claude Code How-To Guide with EPUB builder\"\nreadme = \"README.md\"\nlicense = \"MIT\"\nrequires-python = \">=3.10\"\ndependencies = [\n    \"ebooklib\",\n    \"markdown\",\n    \"beautifulsoup4\",\n    \"httpx\",\n    \"pillow\",\n    \"tenacity\",\n]\n\n[project.optional-dependencies]\ndev = [\n    \"pytest>=7.0\",\n    \"pytest-asyncio>=0.21\",\n]\n\n[tool.pytest.ini_options]\ntestpaths = [\"scripts/tests\"]\nasyncio_mode = \"auto\"\nasyncio_default_fixture_loop_scope = \"function\"\npython_files = [\"test_*.py\"]\npython_functions = [\"test_*\"]\naddopts = \"-v\"\n\n[build-system]\nrequires = [\"setuptools>=61.0\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.setuptools.packages.find]\nwhere = [\"scripts\"]\ninclude = [\"build_epub\"]\nexclude = [\"tests\", \"tests.*\"]\n\n# =============================================================================\n# Ruff Configuration\n# =============================================================================\n[tool.ruff]\ntarget-version = \"py310\"\nline-length = 88\ninclude = [\"scripts/**/*.py\"]\nexclude = [\n    \".git\",\n    \".venv\",\n    \"__pycache__\",\n    \".pytest_cache\",\n    \"*.egg-info\",\n]\n\n[tool.ruff.lint]\nselect = [\n    \"E\",      # pycodestyle errors\n    \"W\",      # pycodestyle warnings\n    \"F\",      # Pyflakes\n    \"I\",      # isort (import sorting)\n    \"B\",      # flake8-bugbear\n    \"C4\",     # flake8-comprehensions\n    \"UP\",     # pyupgrade\n    \"SIM\",    # flake8-simplify\n    \"TCH\",    # flake8-type-checking\n    \"RUF\",    # Ruff-specific rules\n    \"PTH\",    # flake8-use-pathlib\n    \"PL\",     # Pylint\n    \"PERF\",   # Perflint\n]\nignore = [\n    \"E501\",     # Line too long (handled by formatter)\n    \"PLR0913\",  # Too many arguments\n    \"PLR2004\",  # Magic value comparison\n    \"PLR0915\",  # Too many statements\n    \"PERF203\",  # try-except in loop (acceptable for error handling)\n    \"PERF403\",  # dict comprehension (readability preference)\n    \"TC003\",    # Type-checking imports (not critical)\n    \"PLC0415\",  # Import not at top level (acceptable for lazy imports)\n    \"RUF005\",   # Collection concatenation (readability preference)\n]\nfixable = [\"ALL\"]\nunfixable = []\n\n[tool.ruff.lint.isort]\nknown-first-party = [\"build_epub\"]\nforce-single-line = false\ncombine-as-imports = true\n\n[tool.ruff.lint.per-file-ignores]\n\"scripts/tests/*.py\" = [\"S101\", \"PLR2004\"]\n\n[tool.ruff.format]\nquote-style = \"double\"\nindent-style = \"space\"\nskip-magic-trailing-comma = false\ndocstring-code-format = true\n\n# =============================================================================\n# Bandit Configuration\n# =============================================================================\n[tool.bandit]\ntargets = [\"scripts\"]\nexclude_dirs = [\"scripts/tests\", \".venv\", \"__pycache__\"]\nskips = [\"B101\", \"B113\"]  # B113: httpx timeout false positive (timeout is set)\n"
  },
  {
    "path": "scripts/requirements-dev.txt",
    "content": "# Development dependencies (includes core dependencies)\n-r requirements.txt\n\n# Testing\npytest>=7.0\npytest-asyncio>=0.21\npytest-cov>=4.0.0\n\n# Code Quality\npre-commit>=3.6.0\nruff>=0.8.0\nbandit[toml]>=1.7.7\n"
  },
  {
    "path": "scripts/requirements.txt",
    "content": "# Core dependencies for build_epub.py\nebooklib\nmarkdown\nbeautifulsoup4\nhttpx\npillow\ntenacity\n"
  },
  {
    "path": "scripts/tests/__init__.py",
    "content": "# Tests for build_epub module\n"
  },
  {
    "path": "scripts/tests/conftest.py",
    "content": "\"\"\"Pytest configuration and shared fixtures for EPUB builder tests.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\n# Add parent directory to path for imports\nsys.path.insert(0, str(Path(__file__).parent.parent))\n\nfrom build_epub import BuildState, EPUBConfig, setup_logging\n\n\n@pytest.fixture\ndef tmp_project(tmp_path: Path) -> Path:\n    \"\"\"Create a minimal project structure for testing.\"\"\"\n    # Create root markdown file\n    readme = tmp_path / \"README.md\"\n    readme.write_text(\"# Test Project\\n\\nThis is a test.\")\n\n    # Create a chapter directory\n    chapter_dir = tmp_path / \"01-test-chapter\"\n    chapter_dir.mkdir()\n    (chapter_dir / \"README.md\").write_text(\"# Chapter Overview\\n\\nOverview content.\")\n    (chapter_dir / \"section.md\").write_text(\"# Section\\n\\nSection content.\")\n\n    # Create a proper PNG logo using PIL\n    from PIL import Image as PILImage\n\n    logo_path = tmp_path / \"claude-howto-logo.png\"\n    img = PILImage.new(\"RGB\", (100, 100), color=(26, 26, 46))\n    img.save(logo_path, \"PNG\")\n\n    return tmp_path\n\n\n@pytest.fixture\ndef config(tmp_project: Path) -> EPUBConfig:\n    \"\"\"Create a test configuration.\"\"\"\n    return EPUBConfig(\n        root_path=tmp_project,\n        output_path=tmp_project / \"test.epub\",\n    )\n\n\n@pytest.fixture\ndef state() -> BuildState:\n    \"\"\"Create a fresh build state.\"\"\"\n    return BuildState()\n\n\n@pytest.fixture\ndef logger() -> logging.Logger:\n    \"\"\"Create a test logger.\"\"\"\n    return setup_logging(verbose=False)\n"
  },
  {
    "path": "scripts/tests/test_build_epub.py",
    "content": "\"\"\"Tests for the EPUB builder module.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nfrom pathlib import Path\nfrom unittest.mock import patch\n\nimport pytest\n\n# Fixtures are imported from conftest.py automatically by pytest\n# Import from parent directory (handled by conftest.py sys.path)\nfrom build_epub import (\n    BuildState,\n    ChapterCollector,\n    EPUBConfig,\n    ValidationError,\n    create_chapter_html,\n    extract_all_mermaid_blocks,\n    get_chapter_order,\n    sanitize_mermaid,\n    setup_logging,\n    validate_inputs,\n)\n\n# =============================================================================\n# BuildState Tests\n# =============================================================================\n\n\nclass TestBuildState:\n    \"\"\"Tests for BuildState dataclass.\"\"\"\n\n    def test_initial_state(self, state: BuildState) -> None:\n        \"\"\"Test that initial state is empty.\"\"\"\n        assert state.mermaid_counter == 0\n        assert len(state.mermaid_cache) == 0\n        assert len(state.mermaid_added_to_book) == 0\n        assert len(state.path_to_chapter) == 0\n\n    def test_state_modification(self, state: BuildState) -> None:\n        \"\"\"Test that state can be modified.\"\"\"\n        state.mermaid_counter = 5\n        state.mermaid_cache[\"key\"] = (b\"data\", \"file.png\")\n        state.mermaid_added_to_book.add(\"file.png\")\n        state.path_to_chapter[\"README.md\"] = \"chap_01.xhtml\"\n\n        assert state.mermaid_counter == 5\n        assert state.mermaid_cache[\"key\"] == (b\"data\", \"file.png\")\n        assert \"file.png\" in state.mermaid_added_to_book\n        assert state.path_to_chapter[\"README.md\"] == \"chap_01.xhtml\"\n\n    def test_reset(self, state: BuildState) -> None:\n        \"\"\"Test that reset clears all state.\"\"\"\n        state.mermaid_counter = 5\n        state.mermaid_cache[\"key\"] = (b\"data\", \"file.png\")\n        state.mermaid_added_to_book.add(\"file.png\")\n        state.path_to_chapter[\"README.md\"] = \"chap_01.xhtml\"\n\n        state.reset()\n\n        assert state.mermaid_counter == 0\n        assert len(state.mermaid_cache) == 0\n        assert len(state.mermaid_added_to_book) == 0\n        assert len(state.path_to_chapter) == 0\n\n\n# =============================================================================\n# EPUBConfig Tests\n# =============================================================================\n\n\nclass TestEPUBConfig:\n    \"\"\"Tests for EPUBConfig dataclass.\"\"\"\n\n    def test_required_fields(self, tmp_path: Path) -> None:\n        \"\"\"Test that required fields must be provided.\"\"\"\n        config = EPUBConfig(\n            root_path=tmp_path,\n            output_path=tmp_path / \"out.epub\",\n        )\n        assert config.root_path == tmp_path\n        assert config.output_path == tmp_path / \"out.epub\"\n\n    def test_default_values(self, tmp_path: Path) -> None:\n        \"\"\"Test that default values are set correctly.\"\"\"\n        config = EPUBConfig(\n            root_path=tmp_path,\n            output_path=tmp_path / \"out.epub\",\n        )\n        assert config.identifier == \"claude-howto-guide\"\n        assert config.title == \"Claude Code How-To Guide\"\n        assert config.language == \"en\"\n        assert config.author == \"Claude Code Community\"\n        assert config.request_timeout == 30.0\n        assert config.max_concurrent_requests == 10\n        assert config.max_retries == 3\n\n    def test_custom_values(self, tmp_path: Path) -> None:\n        \"\"\"Test that custom values override defaults.\"\"\"\n        config = EPUBConfig(\n            root_path=tmp_path,\n            output_path=tmp_path / \"out.epub\",\n            title=\"Custom Title\",\n            request_timeout=60.0,\n            max_concurrent_requests=5,\n        )\n        assert config.title == \"Custom Title\"\n        assert config.request_timeout == 60.0\n        assert config.max_concurrent_requests == 5\n\n\n# =============================================================================\n# Validation Tests\n# =============================================================================\n\n\nclass TestValidation:\n    \"\"\"Tests for input validation.\"\"\"\n\n    def test_valid_inputs(self, config: EPUBConfig, logger: logging.Logger) -> None:\n        \"\"\"Test that valid inputs pass validation.\"\"\"\n        # Should not raise\n        validate_inputs(config, logger)\n\n    def test_missing_root_path(self, tmp_path: Path, logger: logging.Logger) -> None:\n        \"\"\"Test that missing root path raises ValidationError.\"\"\"\n        config = EPUBConfig(\n            root_path=tmp_path / \"nonexistent\",\n            output_path=tmp_path / \"out.epub\",\n        )\n        with pytest.raises(ValidationError, match=\"Root path does not exist\"):\n            validate_inputs(config, logger)\n\n    def test_root_path_is_file(self, tmp_path: Path, logger: logging.Logger) -> None:\n        \"\"\"Test that file as root path raises ValidationError.\"\"\"\n        file_path = tmp_path / \"file.txt\"\n        file_path.write_text(\"content\")\n        config = EPUBConfig(\n            root_path=file_path,\n            output_path=tmp_path / \"out.epub\",\n        )\n        with pytest.raises(ValidationError, match=\"Root path is not a directory\"):\n            validate_inputs(config, logger)\n\n    def test_no_markdown_files(self, tmp_path: Path, logger: logging.Logger) -> None:\n        \"\"\"Test that directory with no markdown files raises ValidationError.\"\"\"\n        empty_dir = tmp_path / \"empty\"\n        empty_dir.mkdir()\n        config = EPUBConfig(\n            root_path=empty_dir,\n            output_path=tmp_path / \"out.epub\",\n        )\n        with pytest.raises(ValidationError, match=\"No markdown files found\"):\n            validate_inputs(config, logger)\n\n    def test_missing_output_directory(\n        self, tmp_project: Path, logger: logging.Logger\n    ) -> None:\n        \"\"\"Test that missing output directory raises ValidationError.\"\"\"\n        config = EPUBConfig(\n            root_path=tmp_project,\n            output_path=tmp_project / \"nonexistent\" / \"out.epub\",\n        )\n        with pytest.raises(ValidationError, match=\"Output directory does not exist\"):\n            validate_inputs(config, logger)\n\n\n# =============================================================================\n# Mermaid Processing Tests\n# =============================================================================\n\n\nclass TestMermaidProcessing:\n    \"\"\"Tests for Mermaid diagram processing.\"\"\"\n\n    def test_sanitize_mermaid_numbered_list(self) -> None:\n        \"\"\"Test that numbered lists in brackets are escaped.\"\"\"\n        input_code = 'A[\"1. First item\"] --> B[\"2. Second item\"]'\n        expected = 'A[\"1\\\\. First item\"] --> B[\"2\\\\. Second item\"]'\n        assert sanitize_mermaid(input_code) == expected\n\n    def test_sanitize_mermaid_no_change(self) -> None:\n        \"\"\"Test that code without numbered lists is unchanged.\"\"\"\n        input_code = \"A --> B --> C\"\n        assert sanitize_mermaid(input_code) == input_code\n\n    def test_extract_mermaid_blocks(\n        self, tmp_path: Path, logger: logging.Logger\n    ) -> None:\n        \"\"\"Test extraction of Mermaid blocks from files.\"\"\"\n        # Create test file with mermaid blocks\n        md_file = tmp_path / \"test.md\"\n        md_file.write_text(\n            \"\"\"# Test\n\n```mermaid\ngraph TD\n    A --> B\n```\n\nSome text\n\n```mermaid\ngraph LR\n    C --> D\n```\n\"\"\"\n        )\n\n        diagrams = extract_all_mermaid_blocks([(md_file, \"Test\")], logger)\n\n        assert len(diagrams) == 2\n        assert diagrams[0][0] == 1  # First diagram index\n        assert diagrams[1][0] == 2  # Second diagram index\n        assert \"A --> B\" in diagrams[0][1]\n        assert \"C --> D\" in diagrams[1][1]\n\n    def test_extract_mermaid_blocks_deduplication(\n        self, tmp_path: Path, logger: logging.Logger\n    ) -> None:\n        \"\"\"Test that duplicate Mermaid blocks are deduplicated.\"\"\"\n        md_file1 = tmp_path / \"test1.md\"\n        md_file2 = tmp_path / \"test2.md\"\n\n        same_diagram = \"\"\"```mermaid\ngraph TD\n    A --> B\n```\"\"\"\n\n        md_file1.write_text(f\"# File 1\\n\\n{same_diagram}\")\n        md_file2.write_text(f\"# File 2\\n\\n{same_diagram}\")\n\n        diagrams = extract_all_mermaid_blocks(\n            [(md_file1, \"Test1\"), (md_file2, \"Test2\")], logger\n        )\n\n        # Should only have one diagram since they're identical\n        assert len(diagrams) == 1\n\n\n# =============================================================================\n# Chapter Collection Tests\n# =============================================================================\n\n\nclass TestChapterCollector:\n    \"\"\"Tests for ChapterCollector class.\"\"\"\n\n    def test_collect_single_file(self, tmp_path: Path, state: BuildState) -> None:\n        \"\"\"Test collecting a single markdown file.\"\"\"\n        readme = tmp_path / \"README.md\"\n        readme.write_text(\"# Test\")\n\n        collector = ChapterCollector(tmp_path, state)\n        chapters = collector.collect_all_chapters([(\"README.md\", \"Introduction\")])\n\n        assert len(chapters) == 1\n        assert chapters[0].file_path == readme\n        assert chapters[0].display_name == \"Introduction\"\n        assert chapters[0].chapter_filename == \"chap_01.xhtml\"\n        assert state.path_to_chapter[\"README.md\"] == \"chap_01.xhtml\"\n\n    def test_collect_folder(self, tmp_project: Path, state: BuildState) -> None:\n        \"\"\"Test collecting a folder with multiple files.\"\"\"\n        collector = ChapterCollector(tmp_project, state)\n        chapters = collector.collect_all_chapters([(\"01-test-chapter\", \"Test Chapter\")])\n\n        assert len(chapters) == 2  # README.md and section.md\n        assert chapters[0].is_folder_overview is True\n        assert chapters[0].folder_name == \"Test Chapter\"\n        assert chapters[1].is_folder_overview is False\n\n    def test_path_mapping(self, tmp_project: Path, state: BuildState) -> None:\n        \"\"\"Test that path mapping is built correctly.\"\"\"\n        collector = ChapterCollector(tmp_project, state)\n        collector.collect_all_chapters(\n            [\n                (\"README.md\", \"Introduction\"),\n                (\"01-test-chapter\", \"Test Chapter\"),\n            ]\n        )\n\n        assert \"README.md\" in state.path_to_chapter\n        assert \"01-test-chapter\" in state.path_to_chapter\n        assert \"01-test-chapter/README.md\" in state.path_to_chapter\n\n\n# =============================================================================\n# HTML Generation Tests\n# =============================================================================\n\n\nclass TestHTMLGeneration:\n    \"\"\"Tests for HTML generation.\"\"\"\n\n    def test_create_chapter_html_overview(self) -> None:\n        \"\"\"Test creating HTML for an overview chapter.\"\"\"\n        html = create_chapter_html(\n            display_name=\"Introduction\",\n            file_title=\"Introduction\",\n            html_content=\"<p>Content</p>\",\n            is_overview=True,\n        )\n\n        assert \"<!DOCTYPE html>\" in html\n        assert '<html xmlns=\"http://www.w3.org/1999/xhtml\"' in html\n        assert \"<h1>Introduction</h1>\" in html\n        assert \"<p>Content</p>\" in html\n\n    def test_create_chapter_html_section(self) -> None:\n        \"\"\"Test creating HTML for a section chapter.\"\"\"\n        html = create_chapter_html(\n            display_name=\"Chapter\",\n            file_title=\"Section\",\n            html_content=\"<p>Content</p>\",\n            is_overview=False,\n        )\n\n        assert \"<h2>Section</h2>\" in html\n        assert \"<h1>\" not in html\n\n    def test_html_escaping(self) -> None:\n        \"\"\"Test that HTML special characters are escaped.\"\"\"\n        html = create_chapter_html(\n            display_name=\"<script>alert('xss')</script>\",\n            file_title=\"Test & Title\",\n            html_content=\"<p>Content</p>\",\n            is_overview=True,\n        )\n\n        assert \"&lt;script&gt;\" in html\n        # Note: Python's html.escape uses &#x27; for single quotes\n        assert \"<script>alert\" not in html\n\n\n# =============================================================================\n# Chapter Order Tests\n# =============================================================================\n\n\nclass TestChapterOrder:\n    \"\"\"Tests for chapter ordering.\"\"\"\n\n    def test_get_chapter_order(self) -> None:\n        \"\"\"Test that chapter order is defined correctly.\"\"\"\n        order = get_chapter_order()\n\n        assert len(order) > 0\n        assert order[0] == (\"README.md\", \"Introduction\")\n\n        # Check that all expected chapters are present\n        chapter_names = [name for name, _ in order]\n        assert \"01-slash-commands\" in chapter_names\n        assert \"02-memory\" in chapter_names\n        assert \"resources.md\" in chapter_names\n\n\n# =============================================================================\n# Logging Tests\n# =============================================================================\n\n\nclass TestLogging:\n    \"\"\"Tests for logging setup.\"\"\"\n\n    def test_setup_logging_default(self) -> None:\n        \"\"\"Test default logging setup.\"\"\"\n        logger = setup_logging(verbose=False)\n        assert logger.name == \"epub_builder\"\n\n    def test_setup_logging_verbose(self) -> None:\n        \"\"\"Test verbose logging setup.\"\"\"\n        logger = setup_logging(verbose=True)\n        assert logger.name == \"epub_builder\"\n\n\n# =============================================================================\n# Integration Tests\n# =============================================================================\n\n\nclass TestIntegration:\n    \"\"\"Integration tests for the full build process.\"\"\"\n\n    @pytest.mark.asyncio\n    async def test_build_without_mermaid(\n        self, tmp_project: Path, logger: logging.Logger\n    ) -> None:\n        \"\"\"Test building an EPUB without Mermaid diagrams.\"\"\"\n        from build_epub import build_epub_async\n\n        config = EPUBConfig(\n            root_path=tmp_project,\n            output_path=tmp_project / \"test.epub\",\n        )\n\n        # Override chapter order for minimal test\n        with patch(\"build_epub.get_chapter_order\") as mock_order:\n            mock_order.return_value = [(\"README.md\", \"Introduction\")]\n\n            result = await build_epub_async(config, logger)\n\n            assert result.exists()\n            assert result.suffix == \".epub\"\n\n\n# =============================================================================\n# Run tests\n# =============================================================================\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__, \"-v\"])\n"
  }
]