refactor(ci): shift quality checks to pre-commit, CI as 2nd pass (#34)

* refactor(ci): shift quality checks to pre-commit, CI as 2nd pass

- Remove ci.yml (lint, security, pytest were only for EPUB scripts)
- Move EPUB build to pre-commit local hook (runs on .md changes)
- Add check_cross_references.py, check_mermaid.py, check_links.py scripts
- Add markdown-lint, cross-references, mermaid-syntax, link-check as
  pre-commit hooks — mirrors all 4 CI doc-check jobs locally
- Remove spell check job from docs-check.yml (breaks on translations)
- Refactor docs-check.yml to reuse scripts/ instead of inline Python
- Add .markdownlint.json config shared by pre-commit and CI
- Update CONTRIBUTING.md with required dependencies and hook table

* fix(ci): resolve all CI check failures in docs-check workflow

- fix(check_cross_references): skip code blocks and inline code spans
  to avoid false positives from documentation examples; fix emoji
  heading anchor generation (rstrip not strip); add blog-posts,
  openspec, prompts, .agents to IGNORE_DIRS; ignore README.backup.md
- fix(check_links): strip trailing Markdown punctuation from captured
  URLs; add wikipedia, api.github.com to SKIP_DOMAINS; add placeholder
  URL patterns to SKIP_URL_PATTERNS; add .agents/.claude to IGNORE_DIRS
- fix(check_mermaid): add --no-sandbox puppeteer config support via
  MERMAID_PUPPETEER_NO_SANDBOX env var for GitHub Actions Linux runners
- fix(docs-check.yml): pass MERMAID_PUPPETEER_NO_SANDBOX=true to mermaid job
- fix(content): repair broken anchors in README.md, 09-advanced-features;
  fix #plugins -> #claude-code-plugins in claude_concepts_guide.md;
  remove non-existent ./docs/performance.md placeholder links; fix
  dependabot alerts URL in SECURITY_REPORTING.md; update auto-mode URL
  in resources.md; use placeholder pattern for 07-plugins example URL
- remove README.backup.md (stale file)

* fix(check-scripts): fix strip_code_blocks regex and URL fragment handling

- fix regex in strip_code_blocks to avoid conflicting MULTILINE+DOTALL
  flags that could fail to strip indented code fences; use DOTALL only
- strip URL fragments (#section) before dispatching link checks to avoid
  false-positive 404s on valid URLs with anchor fragments

* fix(check-scripts): fix anchor stripping, cross-ref enforcement, and mermaid temp file cleanup

- heading_to_anchor: use .strip("-") instead of .rstrip("-") to also strip leading hyphens
  produced by emoji-prefixed headings, preventing false-positive anchor errors
- check_cross_references: always exit with main()'s return code — filesystem checks
  should block pre-commit unconditionally, not silently pass on errors
- check_mermaid: wrap file-processing loop in try/finally so the puppeteer config
  temp file is cleaned up even if an unexpected exception (e.g. UnicodeDecodeError) occurs
- docs-check.yml: remove now-unused CROSS_REF_STRICT env var

* fix(scripts): fix anchor stripping and mermaid output path

- Replace .strip('-') with .rstrip('-') in heading_to_anchor() so leading
  hyphens from emoji-prefixed headings are preserved, matching GitHub's
  anchor generation behaviour.
- Use Path.with_suffix('.svg') in check_mermaid.py instead of
  str.replace('.mmd', '.svg') to avoid replacing all occurrences of .mmd
  in the full temp path.
This commit is contained in:
Luong NGUYEN
2026-04-02 02:20:45 +02:00
committed by GitHub
parent 0ca8c37c81
commit 6d1e0ae4af
19 changed files with 887 additions and 1367 deletions
+1 -1
View File
@@ -30,7 +30,7 @@ This is the preferred method for reporting security vulnerabilities.
If you discover a vulnerability in a dependency: If you discover a vulnerability in a dependency:
1. Go to: https://github.com/luongnv89/claude-howto/security/dependabot/alerts 1. Go to: https://github.com/luongnv89/claude-howto/security/advisories
2. Review the alert 2. Review the alert
3. Create a pull request with the fix 3. Create a pull request with the fix
4. Tag with `security` label 4. Tag with `security` label
-130
View File
@@ -1,130 +0,0 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
# Cancel in-progress runs for the same branch
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
name: Lint & Format
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Set up Python
run: uv python install 3.11
- name: Create venv and install Ruff
run: |
uv venv
uv pip install ruff
- name: Ruff Format Check
run: uv run ruff format --check scripts/
- name: Ruff Lint Check
run: uv run ruff check scripts/
security:
name: Security Scan
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Set up Python
run: uv python install 3.11
- name: Create venv and install Bandit
run: |
uv venv
uv pip install "bandit[toml]"
- name: Run Bandit Security Scan
run: uv run bandit -c scripts/pyproject.toml -r scripts/ --exclude scripts/tests/
test:
name: Unit Tests (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.10', '3.11', '3.12']
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Set up Python ${{ matrix.python-version }}
run: uv python install ${{ matrix.python-version }}
- name: Create venv and install dependencies
run: |
uv venv
uv pip install -r scripts/requirements-dev.txt
- name: Run pytest with coverage
run: uv run pytest scripts/tests/ -v --tb=short --cov=scripts --cov-report=xml --cov-report=term-missing
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
files: ./coverage.xml
flags: unittests
name: codecov-python-${{ matrix.python-version }}
fail_ci_if_error: false
build:
name: Build EPUB
runs-on: ubuntu-latest
needs: [lint, security, test]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Set up Python
run: uv python install 3.11
- name: Create venv and install dependencies
run: |
uv venv
uv pip install -r scripts/requirements-dev.txt
- name: Build EPUB
run: uv run scripts/build_epub.py
- name: Verify EPUB Created
run: |
if [ -f claude-howto-guide.epub ]; then
echo "EPUB built successfully"
ls -lh claude-howto-guide.epub
else
echo "EPUB file not found!"
exit 1
fi
- name: Upload EPUB Artifact
uses: actions/upload-artifact@v4
with:
name: claude-howto-guide-epub
path: claude-howto-guide.epub
retention-days: 7
+38 -263
View File
@@ -6,16 +6,18 @@ on:
paths: paths:
- '**.md' - '**.md'
- '.github/workflows/docs-check.yml' - '.github/workflows/docs-check.yml'
- '.cspell.json'
- '.github/markdown-link-check-config.json' - '.github/markdown-link-check-config.json'
- '.markdownlint.json'
- 'scripts/check_*.py'
pull_request: pull_request:
branches: [main] branches: [main]
paths: paths:
- '**.md' - '**.md'
- 'CONTRIBUTING.md' - 'CONTRIBUTING.md'
- 'LICENSE' - 'LICENSE'
- '.cspell.json'
- '.github/markdown-link-check-config.json' - '.github/markdown-link-check-config.json'
- '.markdownlint.json'
- 'scripts/check_*.py'
# Cancel in-progress runs for the same branch # Cancel in-progress runs for the same branch
concurrency: concurrency:
@@ -39,8 +41,7 @@ jobs:
run: npm install -g markdownlint-cli run: npm install -g markdownlint-cli
- name: Run Markdown Linter - name: Run Markdown Linter
run: markdownlint '**/*.md' --ignore node_modules --ignore .venv run: markdownlint '**/*.md' --ignore node_modules --ignore .venv --config .markdownlint.json
continue-on-error: true
link-check: link-check:
name: Check Links name: Check Links
@@ -49,33 +50,43 @@ jobs:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Check markdown links - name: Setup Python
uses: gaurav-nelson/github-action-markdown-link-check@v1 uses: actions/setup-python@v4
with: with:
use-quiet-mode: 'yes' python-version: '3.11'
use-verbose-mode: 'no'
config-file: '.github/markdown-link-check-config.json'
spelling: - name: Run link check
name: Spell Check run: python scripts/check_links.py
env:
LINK_CHECK_STRICT: "1"
mermaid:
name: Mermaid Syntax
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Run cSpell - name: Setup Node.js
uses: streetsidesoftware/cspell-action@v6 uses: actions/setup-node@v4
with: with:
files: | node-version: '18'
**/*.md
**/*.json
**/*.yml
**/*.yaml
incremental: 'no'
config: '.cspell.json'
frontmatter: - name: Install mermaid CLI
name: YAML Frontmatter Validation run: npm install -g @mermaid-js/mermaid-cli
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Validate Mermaid diagrams
run: python scripts/check_mermaid.py
env:
MERMAID_PUPPETEER_NO_SANDBOX: "true"
cross-references:
name: Cross-reference Check
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
@@ -86,245 +97,12 @@ jobs:
with: with:
python-version: '3.11' python-version: '3.11'
- name: Install PyYAML - name: Validate cross-references
run: pip install pyyaml run: python scripts/check_cross_references.py
- name: Validate YAML Frontmatter
run: |
python3 << 'EOF'
import os
import yaml
import re
from pathlib import Path
errors = []
# Check all markdown files in Claude sections
md_files = list(Path('.').glob('**/README.md')) + list(Path('.').glob('01-*/**/*.md'))
for file_path in md_files:
if '.venv' in str(file_path) or 'node_modules' in str(file_path):
continue
with open(file_path, 'r') as f:
content = f.read()
# Check for YAML frontmatter in skill/agent templates
if 'SKILL.md' in str(file_path) or any(x in str(file_path) for x in ['agent', 'template']):
if content.startswith('---'):
try:
# Extract frontmatter
parts = content.split('---', 2)
if len(parts) >= 3:
yaml.safe_load(parts[1])
except yaml.YAMLError as e:
errors.append(f"{file_path}: Invalid YAML frontmatter - {e}")
else:
if 'skill' in str(file_path).lower():
print(f"⚠ {file_path}: Consider adding YAML frontmatter")
if errors:
for error in errors:
print(f"❌ {error}")
exit(1)
else:
print("✅ All YAML frontmatter is valid")
EOF
structure:
name: Documentation Structure
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Validate Documentation Structure
run: |
python3 << 'EOF'
import os
from pathlib import Path
import re
errors = []
warnings = []
# Check that all numbered directories have README.md
for i in range(1, 11):
dir_path = Path(f"{i:02d}-*")
matches = list(dir_path.parent.glob(str(dir_path)))
if matches:
for match in matches:
if (match / "README.md").exists():
print(f"✅ {match}/README.md found")
else:
errors.append(f"{match}: Missing README.md")
# Check README.md has required sections
readme_path = Path("README.md")
if readme_path.exists():
with open(readme_path) as f:
content = f.read()
required_sections = [
"## Table of Contents",
"## Contributing",
"## License",
]
for section in required_sections:
if section not in content:
errors.append(f"README.md: Missing '{section}' section")
else:
print(f"✅ README.md has '{section}' section")
# Check for broken relative links
md_files = list(Path(".").rglob("*.md"))
for file_path in md_files:
if ".venv" in str(file_path) or "node_modules" in str(file_path):
continue
with open(file_path) as f:
content = f.read()
# Find markdown links to local files
local_links = re.findall(r'\[([^\]]+)\]\(([^)]+\.md)\)', content)
for link_text, link_path in local_links:
# Skip anchor-only links
if link_path.startswith("#"):
continue
resolved_path = (file_path.parent / link_path).resolve()
if not resolved_path.exists():
warnings.append(f"{file_path}: Broken link to '{link_path}'")
if errors:
print("\n❌ Validation Errors:")
for error in errors:
print(f" - {error}")
exit(1)
if warnings:
print("\n⚠ Warnings:")
for warning in warnings:
print(f" - {warning}")
print("\n✅ Documentation structure is valid")
EOF
metadata:
name: File Metadata Checks
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for common issues
run: |
set +e # Don't exit on first error
echo "📋 Checking for documentation issues..."
# Check for files over 100KB
echo "Checking file sizes..."
large_files=$(find . -name "*.md" -size +100k | grep -v ".venv" | grep -v "node_modules")
if [ ! -z "$large_files" ]; then
echo "⚠ Large markdown files found (>100KB):"
echo "$large_files"
fi
# Check for TODO markers (might indicate incomplete content)
echo "Checking for TODO markers in main docs..."
todos=$(grep -r "TODO\|FIXME" --include="*.md" . --exclude-dir=.venv --exclude-dir=node_modules --exclude-dir=.git | grep -v ".github" | head -10)
if [ ! -z "$todos" ]; then
echo "⚠ Found TODO/FIXME markers:"
echo "$todos"
fi
# Check for consistent heading structure
echo "Checking heading consistency in key files..."
for file in README.md CONTRIBUTING.md; do
if [ -f "$file" ]; then
heading_count=$(grep -c "^##" "$file")
echo "✅ $file has $heading_count main sections"
fi
done
# Check that LICENSE file exists
if [ -f "LICENSE" ]; then
echo "✅ LICENSE file exists"
else
echo "❌ LICENSE file not found"
exit 1
fi
consistency:
name: Content Consistency
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Check Content Consistency
run: |
python3 << 'EOF'
import re
from pathlib import Path
errors = []
# Check that all numbered sections are referenced in README
readme_path = Path("README.md")
with open(readme_path) as f:
readme_content = f.read()
# Look for numbered directories
for i in range(1, 11):
dir_pattern = f"{i:02d}-"
dirs = list(Path(".").glob(f"{dir_pattern}*"))
if dirs:
for dir_path in dirs:
if dir_path.is_dir():
# Check if referenced in README
dir_name = dir_path.name
if dir_name not in readme_content:
errors.append(f"README.md: Directory '{dir_name}' not mentioned")
else:
print(f"✅ '{dir_name}' is referenced in README")
# Check for consistent code fence formatting
md_files = [f for f in Path(".").rglob("*.md") if ".venv" not in str(f)]
for file_path in md_files:
with open(file_path) as f:
content = f.read()
# Count code fence types
backtick_fences = len(re.findall(r'```', content))
if backtick_fences % 2 != 0:
errors.append(f"{file_path}: Unmatched code fences (backticks)")
if errors:
print("\n❌ Consistency Errors:")
for error in errors:
print(f" - {error}")
exit(1)
print("\n✅ Content is consistent")
EOF
summary: summary:
name: Summary name: Summary
needs: [markdown-lint, link-check, spelling, frontmatter, structure, metadata, consistency] needs: [markdown-lint, link-check, mermaid, cross-references]
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: always() if: always()
steps: steps:
@@ -332,11 +110,8 @@ jobs:
run: | run: |
if [ "${{ needs.markdown-lint.result }}" = "failure" ] || \ if [ "${{ needs.markdown-lint.result }}" = "failure" ] || \
[ "${{ needs.link-check.result }}" = "failure" ] || \ [ "${{ needs.link-check.result }}" = "failure" ] || \
[ "${{ needs.spelling.result }}" = "failure" ] || \ [ "${{ needs.mermaid.result }}" = "failure" ] || \
[ "${{ needs.frontmatter.result }}" = "failure" ] || \ [ "${{ needs.cross-references.result }}" = "failure" ]; then
[ "${{ needs.structure.result }}" = "failure" ] || \
[ "${{ needs.metadata.result }}" = "failure" ] || \
[ "${{ needs.consistency.result }}" = "failure" ]; then
echo "❌ Some documentation checks failed" echo "❌ Some documentation checks failed"
exit 1 exit 1
else else
+13
View File
@@ -0,0 +1,13 @@
{
"default": false,
"MD009": true,
"MD010": true,
"MD011": true,
"MD014": true,
"MD018": true,
"MD019": true,
"MD037": true,
"MD038": true,
"MD039": true,
"MD047": true
}
+42 -3
View File
@@ -10,13 +10,11 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.2 rev: v0.8.2
hooks: hooks:
# Ruff linter
- id: ruff - id: ruff
name: ruff-lint name: ruff-lint
args: [--fix, --exit-non-zero-on-fix] args: [--fix, --exit-non-zero-on-fix]
types_or: [python, pyi] types_or: [python, pyi]
files: ^scripts/ files: ^scripts/
# Ruff formatter (replaces black)
- id: ruff-format - id: ruff-format
name: ruff-format name: ruff-format
types_or: [python, pyi] types_or: [python, pyi]
@@ -28,7 +26,7 @@ repos:
hooks: hooks:
- id: bandit - id: bandit
name: bandit-security name: bandit-security
args: [-c, pyproject.toml] args: [-c, scripts/pyproject.toml]
additional_dependencies: ["bandit[toml]"] additional_dependencies: ["bandit[toml]"]
types: [python] types: [python]
files: ^scripts/ files: ^scripts/
@@ -52,3 +50,44 @@ repos:
args: [--maxkb=1000] args: [--maxkb=1000]
- id: check-merge-conflict - id: check-merge-conflict
name: check-merge-conflict name: check-merge-conflict
# Local doc quality hooks (mirrors CI checks — CI is a 2nd pass of these)
- repo: local
hooks:
- id: markdown-lint
name: markdown-lint
language: node
entry: markdownlint
args: ['--ignore', 'node_modules', '--ignore', '.venv', '--config', '.markdownlint.json']
types: [markdown]
additional_dependencies: ['markdownlint-cli']
- id: cross-references
name: cross-references
language: system
entry: python scripts/check_cross_references.py
pass_filenames: false
types: [markdown]
- id: mermaid
name: mermaid-syntax
language: system
entry: python scripts/check_mermaid.py
pass_filenames: false
types: [markdown]
verbose: true
- id: link-check
name: link-check
language: system
entry: python scripts/check_links.py
pass_filenames: false
types: [markdown]
verbose: true
- id: build-epub
name: build-epub
language: system
entry: uv run scripts/build_epub.py
pass_filenames: false
files: ^(.*\.md|scripts/build_epub\.py)$
@@ -80,7 +80,6 @@ usersWithPosts.forEach(({ user, posts }) => {
- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem) - [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem)
- [Database Join Documentation](https://docs.example.com/joins) - [Database Join Documentation](https://docs.example.com/joins)
- [Performance Optimization Guide](./docs/performance.md)
### Reviewer Notes ### Reviewer Notes
+1 -1
View File
@@ -306,7 +306,7 @@ Use **standalone slash commands** for quick personal workflows. Use **plugins**
"author": { "author": {
"name": "Anthropic" "name": "Anthropic"
}, },
"repository": "https://github.com/anthropic/pr-review", "repository": "https://github.com/your-org/pr-review",
"license": "MIT" "license": "MIT"
} }
``` ```
+1 -1
View File
@@ -32,7 +32,7 @@ Comprehensive guide to Claude Code's advanced capabilities including planning mo
21. [Managed Settings (Enterprise)](#managed-settings-enterprise) 21. [Managed Settings (Enterprise)](#managed-settings-enterprise)
22. [Configuration and Settings](#configuration-and-settings) 22. [Configuration and Settings](#configuration-and-settings)
23. [Best Practices](#best-practices) 23. [Best Practices](#best-practices)
24. [Related Concepts](#related-concepts) 24. [Additional Resources](#additional-resources)
--- ---
+32 -12
View File
@@ -67,19 +67,45 @@ git checkout -b docs/improvement-area
``` ```
### 3. Set Up Your Environment ### 3. Set Up Your Environment
Pre-commit hooks run the same checks as CI locally before every commit. All four checks must pass before a PR will be accepted.
**Required dependencies:**
```bash ```bash
# Create virtual environment # Python tooling (uv is the package manager for this project)
python3 -m venv .venv pip install uv
uv venv
source .venv/bin/activate source .venv/bin/activate
uv pip install -r scripts/requirements-dev.txt
# Install pre-commit hooks (optional but recommended) # Markdown linter (Node.js)
pip install pre-commit npm install -g markdownlint-cli
# Mermaid diagram validator (Node.js)
npm install -g @mermaid-js/mermaid-cli
# Install pre-commit and activate hooks
uv pip install pre-commit
pre-commit install pre-commit install
```
# Run pre-commit checks manually **Verify your setup:**
```bash
pre-commit run --all-files pre-commit run --all-files
``` ```
The hooks that run on every commit are:
| Hook | What it checks |
|------|---------------|
| `markdown-lint` | Markdown formatting and structure |
| `cross-references` | Relative links, anchors, code fences |
| `mermaid-syntax` | All ` ```mermaid ` blocks parse correctly |
| `link-check` | External URLs are reachable |
| `build-epub` | EPUB generates without errors (on `.md` changes) |
## Directory Structure ## Directory Structure
``` ```
@@ -219,17 +245,11 @@ docs(skills): Add comprehensive code review skill
### Local Testing ### Local Testing
```bash ```bash
# Check file formatting # Run all pre-commit checks (same checks as CI)
pre-commit run --all-files pre-commit run --all-files
# Verify links work (if applicable)
# Test examples manually with Claude Code
# Review your changes # Review your changes
git diff git diff
# Test the EPUB generation (if docs changed)
uv run scripts/build_epub.py
``` ```
## Pull Request Process ## Pull Request Process
-945
View File
@@ -1,945 +0,0 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="resources/logos/claude-howto-logo.svg">
</picture>
# Claude How To
> A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.
## Why This Guide?
This project complements [Anthropic's official documentation](https://code.claude.com/docs/en/overview) with a different approach:
| | Official Docs | This Guide |
|--|---------------|------------|
| **Format** | Reference documentation | Visual tutorials with diagrams |
| **Depth** | Feature descriptions | How it works under the hood |
| **Examples** | Basic snippets | Production-ready templates you can use immediately |
| **Structure** | Feature-organized | Progressive learning path (beginner → advanced) |
| **Onboarding** | Self-directed | Guided roadmap with time estimates |
| **Self-Assessment** | None | Interactive quizzes to identify skill gaps and build a personalized learning path |
**What you'll find here:**
- Mermaid diagrams explaining how each feature works
- Ready-to-use configurations you can copy into your project
- Real-world examples with context and best practices
- Clear progression from `/help` to building custom agents
- Troubleshooting guides based on common issues
---
## Table of Contents
- [Why This Guide?](#why-this-guide)
- [Feature Catalog](#-feature-catalog)
- [Quick Navigation](#quick-navigation)
- [Learning Path](#-learning-path)
- [Quick Reference](#-quick-reference-choose-your-features)
- [Getting Started](#-getting-started)
- **Features**
- [01. Slash Commands](#01-slash-commands)
- [02. Memory](#02-memory)
- [03. Skills](#03-skills)
- [04. Subagents](#04-subagents)
- [05. MCP Protocol](#05-mcp-protocol)
- [06. Hooks](#06-hooks)
- [07. Plugins](#07-plugins)
- [08. Checkpoints](#08-checkpoints-and-rewind)
- [09. Advanced Features](#09-advanced-features)
- [10. CLI Reference](#10-cli-reference)
- [Directory Structure](#directory-structure)
- [Installation Quick Reference](#installation-quick-reference)
- [Example Workflows](#example-workflows)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
- [Testing](#testing)
- [Additional Resources](#additional-resources)
- [Contributing](#contributing)
- [EPUB Generation](#epub-generation)
- [Contributors](#contributors)
- [Star History](#star-history)
---
## Feature Catalog
**Looking for a quick reference?** Check out our comprehensive **[Feature Catalog](CATALOG.md)** for:
- All slash commands (built-in and custom) with descriptions
- Sub-agents and their capabilities
- Skills with auto-invocation triggers
- Plugins with components and installation commands
- MCP servers for external integrations
- Hooks for event-driven automation
- One-command installation for each feature
**[View Full Catalog](CATALOG.md)**
---
## Quick Navigation
| Feature | Description | Folder |
|---------|-------------|--------|
| **Feature Catalog** | Complete reference with installation commands | [CATALOG.md](CATALOG.md) |
| **Slash Commands** | User-invoked shortcuts | [01-slash-commands/](01-slash-commands/) |
| **Memory** | Persistent context | [02-memory/](02-memory/) |
| **Skills** | Reusable capabilities | [03-skills/](03-skills/) |
| **Subagents** | Specialized AI assistants | [04-subagents/](04-subagents/) |
| **MCP Protocol** | External tool access | [05-mcp/](05-mcp/) |
| **Hooks** | Event-driven automation | [06-hooks/](06-hooks/) |
| **Plugins** | Bundled features | [07-plugins/](07-plugins/) |
| **Checkpoints** | Session snapshots & rewind | [08-checkpoints/](08-checkpoints/) |
| **Advanced Features** | Planning, thinking, background tasks | [09-advanced-features/](09-advanced-features/) |
| **CLI Reference** | Commands, flags, and options | [10-cli/](10-cli/) |
| **Blog Posts** | Real-world usage examples | [Blog Posts](https://medium.com/@luongnv89) |
---
## 📚 Learning Path
**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.
> **Built-in skills**: This repo includes two interactive skills you can use directly in Claude Code:
> - `/self-assessment` — Evaluate your overall Claude Code proficiency and get a personalized learning path
> - `/lesson-quiz [lesson]` — Test your understanding of any specific lesson (e.g., `/lesson-quiz hooks`)
| Order | Feature | Level | Time | Recommended For |
|-------|---------|-------|------|-----------------|
| **1** | [Slash Commands](01-slash-commands/) | ⭐ Beginner | 30 min | Level 1 start |
| **2** | [Memory](02-memory/) | ⭐⭐ Beginner+ | 45 min | Level 1 |
| **3** | [Checkpoints](08-checkpoints/) | ⭐⭐ Intermediate | 45 min | Level 1 |
| **4** | [CLI Basics](10-cli/) | ⭐⭐ Beginner+ | 30 min | Level 1 |
| **5** | [Skills](03-skills/) | ⭐⭐ Intermediate | 1 hour | Level 2 start |
| **6** | [Hooks](06-hooks/) | ⭐⭐ Intermediate | 1 hour | Level 2 |
| **7** | [MCP](05-mcp/) | ⭐⭐⭐ Intermediate+ | 1 hour | Level 2 |
| **8** | [Subagents](04-subagents/) | ⭐⭐⭐ Intermediate+ | 1.5 hours | Level 2 |
| **9** | [Advanced](09-advanced-features/) | ⭐⭐⭐⭐⭐ Advanced | 2-3 hours | Level 3 start |
| **10** | [Plugins](07-plugins/) | ⭐⭐⭐⭐ Advanced | 2 hours | Level 3 |
| **11** | [CLI Mastery](10-cli/) | ⭐⭐⭐ Advanced | 1 hour | Level 3 |
**Total**: ~11-13 hours | 📖 **[Complete Learning Roadmap →](LEARNING-ROADMAP.md)**
---
## 🎯 Quick Reference: Choose Your Features
### Feature Comparison
| Feature | Invocation | Persistence | Best For |
|---------|-----------|------------|----------|
| **Slash Commands** | Manual (`/cmd`) | Session only | Quick shortcuts |
| **Memory** | Auto-loaded | Cross-session | Long-term learning |
| **Skills** | Auto-invoked | Filesystem | Automated workflows |
| **Subagents** | Auto-delegated | Isolated context | Task distribution |
| **MCP Protocol** | Auto-queried | Real-time | Live data access |
| **Hooks** | Event-triggered | Configured | Automation & validation |
| **Plugins** | One command | All features | Complete solutions |
| **Checkpoints** | Manual/Auto | Session-based | Safe experimentation |
| **Planning Mode** | Manual/Auto | Plan phase | Complex implementations |
| **Background Tasks** | Manual | Task duration | Long-running operations |
| **CLI Reference** | Terminal commands | Session/Script | Automation & scripting |
### Use Case Matrix
| Use Case | Recommended Features |
|----------|---------------------|
| **Team Onboarding** | Memory + Slash Commands + Plugins |
| **Code Quality** | Subagents + Skills + Memory + Hooks |
| **Documentation** | Skills + Subagents + Plugins |
| **DevOps** | Plugins + MCP + Hooks + Background Tasks |
| **Security Review** | Subagents + Skills + Hooks (read-only mode) |
| **API Integration** | MCP + Memory |
| **Quick Tasks** | Slash Commands |
| **Complex Projects** | All Features + Planning Mode |
| **Refactoring** | Checkpoints + Planning Mode + Hooks |
| **Learning/Experimentation** | Checkpoints + Extended Thinking + Permission Mode |
| **CI/CD Automation** | CLI Reference + Hooks + Background Tasks |
| **Performance Optimization** | Planning Mode + Checkpoints + Background Tasks |
| **Script Automation** | CLI Reference + Hooks + MCP |
| **Batch Processing** | CLI Reference + Background Tasks |
---
## ⚡ Getting Started
### 15 Minutes - First Steps
```bash
# Copy your first slash command
cp 01-slash-commands/optimize.md .claude/commands/
# Try it!
# In Claude Code: /optimize
```
### 1 Hour - Essential Setup
```bash
# 1. Slash commands (15 min)
cp 01-slash-commands/*.md .claude/commands/
# 2. Project memory (15 min)
cp 02-memory/project-CLAUDE.md ./CLAUDE.md
# 3. Install a skill (15 min)
cp -r 03-skills/code-review ~/.claude/skills/
# 4. Try them together (15 min)
# See how they work in harmony!
```
### Weekend - Full Setup
- **Day 1**: Slash Commands, Memory, Skills, Hooks
- **Day 2**: Subagents, MCP integration, Plugins
- **Result**: Complete Claude Code power user setup
📖 **[Detailed milestones and exercises →](LEARNING-ROADMAP.md)**
---
## 01. Slash Commands
**Location**: [01-slash-commands/](01-slash-commands/)
**What**: User-invoked shortcuts stored as Markdown files
**Examples**:
- `optimize.md` - Code optimization analysis
- `pr.md` - Pull request preparation
- `generate-api-docs.md` - API documentation generator
**Installation**:
```bash
cp 01-slash-commands/*.md /path/to/project/.claude/commands/
```
**Usage**:
```
/optimize
/pr
/generate-api-docs
```
**Learn More**: [Discovering Claude Code Slash Commands](https://medium.com/@luongnv89/discovering-claude-code-slash-commands-cdc17f0dfb29)
---
## 02. Memory
**Location**: [02-memory/](02-memory/)
**What**: Persistent context across sessions
**Examples**:
- `project-CLAUDE.md` - Team-wide project standards
- `directory-api-CLAUDE.md` - Directory-specific rules
- `personal-CLAUDE.md` - Personal preferences
**Installation**:
```bash
# Project memory
cp 02-memory/project-CLAUDE.md /path/to/project/CLAUDE.md
# Directory memory
cp 02-memory/directory-api-CLAUDE.md /path/to/project/src/api/CLAUDE.md
# Personal memory
cp 02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md
```
**Usage**: Automatically loaded by Claude
---
## 03. Skills
**Location**: [03-skills/](03-skills/)
**What**: Reusable, auto-invoked capabilities with instructions and scripts
**Examples**:
- `code-review/` - Comprehensive code review with scripts
- `brand-voice/` - Brand voice consistency checker
- `doc-generator/` - API documentation generator
**Installation**:
```bash
# Personal skills
cp -r 03-skills/code-review ~/.claude/skills/
# Project skills
cp -r 03-skills/code-review /path/to/project/.claude/skills/
```
**Usage**: Automatically invoked when relevant
---
## 04. Subagents
**Location**: [04-subagents/](04-subagents/)
**What**: Specialized AI assistants with isolated contexts and custom prompts
**Examples**:
- `code-reviewer.md` - Comprehensive code quality analysis
- `test-engineer.md` - Test strategy and coverage
- `documentation-writer.md` - Technical documentation
- `secure-reviewer.md` - Security-focused review (read-only)
- `implementation-agent.md` - Full feature implementation
**Installation**:
```bash
cp 04-subagents/*.md /path/to/project/.claude/agents/
```
**Usage**: Automatically delegated by main agent
---
## 05. MCP Protocol
**Location**: [05-mcp/](05-mcp/)
**What**: Model Context Protocol for accessing external tools and APIs
**Examples**:
- `github-mcp.json` - GitHub integration
- `database-mcp.json` - Database queries
- `filesystem-mcp.json` - File operations
- `multi-mcp.json` - Multiple MCP servers
**Installation**:
```bash
# Set environment variables
export GITHUB_TOKEN="your_token"
export DATABASE_URL="postgresql://..."
# Add MCP server via CLI
claude mcp add github -- npx -y @modelcontextprotocol/server-github
# Or add to project .mcp.json manually (see 05-mcp/ for examples)
```
**Usage**: MCP tools are automatically available to Claude once configured
---
## 06. Hooks
**Location**: [06-hooks/](06-hooks/)
**What**: Event-driven shell commands that execute automatically in response to Claude Code events
**Examples**:
- `format-code.sh` - Auto-format code before writing
- `pre-commit.sh` - Run tests before commits
- `security-scan.sh` - Scan for security issues
- `log-bash.sh` - Log all bash commands
- `validate-prompt.sh` - Validate user prompts
- `notify-team.sh` - Send notifications on events
**Installation**:
```bash
mkdir -p ~/.claude/hooks
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
```
Configure hooks in `~/.claude/settings.json`:
```json
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": ["~/.claude/hooks/format-code.sh"]
}],
"PostToolUse": [{
"matcher": "Write",
"hooks": ["~/.claude/hooks/security-scan.sh"]
}]
}
}
```
**Usage**: Hooks execute automatically on events
**Hook Types**:
- **Tool Hooks**: `PreToolUse:*`, `PostToolUse:*`
- **Session Hooks**: `Stop`, `SubagentStop`, `SubagentStart`
- **Lifecycle Hooks**: `Notification`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`
---
## 07. Plugins
**Location**: [07-plugins/](07-plugins/)
**What**: Bundled collections of commands, agents, MCP, and hooks
**Examples**:
- `pr-review/` - Complete PR review workflow
- `devops-automation/` - Deployment and monitoring
- `documentation/` - Documentation generation
**Installation**:
```bash
/plugin install pr-review
/plugin install devops-automation
/plugin install documentation
```
**Usage**: Use bundled slash commands and features
---
## 08. Checkpoints and Rewind
**Location**: [08-checkpoints/](08-checkpoints/)
**What**: Save conversation state and rewind to previous points to explore different approaches
**Key Concepts**:
- **Checkpoint**: Snapshot of conversation state
- **Rewind**: Return to previous checkpoint
- **Branch Point**: Explore multiple approaches from same checkpoint
**Usage**:
```
# Checkpoints are created automatically with every user prompt
# To rewind, press Esc twice or use:
/rewind
# Then choose from five options:
# 1. Restore code and conversation
# 2. Restore conversation
# 3. Restore code
# 4. Summarize from here
# 5. Never mind
```
**Use Cases**:
- Try different implementation approaches
- Recover from mistakes
- Safe experimentation
- Compare alternative solutions
- A/B testing different designs
**Example Workflow**:
```
1. Work normally (checkpoints are created automatically)
2. Try experimental approach
3. If it works: Continue
4. If it fails: Press Esc+Esc or /rewind to go back
```
---
## 09. Advanced Features
**Location**: [09-advanced-features/](09-advanced-features/)
**What**: Advanced capabilities for complex workflows and automation
### Planning Mode
Create detailed implementation plans before coding:
```
User: /plan Implement user authentication system
Claude: [Creates comprehensive step-by-step plan]
User: Approve and proceed
```
**Benefits**: Clear roadmap, time estimates, risk assessment
### Extended Thinking
Deep reasoning for complex problems. Toggle with `Alt+T` / `Option+T`, or set `MAX_THINKING_TOKENS` environment variable:
```bash
# Toggle in-session: press Alt+T (Option+T on macOS)
# Or set via environment variable
MAX_THINKING_TOKENS=10000 claude
# Then ask complex questions
User: Should we use microservices or monolith?
Claude: [Analyzes trade-offs systematically with extended reasoning]
```
**Benefits**: Better architectural decisions, thorough analysis
### Background Tasks
Run long operations without blocking:
```
User: Run tests in background
Claude: Started bg-1234, you can continue working
[Later] Test results: 245 passed, 3 failed
```
**Benefits**: Parallel development, no waiting
### Permission Modes
Control what Claude can do:
- **`default`**: Standard permissions with confirmation prompts
- **`acceptEdits`**: Auto-accept file edits, confirm other actions
- **`plan`**: Analysis and planning only, no modifications
- **`dontAsk`**: Accept all actions without confirmation
- **`bypassPermissions`**: Skip all permission checks (dangerous)
```bash
claude --permission-mode plan # Code review mode
claude --permission-mode acceptEdits # Learning mode
claude --permission-mode default # Standard mode
```
### Headless Mode
Run Claude Code in CI/CD and automation:
```bash
claude -p "Run tests and generate report"
```
**Use Cases**: CI/CD, automated reviews, batch processing
### Session Management
Manage multiple work sessions:
```bash
/resume # Resume a previous session interactively
/rename # Rename the current session
/fork # Fork the current session
claude -c # Continue the most recent session
claude -r "session" # Resume a session matching the query
```
### Interactive Features
**Keyboard Shortcuts**: Ctrl+R (search), Tab (complete), ↑/↓ (history)
**Command History**: Access previous commands
**Multi-line Input**: Complex prompts across multiple lines
### Configuration
Customize Claude Code behavior in `~/.claude/settings.json`:
```json
{
"permissions": {
"allow": ["Read", "Glob", "Grep", "Bash(git *)"],
"deny": ["Bash(rm -rf *)"]
},
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": ["~/.claude/hooks/format-code.sh"]
}]
},
"env": {
"MAX_THINKING_TOKENS": "10000"
}
}
```
See [config-examples.json](09-advanced-features/config-examples.json) for complete configurations.
---
## 10. CLI Reference
**Location**: [10-cli/](10-cli/)
**What**: Complete command-line interface reference for Claude Code
**Key Areas**:
- CLI commands (`claude`, `claude -p`, `claude -c`, `claude -r`)
- Core flags (print mode, continue, resume, version)
- Model & configuration (`--model`, `--agents`)
- System prompt customization
- Tool & permission management
- Output formats (text, JSON, stream-JSON)
- MCP configuration
- Session management
**Quick Examples**:
```bash
# Interactive mode
claude "explain this project"
# Print mode (non-interactive)
claude -p "review this code"
# Process file content
cat error.log | claude -p "explain this error"
# JSON output for scripts
claude -p --output-format json "list functions"
# Resume session
claude -r "feature-auth" "continue implementation"
```
**Use Cases**:
- CI/CD pipeline integration
- Script automation and piping
- Batch processing
- Multi-session workflows
- Custom agent configurations
---
## Directory Structure
```
├── 01-slash-commands/
│ ├── optimize.md
│ ├── pr.md
│ ├── generate-api-docs.md
│ └── README.md
├── 02-memory/
│ ├── project-CLAUDE.md
│ ├── directory-api-CLAUDE.md
│ ├── personal-CLAUDE.md
│ └── README.md
├── 03-skills/
│ ├── code-review/
│ │ ├── SKILL.md
│ │ ├── scripts/
│ │ └── templates/
│ ├── brand-voice/
│ │ ├── SKILL.md
│ │ └── templates/
│ ├── doc-generator/
│ │ ├── SKILL.md
│ │ └── generate-docs.py
│ └── README.md
├── 04-subagents/
│ ├── code-reviewer.md
│ ├── test-engineer.md
│ ├── documentation-writer.md
│ ├── secure-reviewer.md
│ ├── implementation-agent.md
│ └── README.md
├── 05-mcp/
│ ├── github-mcp.json
│ ├── database-mcp.json
│ ├── filesystem-mcp.json
│ ├── multi-mcp.json
│ └── README.md
├── 06-hooks/
│ ├── format-code.sh
│ ├── pre-commit.sh
│ ├── security-scan.sh
│ ├── log-bash.sh
│ ├── validate-prompt.sh
│ ├── notify-team.sh
│ └── README.md
├── 07-plugins/
│ ├── pr-review/
│ ├── devops-automation/
│ ├── documentation/
│ └── README.md
├── 08-checkpoints/
│ ├── checkpoint-examples.md
│ └── README.md
├── 09-advanced-features/
│ ├── config-examples.json
│ ├── planning-mode-examples.md
│ └── README.md
├── 10-cli/
│ └── README.md
└── README.md (this file)
```
---
## Installation Quick Reference
```bash
# Slash Commands
cp 01-slash-commands/*.md .claude/commands/
# Memory
cp 02-memory/project-CLAUDE.md ./CLAUDE.md
# Skills
cp -r 03-skills/code-review ~/.claude/skills/
# Subagents
cp 04-subagents/*.md .claude/agents/
# MCP
export GITHUB_TOKEN="token"
claude mcp add github -- npx -y @modelcontextprotocol/server-github
# Hooks
mkdir -p ~/.claude/hooks
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
# Plugins
/plugin install pr-review
# Checkpoints (auto-enabled, configure in settings)
# See 08-checkpoints/README.md
# Advanced Features (configure in settings)
# See 09-advanced-features/config-examples.json
# CLI Reference (no installation needed)
# See 10-cli/README.md for usage examples
```
---
## Example Workflows
### 1. Complete Code Review Workflow
```markdown
# Uses: Slash Commands + Subagents + Memory + MCP
User: /review-pr
Claude:
1. Loads project memory (coding standards)
2. Fetches PR via GitHub MCP
3. Delegates to code-reviewer subagent
4. Delegates to test-engineer subagent
5. Synthesizes findings
6. Provides comprehensive review
```
### 2. Automated Documentation
```markdown
# Uses: Skills + Subagents + Memory
User: "Generate API documentation for the auth module"
Claude:
1. Loads project memory (doc standards)
2. Detects doc generation request
3. Auto-invokes doc-generator skill
4. Delegates to api-documenter subagent
5. Creates comprehensive docs with examples
```
### 3. DevOps Deployment
```markdown
# Uses: Plugins + MCP + Hooks
User: /deploy production
Claude:
1. Runs pre-deploy hook (validates environment)
2. Delegates to deployment-specialist subagent
3. Executes deployment via Kubernetes MCP
4. Monitors progress
5. Runs post-deploy hook (health checks)
6. Reports status
```
---
## Best Practices
### Do's ✅
- Start simple with slash commands
- Add features incrementally
- Use memory for team standards
- Test configurations locally first
- Document custom implementations
- Version control project configurations
- Share plugins with team
### Don'ts ❌
- Don't create redundant features
- Don't hardcode credentials
- Don't skip documentation
- Don't over-complicate simple tasks
- Don't ignore security best practices
- Don't commit sensitive data
---
## Troubleshooting
### Feature Not Loading
1. Check file location and naming
2. Verify YAML frontmatter syntax
3. Check file permissions
4. Review Claude Code version compatibility
### MCP Connection Failed
1. Verify environment variables
2. Check MCP server installation
3. Test credentials
4. Review network connectivity
### Subagent Not Delegating
1. Check tool permissions
2. Verify agent description clarity
3. Review task complexity
6. Test agent independently
---
## Testing
This project includes comprehensive automated testing to ensure code quality and reliability.
### Testing Overview
- **Unit Tests**: Python tests using pytest (Python 3.10, 3.11, 3.12)
- **Code Quality**: Linting and formatting with Ruff
- **Security**: Vulnerability scanning with Bandit
- **Type Checking**: Static type analysis with mypy
- **Build Verification**: EPUB generation testing
- **Coverage Tracking**: Codecov integration
### Running Tests Locally
```bash
# Install development dependencies
uv pip install -r requirements-dev.txt
# Run all unit tests
pytest scripts/tests/ -v
# Run tests with coverage report
pytest scripts/tests/ -v --cov=scripts --cov-report=html
# Run code quality checks
ruff check scripts/
ruff format --check scripts/
# Run security scan
bandit -c pyproject.toml -r scripts/ --exclude scripts/tests/
# Run type checking
mypy scripts/ --ignore-missing-imports
```
### Automated Testing on GitHub
Tests run automatically on:
- Every push to `main` or `develop` branches
- Every pull request to `main`
View test results in the GitHub Actions tab or check the [TESTING.md](.github/TESTING.md) guide for detailed information.
### Writing Tests
When contributing, please include tests for new functionality:
1. **Write tests** in `scripts/tests/test_*.py`
2. **Run tests locally** to verify they pass
3. **Check coverage** with `pytest --cov=scripts`
4. **Submit with PR** - tests are required for all contributions
For detailed testing guidelines, see [TESTING.md](.github/TESTING.md).
---
## Additional Resources
- [Claude Code Documentation](https://code.claude.com/docs/en/overview)
- [MCP Protocol Specification](https://modelcontextprotocol.io)
- [Skills Repository](https://github.com/luongnv89/skills) - Collection of ready-to-use skills
- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)
- [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.
---
## Contributing
Found an issue or want to contribute an example? We'd love your help!
**Please read [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:**
- Types of contributions (examples, docs, features, bugs, feedback)
- How to set up your development environment
- Directory structure and how to add content
- Writing guidelines and best practices
- Commit and PR process
**Our Community Standards:**
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - How we treat each other
- [SECURITY.md](SECURITY.md) - Security policy and vulnerability reporting
### Reporting Security Issues
If you discover a security vulnerability, please report it responsibly:
1. **Use GitHub Private Vulnerability Reporting**: https://github.com/luongnv89/claude-howto/security/advisories
2. **Or read** [.github/SECURITY_REPORTING.md](.github/SECURITY_REPORTING.md) for detailed instructions
3. **Do NOT** open a public issue for security vulnerabilities
Security issues are taken seriously and will be addressed promptly. See [SECURITY.md](SECURITY.md) for our full security policy.
Quick start:
1. Fork and clone the repository
2. Create a descriptive branch (`add/feature-name`, `fix/bug`, `docs/improvement`)
3. Make your changes following the guidelines
4. Submit a pull request with a clear description
**Need help?** Open an issue or discussion, and we'll guide you through the process.
---
## License
This project is licensed under the MIT License - see [LICENSE](LICENSE) file for details.
You are free to:
- Use this guide and examples in your projects
- Modify and adapt the content
- Share and distribute
- Use for commercial purposes
The only requirement is to include a copy of the license and copyright notice.
---
## EPUB Generation
Want to read this guide offline? Generate an EPUB ebook:
```bash
uv run scripts/build_epub.py
```
This creates `claude-howto-guide.epub` with all content, including rendered Mermaid diagrams.
See [scripts/README.md](scripts/README.md) for more options.
---
## Contributors
Thanks to everyone who has contributed to this project!
| Contributor | PRs |
|-------------|-----|
| [wjhrdy](https://github.com/wjhrdy) | [#1 - add a tool to create an epub](https://github.com/luongnv89/claude-howto/pull/1) |
| [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) |
---
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=luongnv89/claude-howto&type=Date)](https://star-history.com/#luongnv89/claude-howto&Date)
---
**Last Updated**: March 2026
**Claude Code Version**: 2.1+
**Compatible Models**: Claude Sonnet 4.6, Claude Opus 4.6, Claude Haiku 4.5
+6 -6
View File
@@ -19,7 +19,7 @@
Go from typing `claude` to orchestrating agents, hooks, skills, and MCP servers — with visual tutorials, copy-paste templates, and a guided learning path. Go from typing `claude` to orchestrating agents, hooks, skills, and MCP servers — with visual tutorials, copy-paste templates, and a guided learning path.
**[Get Started in 15 Minutes](#-get-started-in-15-minutes)** | **[Find Your Level](#-not-sure-where-to-start)** | **[Browse the Feature Catalog](CATALOG.md)** **[Get Started in 15 Minutes](#get-started-in-15-minutes)** | **[Find Your Level](#not-sure-where-to-start)** | **[Browse the Feature Catalog](CATALOG.md)**
--- ---
@@ -28,8 +28,8 @@ Go from typing `claude` to orchestrating agents, hooks, skills, and MCP servers
- [The Problem](#the-problem) - [The Problem](#the-problem)
- [How Claude How To Fixes This](#how-claude-how-to-fixes-this) - [How Claude How To Fixes This](#how-claude-how-to-fixes-this)
- [How It Works](#how-it-works) - [How It Works](#how-it-works)
- [Not Sure Where to Start?](#-not-sure-where-to-start) - [Not Sure Where to Start?](#not-sure-where-to-start)
- [Get Started in 15 Minutes](#-get-started-in-15-minutes) - [Get Started in 15 Minutes](#get-started-in-15-minutes)
- [What Can You Build With This?](#what-can-you-build-with-this) - [What Can You Build With This?](#what-can-you-build-with-this)
- [FAQ](#faq) - [FAQ](#faq)
- [Contributing](#contributing) - [Contributing](#contributing)
@@ -92,7 +92,7 @@ The real power is in combining features. Learn to wire slash commands + memory +
Run `/lesson-quiz [topic]` after each module. The quiz pinpoints what you missed so you can fill gaps fast. Run `/lesson-quiz [topic]` after each module. The quiz pinpoints what you missed so you can fill gaps fast.
**[Get Started in 15 Minutes](#-get-started-in-15-minutes)** **[Get Started in 15 Minutes](#get-started-in-15-minutes)**
--- ---
@@ -173,7 +173,7 @@ cp -r 03-skills/code-review ~/.claude/skills/
# Follow the learning path for guided setup # Follow the learning path for guided setup
``` ```
**[View the Full Installation Reference](#installation-quick-reference)** **[View the Full Installation Reference](#get-started-in-15-minutes)**
--- ---
@@ -222,7 +222,7 @@ You already have Claude Code installed. The only thing between you and 10x produ
MIT licensed. Free forever. Clone it, fork it, make it yours. MIT licensed. Free forever. Clone it, fork it, make it yours.
**[Start the Learning Path ->](LEARNING-ROADMAP.md)** | **[Browse the Feature Catalog](CATALOG.md)** | **[Get Started in 15 Minutes](#-get-started-in-15-minutes)** **[Start the Learning Path ->](LEARNING-ROADMAP.md)** | **[Browse the Feature Catalog](CATALOG.md)** | **[Get Started in 15 Minutes](#get-started-in-15-minutes)**
--- ---
+1 -2
View File
@@ -16,7 +16,7 @@ A comprehensive reference guide covering Slash Commands, Subagents, Memory, MCP
3. [Memory](#memory) 3. [Memory](#memory)
4. [MCP Protocol](#mcp-protocol) 4. [MCP Protocol](#mcp-protocol)
5. [Agent Skills](#agent-skills) 5. [Agent Skills](#agent-skills)
6. [Plugins](#plugins) 6. [Plugins](#claude-code-plugins)
7. [Hooks](#hooks) 7. [Hooks](#hooks)
8. [Checkpoints and Rewind](#checkpoints-and-rewind) 8. [Checkpoints and Rewind](#checkpoints-and-rewind)
9. [Advanced Features](#advanced-features) 9. [Advanced Features](#advanced-features)
@@ -1754,7 +1754,6 @@ usersWithPosts.forEach(({ user, posts }) => {
- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem) - [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem)
- [Database Join Documentation](https://docs.example.com/joins) - [Database Join Documentation](https://docs.example.com/joins)
- [Performance Optimization Guide](./docs/performance.md)
### Reviewer Notes ### Reviewer Notes
+153
View File
@@ -0,0 +1,153 @@
# Roadmap: claude-howto 20262027
> April 2026 March 2027 · Dual-Layer Knowledge Base | Full plan: `TASKS-20260401.md`
---
## Vision
Transform claude-howto from a static tutorial repo into a **living, dual-audience knowledge system**:
- **For humans** — interactive, scenario-based learning with progressive difficulty, decision trees, and named patterns that experts bookmark
- **For AI agents** — structured metadata index that agents query before performing Claude Code tasks, making this repo infrastructure, not just content
No competitor targets AI agents as a primary audience. This is the moat.
---
## The 7 Pillars
| # | Pillar | What it delivers |
|---|--------|-----------------|
| P1 | Fun Layer | Scenario intros + "Try It Now" blocks in every module |
| P2 | AI Agent Index | Generated `agent-manifest.json` + `AGENT-INDEX.md` + lookup skill |
| P3a | Expert Reference (in-module) | Decision trees + named patterns per module |
| P3b | Expert Reference (cross-module) | `RECIPES.md` — compound multi-feature workflows |
| P4 | Newcomer Onboarding | `quickstart.sh` + `QUICKSTART.md` + difficulty badges |
| P5 | Community Showcase | `COMMUNITY-PROJECTS.md` — curated user projects |
| P6 | Content Quality | Expand weakest modules; project `CLAUDE.md` |
| P7 | Living Curriculum | `WHATS-NEW.md` + version badges + weekly staleness CI action |
---
## Timeline at a Glance
```
Apr 2026 MayJun 2026 JulAug 2026 Sep 2026 OctNov 2026 Dec 2026Mar 2027
| | | | | |
[M1] [M2] [M3] [M4] [M5] [M6]
Infrastructure 6/10 modules 10/10 Agent layer Version audit Self-sustaining
+ hooks/checks complete complete + recipes complete system
```
---
## Milestones
### M1 — Infrastructure Live · End of April 2026
**What ships:**
- `scripts/quickstart.sh` — one-command setup for new users (idempotent)
- `QUICKSTART.md` — First 15 Minutes visual guide
- Difficulty badges + "What you'll build" previews on all 10 modules
- `WHATS-NEW.md` + version badges on all modules
- `.github/workflows/staleness-check.yml` — weekly Monday issue if module unverified 30+ days
- Root `CLAUDE.md` — project's own configuration as a best-practice example
- `scripts/build-agent-index.py` — generator that reads all 10 modules → outputs `agent-manifest.json` + `AGENT-INDEX.md`
- **06-hooks** — full deep pass: 5 complete hook scripts, decision tree, Try It Now, patterns
- **08-checkpoints** — full deep pass: 311 → 800+ lines, 3 workflow templates, decision tree, patterns
**Why start here:** Infrastructure benefits every future phase. Hooks and checkpoints are the weakest modules and most likely to lose new visitors.
---
### M2 — 6/10 Modules Complete · End of June 2026
**What ships (one deep pass per module):**
- **01-slash-commands** — scenario intro, decision tree, Try It Now, named patterns
- **02-memory** — scenario intro, decision tree, Try It Now, named patterns
- **03-skills** — scenario intro, decision tree, Try It Now, named patterns
- **10-cli** — scenario intro, decision tree, Try It Now, named patterns
- CI step: validate `agent-manifest.json` schema on every push
Each module pass = run the generator to confirm valid manifest output.
---
### M3 — All 10 Modules Complete · End of August 2026
**What ships:**
- **04-subagents** — full deep pass (incl. "The Multi-Agent Review Pattern")
- **05-mcp** — full deep pass
- **07-plugins** — full deep pass
- **09-advanced-features** — full deep pass
Every module now has: scenario intro, 2+ Try It Now blocks, Mermaid decision tree, 2+ named patterns.
---
### M4 — Agent Layer Live · End of September 2026
**What ships:**
- Final `agent-manifest.json` covering 100% of modules (generated from completed content)
- `AGENT-INDEX.md` linked from `README.md`
- `skills/claude-howto-lookup/SKILL.md` — lightweight agent skill that queries the manifest
- `RECIPES.md` — 5+ compound workflows (schema: name, modules-used, problem, solution, expected outcome)
- `COMMUNITY-PROJECTS.md` — static curated list with PR-based submission format
**Why September:** The agent index is only meaningful once all 10 modules are content-complete.
---
### M5 — Version Audit Complete · End of November 2026
**What ships:**
- Full version audit: all 10 modules verified against current CC version
- Updated `cc_version_verified` frontmatter + version badges everywhere
- `RECIPES.md` expanded to 8+ recipes based on observed community patterns
- Pinned GitHub Discussion: "Share your Claude Code workflows" — signal collection for agent usage
---
### M6 — Self-Sustaining System · End of March 2027
**What ships / runs continuously:**
- `/docs-sync-claude-code` skill runs after every CC release → `WHATS-NEW.md` updated
- Agent manifest CI regression: 100% module coverage enforced
- `RECIPES.md` at 10+ recipes
- `COMMUNITY-PROJECTS.md` growing organically
- Agent usage signal evaluated → if validated, promote the lookup skill (marketing, asm registry)
---
## Deliverables Summary
| Deliverable | Type | Phase |
|-------------|------|-------|
| `scripts/quickstart.sh` | Script | P1 |
| `QUICKSTART.md` | Doc | P1 |
| Root `CLAUDE.md` | Config | P1 |
| `WHATS-NEW.md` | Doc | P1 |
| `.github/workflows/staleness-check.yml` | CI | P1 |
| `scripts/build-agent-index.py` | Script | P1 |
| 10 module deep passes (scenario + Try It Now + decision tree + patterns) | Content | P1P3 |
| `agent-manifest.json` (generated) | Data | P4 |
| `AGENT-INDEX.md` (generated) | Doc | P4 |
| `skills/claude-howto-lookup/SKILL.md` | Skill | P4 |
| `RECIPES.md` (5 → 8 → 10+ recipes) | Doc | P4P6 |
| `COMMUNITY-PROJECTS.md` | Doc | P4 |
---
## What Is NOT in Scope
Deferred to `TODOS.md` — do not let these creep in:
- Skill marketplace or installable registry
- Custom website or dashboard
- Completion tracking (cc-progress)
- Community tutorial CI validation
- Auto-generated CONTRIBUTORS.md
- Multi-language translations
- Quiz/assessment infrastructure
- Community voting on projects
+291
View File
@@ -0,0 +1,291 @@
# Tasks: Dual-Layer Knowledge Base — claude-howto
> Created: 2026-04-01
---
## Milestones
| # | Milestone | Target | Description |
|---|-----------|--------|-------------|
| M1 | Infrastructure Live | End of April 2026 | quickstart.sh, CLAUDE.md, staleness action, agent index generator live; 2 weakest modules upgraded |
| M2 | 6/10 Modules Complete | End of June 2026 | Slash commands, memory, skills, CLI modules fully upgraded; generator producing valid manifest |
| M3 | All 10 Modules Complete | End of August 2026 | Every module has scenario intro, Try It Now blocks, decision tree, named patterns |
| M4 | Agent Layer Live | End of September 2026 | agent-manifest.json + AGENT-INDEX.md generated; lookup skill in repo; RECIPES.md + COMMUNITY-PROJECTS.md live |
| M5 | Version Audit Complete | End of November 2026 | All 10 modules verified against current CC version; RECIPES.md at 8+ recipes |
| M6 | Self-Sustaining System | End of March 2027 | Agent manifest covers 100% modules (CI-validated); RECIPES.md at 10+; community page growing organically |
---
## Phase 1 — Infrastructure & Weak Modules (April 2026)
**Target milestone: M1**
### Pillar 4: Newcomer Onboarding
- [ ] **T-001** — Write `scripts/quickstart.sh`
- Detects `~/.claude/` directory (creates with user confirmation if missing)
- Copies first slash command + CLAUDE.md + skill to user's setup
- Appends agent-discovery line to CLAUDE.md linking to AGENT-INDEX.md
- Idempotent: skips existing files with a warning, never overwrites
- Prints next steps on completion
- [ ] **T-002** — Create `QUICKSTART.md` (First 15 Minutes visual guide)
- Annotated terminal steps as code blocks (avoid PNG screenshots where possible; prefer ASCII or Mermaid)
- Document which commands produce each visual so they can be re-captured
- [ ] **T-003** — Add difficulty badges to all 10 module READMEs
- Format: `> 🟢 **Beginner** | ⏱ 30 minutes` at top of each module README
- Add "What you'll build" bullet preview below the badge
### Pillar 7: Living Curriculum
- [ ] **T-004** — Create `WHATS-NEW.md`
- Format: `## CC vX.X — DATE` with bullet items per feature change
- Add at least one entry for current CC version
- [ ] **T-005** — Add version badges to all 10 module READMEs
- Format: `> ✅ Verified against Claude Code **vX.X.X** · Last verified: YYYY-MM-DD`
- Add `cc_version_verified` to each module's frontmatter
- [ ] **T-006** — Create `.github/workflows/staleness-check.yml`
- Schedule: weekly Monday 09:00 UTC
- Reads each module's `last_verified` date from frontmatter (use `yq` or 10-line Python script)
- Creates a GitHub Issue for any module not verified in 30+ days
- Skips if open issue with same title already exists
### Pillar 6: Content Quality (CLAUDE.md)
- [ ] **T-007** — Create root `CLAUDE.md` for the project
- Demonstrates best practices as the project's own configuration
- Documents contributing conventions, module structure, and maintenance workflow
### Pillar 2: AI Agent Index (Generator)
- [ ] **T-008** — Write `scripts/build-agent-index.py`
- Reads all 10 module README files
- Extracts: headings (→ topics), code blocks (→ examples with language tags), tables (→ reference data)
- Outputs `agent-manifest.json` with schema defined in CEO plan
- Outputs `AGENT-INDEX.md` (human-readable summary)
- Validates references point to actual files
### Module 08-checkpoints: Full Deep Pass (311 → 800+ lines)
- [ ] **T-009** — Rewrite module intro with real-world scenario
- Example: "Your refactor just broke 3 things. Here's how checkpoints save you..."
- [ ] **T-010** — Add checkpoint strategy decision tree (Mermaid flowchart)
- "I want to do X" → follow arrows → land on checkpoint pattern
- [ ] **T-011** — Add 3 workflow templates
- Safe refactoring workflow
- A/B testing with checkpoints
- Disaster recovery workflow
- [ ] **T-012** — Add integration with planning mode section
- [ ] **T-013** — Add Mermaid diagram for checkpoint lifecycle
- [ ] **T-014** — Add 2+ "Try It Now" blocks with verifiable commands
- Each: context sentence, command to run, expected output description
- [ ] **T-015** — Add "Patterns & Recipes" section with 2+ named patterns
- Each pattern: problem, solution code, when to use, when NOT to use
### Module 06-hooks: Full Deep Pass
- [ ] **T-016** — Rewrite module intro with real-world scenario
- Example: "Your CI caught a lint error after 20 minutes. Hooks catch it in 2 seconds..."
- [ ] **T-017** — Add hooks decision tree (Mermaid flowchart)
- "I want to trigger X when Y happens" → follow arrows → land on hook type
- [ ] **T-018** — Add 5 complete hook examples with full scripts (~80 lines each)
1. Auto-format on write (prettier/black)
2. Security scan on commit (trufflehog/bandit)
3. Test runner on file change
4. Notification on session end
5. Prompt validation (block dangerous patterns)
- [ ] **T-019** — Add 2+ "Try It Now" blocks with verifiable commands
- [ ] **T-020** — Add "Patterns & Recipes" section with 2+ named patterns
**M1 Checkpoint: infrastructure live, 2 weakest modules fully upgraded**
---
## Phase 2 — Deep Pass: Strong Modules Batch 1 (MayJune 2026)
**Target milestone: M2**
### Module 01-slash-commands: Full Deep Pass
- [ ] **T-021** — Rewrite intro with scenario ("Your teammate just pushed 47 files...")
- [ ] **T-022** — Add decision tree (Mermaid)
- [ ] **T-023** — Add 2+ "Try It Now" blocks
- [ ] **T-024** — Add "Patterns & Recipes" section with 2+ named patterns
### Module 02-memory: Full Deep Pass
- [ ] **T-025** — Rewrite intro with real-world scenario
- [ ] **T-026** — Add decision tree (Mermaid)
- [ ] **T-027** — Add 2+ "Try It Now" blocks
- [ ] **T-028** — Add "Patterns & Recipes" section with 2+ named patterns
### Module 03-skills: Full Deep Pass
- [ ] **T-029** — Rewrite intro with real-world scenario
- [ ] **T-030** — Add decision tree (Mermaid)
- [ ] **T-031** — Add 2+ "Try It Now" blocks
- [ ] **T-032** — Add "Patterns & Recipes" section with 2+ named patterns
### Module 10-cli: Full Deep Pass
- [ ] **T-033** — Rewrite intro with real-world scenario
- [ ] **T-034** — Add decision tree (Mermaid)
- [ ] **T-035** — Add 2+ "Try It Now" blocks
- [ ] **T-036** — Add "Patterns & Recipes" section with 2+ named patterns
### Generator Validation
- [ ] **T-037** — Run `scripts/build-agent-index.py` after each module upgrade; confirm valid manifest output
- [ ] **T-038** — Add CI step: validate agent-manifest.json schema on every push
**M2 Checkpoint: 6/10 modules complete, generator producing valid manifest**
---
## Phase 3 — Deep Pass: Strong Modules Batch 2 (JulyAugust 2026)
**Target milestone: M3**
### Module 04-subagents: Full Deep Pass
- [ ] **T-039** — Rewrite intro with real-world scenario
- [ ] **T-040** — Add decision tree (Mermaid)
- [ ] **T-041** — Add 2+ "Try It Now" blocks
- [ ] **T-042** — Add "Patterns & Recipes" section (e.g., "The Multi-Agent Review Pattern")
### Module 05-mcp: Full Deep Pass
- [ ] **T-043** — Rewrite intro with real-world scenario
- [ ] **T-044** — Add decision tree (Mermaid)
- [ ] **T-045** — Add 2+ "Try It Now" blocks
- [ ] **T-046** — Add "Patterns & Recipes" section with 2+ named patterns
### Module 07-plugins: Full Deep Pass
- [ ] **T-047** — Rewrite intro with real-world scenario
- [ ] **T-048** — Add decision tree (Mermaid)
- [ ] **T-049** — Add 2+ "Try It Now" blocks
- [ ] **T-050** — Add "Patterns & Recipes" section with 2+ named patterns
### Module 09-advanced-features: Full Deep Pass
- [ ] **T-051** — Rewrite intro with real-world scenario
- [ ] **T-052** — Add decision tree (Mermaid)
- [ ] **T-053** — Add 2+ "Try It Now" blocks
- [ ] **T-054** — Add "Patterns & Recipes" section with 2+ named patterns
**M3 Checkpoint: all 10 modules complete and consistent**
---
## Phase 4 — Agent Layer & Cross-Module (September 2026)
**Target milestone: M4**
### Pillar 2: Finalize AI Agent Index
- [ ] **T-055** — Run `scripts/build-agent-index.py` against all 10 completed modules
- Produce final `agent-manifest.json` with 100% module coverage
- Produce `AGENT-INDEX.md` and link from README.md
- [ ] **T-056** — Create `skills/claude-howto-lookup/SKILL.md`
- Reads `agent-manifest.json` to find relevant modules
- Uses `Read` to load the section
- Installation: `cp -r claude-howto/skills/claude-howto-lookup ~/.claude/skills/`
- [ ] **T-057** — Mention lookup skill in quickstart.sh and QUICKSTART.md as optional feature
### Pillar 3b: Cross-Module RECIPES.md
- [ ] **T-058** — Create `RECIPES.md` with 5+ compound workflows
- Schema per recipe: name, modules-used, problem, solution code block, expected outcome
- Example: skill + hook + subagent = automated review pipeline
- Ensure HTML anchors on all major headings for deep-linking
### Pillar 5: Community Showcase
- [ ] **T-059** — Create `COMMUNITY-PROJECTS.md`
- Static Markdown page with submission format: name, description, link, features used
- Template entry included
- PR-based submission instructions
**M4 Checkpoint: agent index live, recipes live, community page live**
---
## Phase 5 — Version Audit & Recipe Expansion (OctoberNovember 2026)
**Target milestone: M5**
- [ ] **T-060** — Run full version audit: verify all 10 modules against current CC version
- Update `cc_version_verified` frontmatter in each module
- Update version badges
- [ ] **T-061** — Expand `RECIPES.md` to 8+ recipes based on observed community patterns
- [ ] **T-062** — Iterate agent manifest schema if new patterns emerge from completed modules
- [ ] **T-063** — Open pinned GitHub Discussion: "Share your Claude Code workflows"
- Collect signal on real agent usage to inform future recipe expansion
**M5 Checkpoint: all modules verified current, recipes growing**
---
## Phase 6 — Compound & Sustain (December 2026 March 2027)
**Target milestone: M6**
- [ ] **T-064** — Run `/docs-sync-claude-code` skill after every CC release; update `WHATS-NEW.md`
- [ ] **T-065** — Ensure agent manifest covers 100% of modules (CI regression test)
- [ ] **T-066** — Grow `RECIPES.md` to 10+ recipes
- [ ] **T-067** — Monitor `COMMUNITY-PROJECTS.md` for organic growth; curate new entries
- [ ] **T-068** — Evaluate agent usage signal from GitHub Discussions; if validated, invest in promoting the lookup skill (marketing, asm registry)
**M6 Checkpoint: the system is self-sustaining**
---
## Deferred (TODOS.md)
These items are out of scope for this plan. Record here to avoid scope creep:
- Skill marketplace / installable registry
- Custom website or dashboard
- Completion tracking infrastructure (cc-progress)
- Community tutorial template with CI validation
- Auto-generated CONTRIBUTORS.md
- Multi-language translations
- Quiz/assessment infrastructure upgrades
- Community voting/review mechanism for COMMUNITY-PROJECTS.md
---
## Task Summary by Phase
| Phase | Tasks | Period | Modules Touched |
|-------|-------|--------|-----------------|
| 1 — Infrastructure & Weak Modules | T-001 to T-020 | April 2026 | 06-hooks, 08-checkpoints + infra |
| 2 — Batch 1 Deep Pass | T-021 to T-038 | MayJune 2026 | 01, 02, 03, 10 |
| 3 — Batch 2 Deep Pass | T-039 to T-054 | JulyAugust 2026 | 04, 05, 07, 09 |
| 4 — Agent Layer & Cross-Module | T-055 to T-059 | September 2026 | All (manifest) + new files |
| 5 — Version Audit & Recipes | T-060 to T-063 | OctoberNovember 2026 | All (audit) |
| 6 — Sustain | T-064 to T-068 | December 2026March 2027 | Ongoing |
+1 -1
View File
@@ -21,7 +21,7 @@
| Keybindings | Keyboard shortcut customization | [code.claude.com/docs/en/keybindings](https://code.claude.com/docs/en/keybindings) | | Keybindings | Keyboard shortcut customization | [code.claude.com/docs/en/keybindings](https://code.claude.com/docs/en/keybindings) |
| Desktop App | Native desktop application | [code.claude.com/docs/en/desktop](https://code.claude.com/docs/en/desktop) | | Desktop App | Native desktop application | [code.claude.com/docs/en/desktop](https://code.claude.com/docs/en/desktop) |
| Remote Control | Remote session control | [code.claude.com/docs/en/remote-control](https://code.claude.com/docs/en/remote-control) | | Remote Control | Remote session control | [code.claude.com/docs/en/remote-control](https://code.claude.com/docs/en/remote-control) |
| Auto Mode | Automatic permission management | [code.claude.com/docs/en/auto-mode](https://code.claude.com/docs/en/auto-mode) | | Auto Mode | Automatic permission management | [code.claude.com/docs/en/permissions](https://code.claude.com/docs/en/permissions) |
| Channels | Multi-channel communication | [code.claude.com/docs/en/channels](https://code.claude.com/docs/en/channels) | | Channels | Multi-channel communication | [code.claude.com/docs/en/channels](https://code.claude.com/docs/en/channels) |
| Voice Dictation | Voice input for Claude Code | [code.claude.com/docs/en/voice-dictation](https://code.claude.com/docs/en/voice-dictation) | | Voice Dictation | Voice input for Claude Code | [code.claude.com/docs/en/voice-dictation](https://code.claude.com/docs/en/voice-dictation) |
-1
View File
@@ -239,4 +239,3 @@ Questions or customization needed?
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Happy building! 🚀 Happy building! 🚀
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Validate cross-references, anchors, and code fences in Markdown files."""
import re
import sys
from pathlib import Path
IGNORE_DIRS = {
".venv",
"node_modules",
".git",
"blog-posts",
"openspec",
"prompts",
".agents",
}
IGNORE_FILES = {"README.backup.md"}
def iter_md_files():
for f in Path().rglob("*.md"):
if (
not any(part in IGNORE_DIRS for part in f.parts)
and f.name not in IGNORE_FILES
):
yield f
def heading_to_anchor(heading: str) -> str:
# Match GitHub's anchor generation: strip non-ASCII (emoji), strip punctuation,
# lowercase, replace spaces with hyphens, strip leading/trailing hyphens.
heading_ascii = heading.encode("ascii", "ignore").decode()
return re.sub(r"[^\w\s-]", "", heading_ascii.lower()).replace(" ", "-").rstrip("-")
def strip_code_blocks(content: str) -> str:
"""Remove fenced code blocks and inline code spans to avoid scanning example links."""
# Strip fenced code blocks (``` ... ```)
content = re.sub(r"```[^\n]*\n.*?```", "", content, flags=re.DOTALL)
# Strip inline code spans (` ... `)
content = re.sub(r"`[^`\n]+`", "", content)
return content
def main() -> int:
errors = []
for file_path in iter_md_files():
content = file_path.read_text()
# Strip code blocks before scanning for links/anchors to avoid false positives
# from documentation examples inside code fences.
scannable = strip_code_blocks(content)
# Relative .md links must resolve
errors.extend(
f"{file_path}: broken cross-reference → '{link_path}'"
for link_path in re.findall(r"\[[^\]]+\]\(([^)#]+\.md)[^)]*\)", scannable)
if not (file_path.parent / link_path).resolve().exists()
)
# In-page anchors must match a real heading
anchors = re.findall(r"\[[^\]]+\]\(#([^)]+)\)", scannable)
if anchors:
headings = re.findall(r"^#{1,6}\s+(.+)$", content, re.MULTILINE)
valid_anchors = {heading_to_anchor(h) for h in headings}
errors.extend(
f"{file_path}: broken anchor → '#{anchor}'"
for anchor in anchors
if anchor not in valid_anchors
)
# Unmatched code fences (only count fences at start of line)
if len(re.findall(r"^```", content, re.MULTILINE)) % 2 != 0:
errors.append(f"{file_path}: unmatched code fences")
# All numbered lesson dirs must have README.md
for i in range(1, 11):
errors.extend(
f"{d}: missing README.md"
for d in Path().glob(f"{i:02d}-*")
if d.is_dir() and not (d / "README.md").exists()
)
if errors:
print("❌ Cross-reference errors:")
for e in errors:
print(f" - {e}")
return 1
md_count = sum(1 for _ in iter_md_files())
print(f"✅ All cross-references valid ({md_count} files checked)")
return 0
if __name__ == "__main__":
sys.exit(main())
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""Check external URLs in Markdown files are reachable."""
import re
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
IGNORE_DIRS = {
".venv",
"node_modules",
".git",
"blog-posts",
"openspec",
"prompts",
".agents",
".claude",
}
TIMEOUT = 10
# Domains/patterns to skip: badges, placeholders, and bot-blocking hosts
SKIP_DOMAINS = {
"shields.io",
"img.shields.io",
"star-history.com",
"api.star-history.com",
"example.com",
"localhost",
"127.0.0.1",
"my-webhook.example.com",
"git.internal",
# Wikipedia blocks HEAD requests — GET also unreliable in CI without network
"en.wikipedia.org",
"wikipedia.org",
# GitHub API requires auth — unauthenticated requests return 404 for protected endpoints
"api.github.com",
}
SKIP_DOMAIN_SUFFIXES = (".example.com", ".example.org", ".internal")
# Placeholder/template URLs that are intentionally non-resolvable
SKIP_URL_PATTERNS = {
"github.com/org/",
"github.com/user/",
"github.com/your-org/",
"docs.example.com",
}
URL_RE = re.compile(r"https?://[a-zA-Z0-9][a-zA-Z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+")
def is_skipped(url: str) -> bool:
try:
domain = url.split("/")[2]
except IndexError:
return True # malformed URL
if any(skip == domain or domain.endswith("." + skip) for skip in SKIP_DOMAINS):
return True
if any(domain.endswith(suffix) for suffix in SKIP_DOMAIN_SUFFIXES):
return True
return any(pattern in url for pattern in SKIP_URL_PATTERNS)
def check_url(url: str) -> tuple[str, bool, str]:
if is_skipped(url):
return url, True, "skipped"
try:
req = urllib.request.Request(
url, headers={"User-Agent": "Mozilla/5.0"}, method="HEAD"
)
with urllib.request.urlopen(req, timeout=TIMEOUT): # nosec B310
return url, True, "ok"
except urllib.error.HTTPError as e:
# 403/429 often means the server is up but blocks bots — treat as ok
if e.code in (401, 403, 405, 429):
return url, True, f"http {e.code} (ignored)"
return url, False, f"HTTP {e.code}"
except Exception as e:
return url, False, str(e)
def main(strict: bool = False) -> int:
urls: dict[str, list[str]] = {} # url -> [file, ...]
md_files = [
f
for f in Path().rglob("*.md")
if not any(part in IGNORE_DIRS for part in f.parts)
]
for file_path in md_files:
content = file_path.read_text()
for raw_url in URL_RE.findall(content):
# Strip trailing Markdown/punctuation characters the regex may over-capture
# from link syntax like [text](https://url/) or **https://url)**
clean_url = raw_url.rstrip(")>*_`':.,;").split("#")[0]
urls.setdefault(clean_url, []).append(str(file_path))
if not urls:
print("✅ No external URLs found")
return 0
errors = []
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(check_url, url): url for url in urls}
for future in as_completed(futures):
url, ok, reason = future.result()
if not ok:
errors.extend(f"{f}: dead link → {url} ({reason})" for f in urls[url])
if errors:
print("❌ Dead links found:")
for e in sorted(errors):
print(f" - {e}")
# In non-strict mode (pre-commit), report but don't block the commit.
# Set LINK_CHECK_STRICT=1 (as CI does) to enforce failures.
return 1 if strict else 0
print(f"✅ All external URLs reachable ({len(urls)} checked)")
return 0
if __name__ == "__main__":
import os
sys.exit(main(strict=os.environ.get("LINK_CHECK_STRICT") == "1"))
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Validate Mermaid diagram syntax in Markdown files using mmdc."""
import json
import os
import re
import shutil
import subprocess # nosec B404
import sys
import tempfile
from pathlib import Path
IGNORE_DIRS = {".venv", "node_modules", ".git", "blog-posts", ".agents"}
def main() -> int:
if not shutil.which("mmdc"):
print(
"⚠ mmdc not found — skipping Mermaid validation (install @mermaid-js/mermaid-cli)"
)
return 0
errors = []
checked = 0
# On GitHub Actions Linux runners, Chrome/Puppeteer requires --no-sandbox.
# Write a temporary puppeteer config when MERMAID_PUPPETEER_NO_SANDBOX is set.
puppeteer_config_path = None
extra_args: list[str] = []
if os.environ.get("MERMAID_PUPPETEER_NO_SANDBOX") == "true":
with tempfile.NamedTemporaryFile(
suffix=".json", mode="w", delete=False
) as pcfg:
json.dump({"args": ["--no-sandbox", "--disable-setuid-sandbox"]}, pcfg)
puppeteer_config_path = pcfg.name
extra_args = ["-p", puppeteer_config_path]
md_files = [
f
for f in Path().rglob("*.md")
if not any(part in IGNORE_DIRS for part in f.parts)
]
try:
for file_path in md_files:
content = file_path.read_text()
blocks = re.findall(r"```mermaid\n(.*?)```", content, re.DOTALL)
for i, block in enumerate(blocks):
with tempfile.NamedTemporaryFile(
suffix=".mmd", mode="w", delete=False
) as tmp:
tmp.write(block)
tmp_path = tmp.name
out_path = str(Path(tmp_path).with_suffix(".svg"))
try:
result = subprocess.run( # nosec B603 B607
["mmdc", "-i", tmp_path, "-o", out_path, *extra_args],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
errors.append(
f"{file_path} (block {i + 1}): {result.stderr.strip()}"
)
else:
checked += 1
finally:
Path(tmp_path).unlink(missing_ok=True)
Path(out_path).unlink(missing_ok=True)
finally:
if puppeteer_config_path:
Path(puppeteer_config_path).unlink(missing_ok=True)
print(f"✅ Checked {checked} Mermaid diagram(s)")
if errors:
print("\n❌ Mermaid errors:")
for e in errors:
print(f" - {e}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())