diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index faa25b168..e7ba7cda5 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -4,7 +4,7 @@ "name": "costiash" }, "metadata": { - "description": "Always up-to-date Claude documentation at your fingertips — 574+ docs covering Claude Code CLI, API, Agent SDK, and more" + "description": "Always up-to-date Claude documentation at your fingertips. Content search, fuzzy matching, and auto-discovery — 574+ docs covering Claude Code CLI, API, Agent SDK, and more." }, "plugins": [ { diff --git a/.gitignore b/.gitignore index 8e767c74b..dcdfab2e6 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,13 @@ claude-docs-helper.sh # Upstream reference repository (local development only) upstream/ +# Source reference projects (local development only) +codebase-to-course-main/ + +# Generated HTML artifacts (courses, changelogs — local only) +*.html +!index.html + # Archive folder (legacy/orphaned scripts) archive/ @@ -97,7 +104,6 @@ archive/ docs/plans/ # Skill evaluation workspace (development artifacts) -plugin/skills/claude-docs-workspace/ plugin/skills/claude-docs/evals/ # ============================================================================ @@ -153,5 +159,5 @@ Pipfile.lock !docs/ !scripts/ !tests/ -!enhancements/ !.github/ +autoresearch-results.tsv diff --git a/CHANGELOG.md b/CHANGELOG.md index 508260bfe..87f283d90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,62 @@ All notable changes to the enhanced edition of claude-code-docs will be document The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.1.0] - 2026-03-28 + +### Added +- **`claude-docs-course/` interactive course skill**: Generates self-contained HTML courses on any Claude documentation topic + - 4-phase pipeline: Topic Discovery → Curriculum Design → Build (module by module) → Review & Open + - **Obsidian & Amber design theme**: Dark obsidian backgrounds, warm amber accents, Instrument Serif + Outfit typography, grain textures, glass-morphism effects + - `references/design-system.md` — Complete CSS design tokens for the Obsidian & Amber theme + - `references/interactive-elements.md` — 18 interactive element patterns including Protocol Conversations, code translations, quizzes, data flow animations, glossary tooltips + - `examples/course-from-docs.md` — Worked example for hooks course generation + - Courses saved to `~/.claude-code-docs/courses/.html` +- **`claude-docs-changelog/` report skill**: Generates HTML changelog reports of recent documentation changes + - Discovers changes via git history, categorizes by doc type, summarizes key updates + - Each entry includes a "Create Course" button that copies `/docs --course ` to clipboard + - Obsidian & Amber themed to match courses + - `examples/changelog-report.md` — Worked example +- **Post-response course prompt**: After every docs response, an emphasized prompt invites users to generate an interactive course on the topic +- **`/docs --course `** route: Direct course generation via the `/docs` command +- **`/docs --report`** route: Generate HTML changelog with configurable timeframe (default: 7 days) + +### Changed +- **`/docs` command** expanded: Now routes to 4 skills (search, validate, course, changelog) + inline git log +- **README.md**: Added "Interactive Courses" and "Changelog Reports" sections with usage examples +- **CLAUDE.md**: Updated plugin structure, routing table, and key files for new skills +- **CONTRIBUTING.md**: Updated for 4-skill architecture +- **`.gitignore`**: Added `codebase-to-course-main/` and generated HTML exclusions + +## [1.0.0] - 2026-03-28 + +### Breaking Changes +- **Plugin is now the primary (and only recommended) install path** — `install.sh` is now a migration wrapper that guides users to plugin install +- **Legacy helper scripts no longer user-facing** — `claude-docs-helper.sh` and the Python lookup module are now CI-only; plugin skills handle all user-facing search + +### Added +- **`claude-docs/` search skill**: Enhanced search with 4-tier strategy (direct lookup, scoped search, content search, fuzzy matching) + - `scripts/content-search.sh` — Full-text keyword search using `.search_index.json` or grep fallback + - `scripts/fuzzy-search.sh` — Token-based fuzzy filename matching + - `examples/` — 3 worked examples (direct lookup, semantic search, cross-context disambiguation) +- **`claude-docs-validate/` health check skill**: Documentation freshness and URL reachability checks + - `scripts/validate-paths.sh` — Parallel HTTP HEAD checks with `--quick` mode + - `examples/` — Validation workflow example +- **Zero Python dependency for users** — All plugin features use shell scripts only; Python is CI-only + +### Changed +- **`/docs` command** rewritten as lean router (~40 lines) delegating to skills +- **`install.sh`** rewritten as migration wrapper (~100 lines) routing to plugin install +- **`uninstall.sh`** simplified to plugin uninstall instructions +- **CLAUDE.md** streamlined — removed ~350 lines of search strategy (now lives in skill SKILL.md) +- **README.md** updated — plugin-first, script install moved to "Legacy" section +- **UNINSTALL.md** simplified to plugin-only primary path +- **CONTRIBUTING.md** updated for plugin-first development workflow + +### Removed +- `plugin/skills/claude-docs-workspace/` — Stale Phase 2 eval artifacts (was gitignored, not in repo) +- User-facing Python search (replaced by shell scripts in plugin skills) +- Legacy install.sh functionality (779 lines → 100 lines) + ## [0.6.0] - 2026-02-28 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index a9f59c0a1..c833f3708 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,398 +16,62 @@ This repository contains local copies of Claude documentation from multiple Anth The docs are periodically updated via GitHub Actions with safeguards to prevent mass deletion. -## Architecture: Single Installation with Optional Python Features +## Architecture: Plugin-Based Documentation System -This repository uses a **graceful degradation** approach: +This repository delivers documentation via a **Claude Code plugin**. The plugin provides: -**Installation** (always the same): -- Documentation paths tracked in manifest (6 categories) -- Documentation files downloaded -- Python scripts for enhanced features -- Full test suite (303 tests) and GitHub workflows +- **`/docs` command** — Routes queries to the appropriate skill +- **`claude-docs/` skill** — Auto-discovery + search (content search, fuzzy matching, direct lookups) +- **`claude-docs-validate/` skill** — Documentation health checks and freshness validation +- **SessionStart hook** — Auto-updates docs via `git pull` on each session start -**Runtime Features** (Python-dependent): -- **Without Python 3.9+**: Basic documentation reading via shell scripts -- **With Python 3.9+**: Full-text search, path validation, fuzzy matching, auto-regeneration +### Plugin Structure -There is NO separate "standard mode installation" - the full repository is always installed. Python features simply activate when Python 3.9+ is available. - -## For /docs Command - AI-Powered Semantic Search - -**IMPORTANT**: The `/docs` command is **AI-powered** and leverages Claude's semantic understanding instead of primitive keyword matching. - -When responding to /docs commands: - -1. **Read AI Instructions**: `~/.claude/commands/docs.md` contains comprehensive AI instructions on how to: - - Analyze user intent semantically - - Route to appropriate helper functions - - Present results naturally with context - -2. **Semantic Analysis**: Use your language understanding to classify user intent: - - **Direct lookup**: User names a specific topic (e.g., `/docs hooks`) - - **Information search**: User asks questions (e.g., `/docs what are best practices for SDK in Python?`) - - **Path discovery**: User wants to find available docs (e.g., `/docs show me all MCP documentation`) - - **Freshness check**: User wants update status (e.g., `/docs -t`) - - **What's new**: User wants recent changes (e.g., `/docs what's new`) - -3. **Intelligent Routing**: Based on semantic understanding, route to appropriate functions: - - `--search-content ""` for semantic information searches (requires Python 3.9+) - - `--search ""` for path discovery (requires Python 3.9+) - - `` for direct documentation lookups - - `-t` for freshness checks - - `"what's new"` for recent changes - -4. **Graceful Degradation**: The helper script automatically detects Python availability: - - **With Python 3.9+**: Full AI-powered search with content search, path search, validation - - **Without Python**: Basic documentation reading, explain limitations gracefully - -5. **Natural Presentation**: Don't dump raw tool output - present information naturally: - - Summarize search results with context - - Provide official documentation links - - Combine multiple sources when helpful - - Explain your routing decisions if uncertain - -**Example AI-Powered Workflow**: -``` -User: /docs what are the best practices and recommended workflows using Claude Agent SDK in Python? - -Your Analysis: -- User wants information (not a specific doc name) -- Key concepts: best practices, workflows, Agent SDK, Python -- Route to content search - -Your Actions: -1. Extract keywords: "best practices workflows Agent SDK Python" -2. Execute: ~/.claude-code-docs/claude-docs-helper.sh --search-content "best practices workflows Agent SDK Python" -3. Read matching documentation sections -4. Present naturally: "Based on the official documentation, here are the best practices..." -5. Include links to relevant docs - -Result: User gets semantic answer with documentation context, not raw file paths -``` - -## Intent-Driven Documentation Search - ENHANCED APPROACH - -**Philosophy**: Hide complexity from users. Synthesize aggressively. Minimize interaction. - -### Core Principles - -1. **Intent-driven, not path-driven** - Understand WHAT the user wants, not WHERE it might be located -2. **Content search over path matching** - Find relevant information even without exact path matches -3. **Synthesize by default** - Read multiple docs silently, present one unified answer -4. **Only ask when contexts are incompatible** - Different products with fundamentally different workflows - -### Category Labels (User-Facing) - -When presenting options to users, always use these user-friendly labels: - -| Internal Category | User-Facing Label | -|-------------------|-------------------| -| `claude_code` | Claude Code CLI | -| `agent_sdk` | Claude Agent SDK | -| `api_reference` | Claude API | -| `agents_and_tools` | Agents & Tools | -| `core_documentation` | Claude Documentation | -| `about_claude` | About Claude | -| `get_started` | Getting Started | -| `test_and_evaluate` | Testing & Evaluation | -| `prompt_library` | Prompt Library | -| `release_notes` | Release Notes | -| `resources` | Resources | - -**Why this matters**: Users think in product names ("I'm using Claude Agent SDK"), not internal category identifiers. - -### Ambiguity Resolution Strategy - -#### SYNTHESIZE (default behavior): - -**When**: Multiple documents in the same product context - -**Action**: -- Read ALL matching documents silently (no asking user which to read) -- Extract relevant sections related to query intent -- Synthesize one unified, coherent answer -- Cite all sources at the end - -**Example**: ``` -User: /docs hooks in agent sdk - -Search finds: -- /en/docs/agent-sdk/python.md (15 mentions of "hooks") -- /en/docs/agent-sdk/overview.md (3 mentions of "hooks") -- /en/docs/agent-sdk/plugins.md (8 mentions of "hooks") - -Decision: All in same context (Agent SDK) → SYNTHESIZE - -Action: -1. Read all three documents silently -2. Extract all hook-related content -3. Synthesize unified explanation - -Present: -"In the Claude Agent SDK, hooks provide intercept points in the agent lifecycle... - -[Unified explanation combining insights from all three sources] - -You can configure hooks in Python like this: -[Code example from python.md] - -Common use cases for hooks include: -[Use cases from overview.md] - -When integrating with plugins: -[Integration details from plugins.md] - -Sources: -• Agent SDK Python Guide: https://platform.claude.com/en/docs/agent-sdk/python -• Agent SDK Overview: https://platform.claude.com/en/docs/agent-sdk/overview -• Plugins Integration: https://platform.claude.com/en/docs/agent-sdk/plugins" +plugin/ +├── commands/docs.md # /docs command (lean router) +├── skills/ +│ ├── claude-docs/ # Search skill (auto-discovery) +│ │ ├── SKILL.md # Search strategy and synthesis rules +│ │ ├── manifest-reference.md # Category-to-label mapping (single source of truth) +│ │ ├── examples/ # Worked examples for Claude +│ │ └── scripts/ # content-search.sh, fuzzy-search.sh +│ ├── claude-docs-validate/ # Validation skill +│ │ ├── SKILL.md # Health check instructions +│ │ ├── examples/ # Worked examples +│ │ └── scripts/ # validate-paths.sh +│ └── claude-docs-course/ # Interactive course generator +│ ├── SKILL.md # Course generation workflow (Obsidian & Amber theme) +│ ├── references/ # design-system.md, interactive-elements.md +│ └── examples/ # Worked examples +└── hooks/ # SessionStart auto-sync ``` -**Never show**: "Found 3 documents about hooks, which do you want to read?" ❌ - -#### ASK (minimal - only for cross-context ambiguity): +Search intelligence lives in the skills, not in CLAUDE.md. See `plugin/skills/claude-docs/SKILL.md` for search strategy details. -**When**: Matches span fundamentally different product contexts with incompatible workflows +## For /docs Command -**Action**: -- Use AskUserQuestion tool -- Present options with user-friendly product labels -- Explain WHY contexts are different -- After selection → synthesize within chosen context +The `/docs` command is handled by the plugin's lean router at `plugin/commands/docs.md`. It delegates to: -**Example**: -``` -User: /docs skills - -Search finds matches in 3 different products: -- Claude Agent SDK (5 docs) - Building custom agent capabilities -- Claude Code CLI (2 docs) - Installing/running pre-built skills locally -- Claude API (7 docs) - Programmatic skill management endpoints - -Decision: Different products, incompatible workflows → ASK +- **`claude-docs` skill** — For all documentation lookups, questions, and searches +- **`claude-docs-validate` skill** — For freshness checks (`-t`) and health validation +- **`claude-docs-course` skill** — For interactive course generation (`--course `) +- **`claude-docs-changelog` skill** — For HTML changelog reports (`--report`) +- **Inline git log** — For "what's new" queries -Present: -"Skills exist in different Claude products with different purposes: +Search intelligence, synthesis rules, and URL generation live in `plugin/skills/claude-docs/SKILL.md`. Category mappings are in `plugin/skills/claude-docs/manifest-reference.md` (single source of truth). -○ 1. Claude Agent SDK - Build custom agent capabilities in Python/TypeScript - (For developers creating new agent skills) +## CI/CD Scripts (Python, repo-only) -○ 2. Claude Code CLI - Install and run pre-built skills locally - (For using existing skills in command-line interface) +The `scripts/` directory contains Python modules that run in GitHub Actions — they are **not** user-facing and are **not** installed with the plugin: -○ 3. Claude API - Programmatic skill management endpoints - (For API integration and automation) +- `scripts/fetcher/` — Fetches docs from Anthropic sitemaps (every 3 hours) +- `scripts/lookup/` — Path validation for CI checks (daily) +- `scripts/build_search_index.py` — Generates `.search_index.json` consumed by the plugin's content search +- `scripts/fetch_claude_docs.py` — Thin wrapper for fetcher package +- `scripts/lookup_paths.py` — Thin wrapper for lookup package -Which are you working with?" - -After user selects option 1 (Agent SDK): -→ Read all 5 Agent SDK docs about skills -→ Synthesize unified answer within that context -→ Present with sources -``` - -### Content Search Strategies - -**Priority order for finding relevant information**: - -1. **Explicit context in query** → Filter to that product first - - "hooks in agent sdk" → Search only agent-sdk category - - "cli memory features" → Search only claude_code category - - "api authentication" → Search only api_reference category - -2. **Keyword extraction** → Full-text content search across all docs - - "best practices for extended thinking" - - Extract: ["best practices", "extended thinking"] - - Search document content, not just paths - -3. **No exact path match** → Search document content anyway - - Query: "how do I use memory in agent sdk?" - - No `/agent-sdk/memory.md` path exists - - But `/agent-sdk/python.md` contains extensive memory documentation - - Find it via content search, read it, extract relevant sections - -### Decision Logic (Pseudo-code) - -```python -def handle_docs_query(user_query): - # Step 1: Extract intent and context from query - intent = extract_intent(user_query) # what they want to know - context = extract_context(user_query) # which product (if specified) - keywords = extract_keywords(user_query) - - # Step 2: Search with context filter if available - if context: # e.g., "in agent sdk", "cli hooks" - matches = search_content(keywords, category_filter=context) - else: - matches = search_content(keywords) # search everywhere - - # Step 3: Analyze results - if len(matches) == 0: - return suggest_alternatives() - - categories = get_product_contexts(matches) - - # Step 4: Decide action based on context analysis - if len(categories) == 1: - # ✅ Same product context → SYNTHESIZE - docs = read_all_matching_docs(matches) - answer = synthesize_unified_answer(docs, intent) - return present_with_sources(answer, matches) - - else: - # ❓ Different product contexts → ASK - options = format_product_options(categories) - selected_category = ask_user_question(options) - - # Then synthesize within selected context - filtered_matches = filter_by_category(matches, selected_category) - docs = read_all_matching_docs(filtered_matches) - answer = synthesize_unified_answer(docs, intent) - return present_with_sources(answer, filtered_matches) -``` - -### Example Workflows - -#### Example 1: Clear context, multiple docs (synthesize) -``` -User: /docs how do I use memory in the agent sdk? - -Analysis: -- Intent: how-to question about memory -- Context: agent sdk (explicitly stated) -- Type: implementation guidance - -Search: Content search in agent_sdk category for "memory" -Found: -- /en/docs/agent-sdk/python.md (12 mentions) -- /en/docs/agent-sdk/overview.md (5 mentions) -- /en/docs/agent-sdk/sessions.md (8 mentions) - -Decision: All same context (Agent SDK) → SYNTHESIZE - -Action: -1. Read all three docs silently -2. Extract memory-related sections -3. Combine into unified explanation - -Output: -"In the Claude Agent SDK, memory allows agents to maintain state across interactions... - -[Unified explanation from all three docs] -[Code examples from python.md] -[Architecture details from overview.md] -[Session persistence from sessions.md] - -Sources: -• Agent SDK Python Guide: https://platform.claude.com/en/docs/agent-sdk/python -• Agent SDK Overview: https://platform.claude.com/en/docs/agent-sdk/overview -• Sessions: https://platform.claude.com/en/docs/agent-sdk/sessions" -``` - -#### Example 2: Ambiguous context (ask, then synthesize) -``` -User: /docs memory - -Analysis: -- Intent: general query about memory -- Context: UNCLEAR (not specified) -- Type: general information - -Search: Content search across all categories for "memory" -Found in multiple product contexts: -- claude_code (2 docs) - CLI memory management features -- api_reference (3 docs) - Memory API endpoints -- core_documentation (4 docs) - Memory tool for agents - -Decision: Different products, different use cases → ASK - -Ask: -"Memory features exist in different Claude products: - -○ 1. Claude Code CLI - Local memory management for command-line interface - -○ 2. Claude API - Memory API endpoints for programmatic access - -○ 3. Claude Documentation - Memory tool for building agents - -Which are you interested in?" - -User selects: 1 (Claude Code CLI) - -Then: -→ Filter to claude_code category only -→ Read both CLI memory docs -→ Synthesize unified CLI memory answer -→ Present with sources -``` - -#### Example 3: Complex integration question (synthesize) -``` -User: /docs how do agent sdk skills interact with mcp servers? - -Analysis: -- Intent: integration/how-to -- Context: agent sdk (explicit) -- Keywords: ["skills", "mcp", "integration"] - -Search: Content search in agent_sdk for "skills" AND "mcp" -Found: -- /en/docs/agent-sdk/skills.md -- /en/docs/agent-sdk/mcp.md -- /en/docs/agent-sdk/plugins.md - -Decision: All same context (Agent SDK) → SYNTHESIZE - -Action: -1. Read all three docs -2. Find sections about skills+MCP integration -3. Synthesize unified integration guide - -Output: -"Agent SDK skills can interact with MCP servers in several ways: - -[Unified explanation showing integration patterns] -[Skill configuration examples from skills.md] -[MCP server setup from mcp.md] -[Plugin considerations from plugins.md] - -Sources: ..." -``` - -### Implementation Checklist - -- [ ] Content search is the default (not just path matching) -- [ ] Read multiple docs silently without asking user -- [ ] Synthesize aggressively within same product context -- [ ] Only ask when crossing product boundaries -- [ ] Extract context hints from query ("in agent sdk", "cli hooks") -- [ ] Cite all sources at the end -- [ ] Graceful degradation if Python unavailable (basic path matching + suggestions) - -## Python-Enhanced Features - -When Python 3.9+ is installed, these additional capabilities are available: - -- **Full-text search**: `--search "keyword"` searches across all documentation content -- **Category filtering**: `--category api` lists paths in specific categories -- **Path validation**: `--validate` checks documentation integrity -- **Active documentation**: Access to paths across 6 categories: - - API Reference (390 paths, 68.1%) - Includes multi-language SDK docs (Python, TypeScript, Go, Java, Kotlin, Ruby) - - Core Documentation (74 paths, 12.9%) - - Prompt Library (64 paths, 11.2%) - - Claude Code (43 paths, 7.5%) - - Release Notes (2 paths) - - Resources (0 paths) - -See `enhancements/` directory for comprehensive feature documentation and examples. +These require Python 3.9+ and are only executed in GitHub Actions workflows. ## Repository Structure @@ -415,53 +79,32 @@ See `enhancements/` directory for comprehensive feature documentation and exampl / ├── docs/ # Documentation files (.md format) │ ├── docs_manifest.json # File tracking manifest -│ └── .search_index.json # Full-text search index (Python-generated) -├── scripts/ -│ ├── claude-docs-helper.sh # Main helper (feature detection) -│ ├── claude-docs-helper.sh.template # Template for base functionality -│ ├── fetch_claude_docs.py # Thin wrapper for fetcher package -│ ├── lookup_paths.py # Thin wrapper for lookup package -│ ├── build_search_index.py # Index builder (Python) -│ ├── fetcher/ # Documentation fetching package -│ │ ├── __init__.py # Package exports -│ │ ├── config.py # Constants and safety thresholds -│ │ ├── manifest.py # Manifest file operations -│ │ ├── paths.py # Path conversion and categorization -│ │ ├── sitemap.py # Sitemap discovery and parsing -│ │ ├── content.py # Content fetching and validation -│ │ ├── safeguards.py # Safety checks (deletion prevention) -│ │ └── cli.py # Main entry point -│ └── lookup/ # Search and validation package -│ ├── __init__.py # Package exports -│ ├── config.py # Configuration constants -│ ├── manifest.py # Manifest loading utilities -│ ├── search.py # Search functionality -│ ├── validation.py # Path validation -│ ├── formatting.py # Output formatting -│ └── cli.py # Main entry point -├── plugin/ # Claude Code Plugin (v0.6.0) +│ └── .search_index.json # Full-text search index (CI-generated) +├── scripts/ # CI-only Python scripts +│ ├── fetch_claude_docs.py # Thin wrapper for fetcher +│ ├── lookup_paths.py # Thin wrapper for lookup +│ ├── build_search_index.py # Index builder +│ ├── fetcher/ # Documentation fetching package (8 modules) +│ └── lookup/ # Search and validation package (7 modules) +├── plugin/ # Claude Code Plugin (v1.1.0) │ ├── .claude-plugin/plugin.json # Plugin metadata -│ ├── commands/docs.md # /docs slash command -│ ├── skills/claude-docs/ # Auto-discovery Skill + manifest reference -│ └── hooks/ # SessionStart hook (auto-update docs) +│ ├── commands/docs.md # /docs slash command (lean router) +│ ├── skills/ +│ │ ├── claude-docs/ # Search skill + examples + scripts +│ │ ├── claude-docs-validate/ # Validation skill + examples + scripts +│ │ ├── claude-docs-course/ # Interactive course generator + references +│ │ └── claude-docs-changelog/ # Changelog report generator + examples +│ └── hooks/ # SessionStart hook (auto-update docs) ├── .claude-plugin/marketplace.json # Marketplace registration -├── paths_manifest.json # Active paths manifest (6 categories) +├── paths_manifest.json # Active paths manifest (auto-generated categories) ├── pyproject.toml # Python project configuration ├── CHANGELOG.md # Version history -├── archive/ # Archived/deprecated scripts (git-ignored) -├── enhancements/ # Feature documentation -│ ├── README.md # Overview -│ ├── FEATURES.md # Technical specs -│ ├── CAPABILITIES.md # Detailed capabilities -│ ├── EXAMPLES.md # Usage examples -│ └── TEST_EXECUTION_REPORT.md # Test execution results -├── tests/ # Test suite (303 tests, 303 passing) -├── reports/ # Coverage and test reports -├── install.sh # Installation script -├── uninstall.sh # Clean removal script -├── index.html # GitHub Pages landing page -└── CLAUDE.md # This file (AI context) - +├── tests/ # Test suite (CI-only, covers Python scripts) +├── reports/ # Coverage and test reports +├── install.sh # Migration wrapper (routes to plugin install) +├── uninstall.sh # Points to plugin uninstall +├── index.html # GitHub Pages landing page +└── CLAUDE.md # This file (AI context) ``` ## Key Files @@ -470,27 +113,29 @@ When working on this repository, read these files as needed (not auto-loaded to ### Plugin Files - `plugin/.claude-plugin/plugin.json` - Plugin metadata (version, hooks) -- `plugin/commands/docs.md` - `/docs` command implementation -- `plugin/skills/claude-docs/SKILL.md` - Auto-discovery Skill (triggers automatically for Claude topics) -- `plugin/skills/claude-docs/manifest-reference.md` - Category reference for the Skill +- `plugin/commands/docs.md` - `/docs` command (lean router) +- `plugin/skills/claude-docs/SKILL.md` - Search skill (auto-discovery, search strategy, synthesis rules) +- `plugin/skills/claude-docs/manifest-reference.md` - Category-to-label mapping (single source of truth) +- `plugin/skills/claude-docs/scripts/content-search.sh` - Full-text keyword search +- `plugin/skills/claude-docs/scripts/fuzzy-search.sh` - Fuzzy filename matching +- `plugin/skills/claude-docs/examples/` - Worked examples for search workflows +- `plugin/skills/claude-docs-validate/SKILL.md` - Validation skill instructions +- `plugin/skills/claude-docs-course/SKILL.md` - Interactive course generator (Obsidian & Amber theme) +- `plugin/skills/claude-docs-course/references/design-system.md` - Course visual design tokens +- `plugin/skills/claude-docs-course/references/interactive-elements.md` - HTML/CSS/JS patterns for course elements +- `plugin/skills/claude-docs-changelog/SKILL.md` - Changelog report generator (Obsidian & Amber theme) +- `plugin/skills/claude-docs-validate/scripts/validate-paths.sh` - HTTP reachability checks - `plugin/hooks/hooks.json` + `sync-docs.sh` - SessionStart hook (auto-update docs) - `.claude-plugin/marketplace.json` - Marketplace registration -### Core Files (Legacy Script Install) -- `install.sh` - Installation script -- `README.md` - User documentation -- `CONTRIBUTING.md` - Contribution guidelines -- `scripts/claude-docs-helper.sh` - Main entry point (feature detection) -- `uninstall.sh` - Clean removal - -### Python Features -- `scripts/fetch_claude_docs.py` - Thin wrapper for fetcher package (backwards compatible) -- `scripts/lookup_paths.py` - Thin wrapper for lookup package (backwards compatible) +### CI/CD Scripts (Python) +- `scripts/fetch_claude_docs.py` - Documentation fetcher entry point +- `scripts/lookup_paths.py` - Search & validation entry point - `scripts/fetcher/` - Documentation fetching package (8 modules) - `scripts/lookup/` - Search & validation package (7 modules) - `scripts/build_search_index.py` - Full-text search indexing -- `paths_manifest.json` - Active paths manifest (6 categories, ~573 paths) -- `tests/` - Test suite (303 tests) +- `paths_manifest.json` - Active paths manifest (auto-generated categories) +- `tests/` - Test suite (covers CI scripts) ### Automation - `.github/workflows/` - Auto-update workflows (runs every 3 hours) @@ -528,35 +173,25 @@ Files are named based on their source: ## Working on This Repository -**Critical Rule**: Changes must maintain graceful degradation - work with AND without Python. - ### Development Setup ```bash -# Install dependencies (uses uv) +# Install Python dependencies for CI scripts (uses uv) uv sync --group dev ``` -### Feature Detection -The helper script checks Python availability at runtime: -```bash -if command -v python3 &> /dev/null && [ -f "$SCRIPTS_DIR/lookup_paths.py" ]; then - # Python features available - use enhanced search/validation -else - # Python not available - use basic shell features only -fi -``` - ### Testing ```bash -# Test basic features (always works) -./scripts/claude-docs-helper.sh hooks +# Test plugin search scripts manually +DOCS_DIR=./docs ./plugin/skills/claude-docs/scripts/content-search.sh "hooks" +DOCS_DIR=./docs ./plugin/skills/claude-docs/scripts/fuzzy-search.sh "agent sdk" +DOCS_DIR=./docs ./plugin/skills/claude-docs-validate/scripts/validate-paths.sh --quick -# Test Python features (requires Python 3.9+) +# Test CI Python scripts python3 scripts/lookup_paths.py --search "mcp" pytest tests/ -v -# Run full test suite -pytest tests/ -q # Should see: 303 passed +# Run full CI test suite +pytest tests/ -q ``` ## Upstream Compatibility @@ -564,5 +199,4 @@ pytest tests/ -q # Should see: 303 passed This enhanced edition maintains compatibility with upstream (ericbuess/claude-code-docs): - Same installation location (~/.claude-code-docs) - Same `/docs` command interface -- Python features are additive, not breaking -- Works without Python (graceful degradation) +- Plugin features are additive, not breaking diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be7e1ca33..e982feb3f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,19 +4,19 @@ Thank you for contributing to the Enhanced Claude Code Documentation Mirror! ## Project Philosophy -This project extends [ericbuess/claude-code-docs](https://github.com/ericbuess/claude-code-docs) with optional Python features: +This project extends [ericbuess/claude-code-docs](https://github.com/ericbuess/claude-code-docs) as a native Claude Code plugin: -**Core Principle: Graceful Degradation** -- Single installation (paths tracked across 6 categories + Python scripts) -- Python features activate only when Python 3.9+ is available -- Everything works without Python (basic `/docs` command) -- No separate "modes" - just feature detection at runtime +**Core Principle: Plugin-First Architecture** +- All user-facing features delivered via Claude Code plugin (skills, commands, hooks) +- Shell scripts in skills provide search capabilities — zero Python dependency for users +- Python modules in `scripts/` are CI-only (fetching docs, building search index, validation) +- Single installation path: plugin marketplace **Design Goals:** -1. **Honesty**: Accurate claims about what we deliver (paths tracked in manifest, files downloaded) -2. **Simplicity**: One installation, automatic feature detection -3. **Compatibility**: Works with upstream, same `/docs` interface -4. **Testing**: All changes tested (303 tests) +1. **Zero dependencies**: Plugin works with just Claude Code — no Python, jq, or curl required on user machines +2. **Skill-based search**: Content search and fuzzy matching via shell scripts in plugin skills +3. **CI integrity**: Python scripts continue powering GitHub Actions workflows unchanged +4. **Testing**: CI test suite covers Python modules; plugin skills tested manually ## Repository URL Strategy @@ -81,36 +81,35 @@ git remote add upstream https://github.com/costiash/claude-code-docs.git ## Development Workflows -### For Shell Scripts +### For Plugin Skills -Working on installation, helper scripts, or core functionality: +Working on search skills, commands, or hooks: ```bash -# No Python setup needed cd claude-code-docs -# Test installation -./install.sh - -# Test basic commands -~/.claude-code-docs/claude-docs-helper.sh hooks -~/.claude-code-docs/claude-docs-helper.sh -t -~/.claude-code-docs/claude-docs-helper.sh what's new +# Test search scripts manually +DOCS_DIR=./docs ./plugin/skills/claude-docs/scripts/content-search.sh "hooks" +DOCS_DIR=./docs ./plugin/skills/claude-docs/scripts/fuzzy-search.sh "agent sdk" +DOCS_DIR=./docs ./plugin/skills/claude-docs-validate/scripts/validate-paths.sh --quick -# Test uninstall -./uninstall.sh +# Test the plugin in Claude Code +# Install from local source: +/plugin install claude-docs@/path/to/claude-code-docs/plugin ``` **Files to work on:** -- `install.sh` - Installation script -- `uninstall.sh` - Removal script -- `scripts/claude-docs-helper.sh` - Main entry point -- `.github/workflows/` - GitHub Actions -- `docs/` - Documentation files +- `plugin/commands/docs.md` — `/docs` command router +- `plugin/skills/claude-docs/SKILL.md` — Search skill instructions +- `plugin/skills/claude-docs/scripts/` — Search shell scripts +- `plugin/skills/claude-docs-validate/` — Validation skill +- `plugin/skills/claude-docs-course/` — Interactive course generator (Obsidian & Amber theme) +- `plugin/skills/claude-docs-changelog/` — Changelog report generator +- `plugin/hooks/` — SessionStart sync hook -### For Python Features +### For CI/CD Scripts (Python) -Working on search, validation, or Python tools: +Working on documentation fetching, search indexing, or CI validation (these run in GitHub Actions, not on user machines): ```bash # Setup Python virtual environment @@ -120,12 +119,8 @@ source .venv/bin/activate # Windows: .venv\Scripts\activate # Install in development mode pip install -e ".[dev]" -# Test Python commands -~/.claude-code-docs/claude-docs-helper.sh --search "mcp" -~/.claude-code-docs/claude-docs-helper.sh --validate - # Run tests (REQUIRED before submitting PR) -pytest tests/ -v # Should see: 303 passed +pytest tests/ -v # All tests must pass # Test specific changes python scripts/lookup_paths.py "your test query" @@ -136,7 +131,7 @@ python scripts/fetch_claude_docs.py --help - `scripts/fetch_claude_docs.py` - Documentation fetcher with auto-regeneration - `scripts/lookup_paths.py` - Search & validation - `scripts/build_search_index.py` - Full-text search indexing -- `tests/` - Test suite (303 tests) +- `tests/` - Test suite (run `pytest --collect-only -q` to see current count) ## Code Standards @@ -231,18 +226,20 @@ All documentation files follow a consistent naming convention: ### Format ``` -en__section__subsection__page.md -# OR (for Claude Code docs) -docs__en__page.md +# Claude Code CLI docs (from code.claude.com) +claude-code__.md + +# Platform docs (from platform.claude.com) +docs__en__
__.md ``` ### Examples -| URL Path | Filename | -|----------|----------| -| `/en/docs/claude-code/hooks` | `en__docs__claude-code__hooks.md` | -| `/docs/en/hooks` | `docs__en__hooks.md` | -| `/en/api/overview` | `en__api__overview.md` | +| Source URL | Filename | +|------------|----------| +| `code.claude.com/docs/en/hooks` | `claude-code__hooks.md` | +| `platform.claude.com/en/docs/api/messages/create` | `docs__en__api__messages__create.md` | +| `platform.claude.com/en/docs/agent-sdk/python` | `docs__en__agent-sdk__python.md` | ### Rules @@ -251,28 +248,26 @@ docs__en__page.md 3. **No special characters** except alphanumeric, hyphens, underscores 4. **Keep `.md` extension** 5. **Place in `docs/` directory** +6. **`claude-code__` prefix** for CLI docs, **`docs__en__` prefix** for platform docs ## Testing Requirements -### Manual Testing (Shell Scripts) +### Manual Testing (Plugin Skills) -Test on both macOS and Linux: +Test search scripts on both macOS and Linux: ```bash -# Installation -./install.sh -~/.claude-code-docs/claude-docs-helper.sh --help +# Content search +DOCS_DIR=./docs ./plugin/skills/claude-docs/scripts/content-search.sh "hooks" -# Core functionality -~/.claude-code-docs/claude-docs-helper.sh hooks -~/.claude-code-docs/claude-docs-helper.sh -t -~/.claude-code-docs/claude-docs-helper.sh what's new +# Fuzzy search +DOCS_DIR=./docs ./plugin/skills/claude-docs/scripts/fuzzy-search.sh "agent sdk" -# Updates -cd ~/.claude-code-docs && git pull +# Validation (quick mode) +DOCS_DIR=./docs ./plugin/skills/claude-docs-validate/scripts/validate-paths.sh --quick -# Uninstall -./uninstall.sh +# Or install the plugin locally and test via /docs command +/plugin install claude-docs@/path/to/claude-code-docs/plugin ``` ### Automated Testing (Python Features) @@ -285,16 +280,16 @@ cd ~/.claude-code-docs && git pull pytest # Run specific test suites -pytest tests/unit/ # 82 unit tests -pytest tests/integration/ # 36 integration tests -pytest tests/validation/ # 56 validation tests +pytest tests/unit/ +pytest tests/integration/ +pytest tests/validation/ -# Check coverage (target: 78%+) +# Check coverage pytest --cov=scripts --cov-report=html pytest --cov=scripts --cov-report=term # Run specific test file -pytest tests/unit/test_lookup_paths.py -v +pytest tests/unit/test_lookup_functions.py -v # Verbose output pytest -v @@ -330,8 +325,7 @@ def test_search_paths_with_limit(): ``` **Current test status:** -- Total: 303 tests -- Passing: 303 (100%) +Run `pytest tests/ -v` — all tests must pass before submitting a PR. ## Pull Request Guidelines @@ -386,10 +380,12 @@ Fixes #123 | Feature Type | Documentation Required | |-------------|----------------------| -| Shell scripts | Update README.md | -| Python features | Update docstrings + README.md | -| New commands | Update command documentation | +| Plugin skills | Update SKILL.md, add/update examples | +| Course/changelog design | Update `references/design-system.md` or `interactive-elements.md` | +| Shell scripts | Update relevant SKILL.md | +| Python CI scripts | Update docstrings | | Architecture changes | Update CLAUDE.md | +| User-facing changes | Update README.md | ## Release Process @@ -414,7 +410,7 @@ git push origin v0.x.x **When to release:** - New Python features complete -- All tests passing (303/303) +- All tests passing (`pytest tests/`) - Documentation updated **Process:** diff --git a/README.md b/README.md index 7860326e3..1fcb69f70 100644 --- a/README.md +++ b/README.md @@ -39,25 +39,20 @@ That's it. On your next session Claude will automatically: - **`/docs` command** — Look up any topic: `/docs hooks`, `/docs extended thinking`, `/docs Agent SDK sessions` - **Auto-discovery Skill** — Claude proactively searches docs when you ask about Claude Code, the API, SDKs, or prompt engineering. No `/docs` prefix needed. +- **Interactive Courses** — Turn any Claude topic into a stunning, self-contained HTML course with animated diagrams, protocol conversations, quizzes, and code translations. Just say "create a course on hooks" or run `/docs --course `. - **Session-start auto-updates** — Docs stay fresh automatically. No cron jobs, no manual pulls. +- **Content search** — Shell-based full-text search and fuzzy filename matching, no Python needed - **Zero dependencies** — No Python, no jq, no curl. Just Claude Code with plugin support. -## Alternative: Script Install +## Legacy: Script Install (Migration) -For environments without plugin support, or if you prefer manual control: +For environments without plugin support, the install script clones documentation locally: ```bash curl -fsSL https://raw.githubusercontent.com/costiash/claude-code-docs/main/install.sh | bash ``` -This provides the `/docs` command only (no auto-discovery Skill). Python 3.9+ enables advanced features like full-text content search and path validation. - -**CI/CD or non-interactive environments:** -```bash -CLAUDE_DOCS_AUTO_INSTALL=yes curl -fsSL https://raw.githubusercontent.com/costiash/claude-code-docs/main/install.sh | bash -``` - -**Requirements:** macOS 12+ or Linux, git, jq, curl. Python 3.9+ optional. +If Claude Code is detected, the script will guide you to install the plugin instead. Without Claude Code, it falls back to `git clone` for basic documentation access. ## Team / Organization Adoption @@ -81,6 +76,42 @@ Auto-prompt every team member to install the plugin by adding this to your proje Commit this file to your repository. When a team member trusts the project folder, they'll be prompted to install the marketplace and plugin automatically — no manual setup needed. +## Interactive Courses — Learn Claude by Doing + +> **This isn't just a docs mirror anymore.** Ask about any Claude topic and get a beautifully crafted, interactive HTML course — complete with animated protocol diagrams, hands-on quizzes, code-with-English translations, and a stunning dark Obsidian & Amber visual theme. One self-contained file, zero setup, opens right in your browser. + +```bash +/docs --course hooks # Generate a course on Claude Code hooks +/docs --course tool use # Deep dive into the Tool Use API +/docs --course prompt caching # Master caching with visual explanations +``` + +Or just ask naturally after any docs response — Claude will offer to create a course on whatever you just looked up. + +**What you get:** +- **4-7 scroll-based modules** with progressive learning arc +- **Protocol Conversations** — animated chat-style visualizations showing how Client, API, Claude, and tools actually exchange messages +- **Code translations** — real API examples from the docs with line-by-line plain English explanations +- **Quizzes that test application** — "What would you use for this scenario?" not "Define this term" +- **Glossary tooltips** on every Claude-specific term +- **Obsidian & Amber theme** — dark, atmospheric design with Instrument Serif headings, warm amber accents, grain textures, and glass effects. Not your typical tutorial. + +Courses are saved to `~/.claude-code-docs/courses/` so you can revisit or share them with your team. + +### Changelog Reports + +Stay on top of what's changing in Claude's documentation. Generate a visual HTML report of recent doc updates — grouped by category, with summaries and key highlights: + +```bash +/docs --report # Last 7 days of changes +/docs --report 24h # Last 24 hours +/docs --report 30d # Last 30 days +``` + +Each entry in the report includes a **"Create Course"** button. Click it to copy a course generation command to your clipboard — paste it into Claude Code to instantly deep-dive into any topic that caught your eye. + +--- + ## Usage ### Direct Lookups @@ -89,6 +120,8 @@ Commit this file to your repository. When a team member trusts the project folde /docs hooks # Claude Code hooks /docs mcp # MCP server configuration /docs agent sdk python # Agent SDK Python guide +/docs --course hooks # Generate an interactive course on hooks +/docs --report # HTML changelog of recent doc changes /docs -t # Check freshness and pull updates /docs what's new # Recent documentation changes ``` @@ -116,7 +149,7 @@ Claude recognizes this is a documentation question and automatically reads the r ## Documentation Coverage -Documentation files across 11 categories, updated every 3 hours: +Documentation files across multiple categories, updated every 3 hours: - **API Reference** — Messages API, Admin API, multi-language SDKs (Python, TypeScript, Go, Java, Kotlin, Ruby) - **Agent SDK** — Python and TypeScript SDK guides, sessions, hooks, custom tools @@ -172,6 +205,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for architecture overview, development se ## Acknowledgments - **[Eric Buess](https://github.com/ericbuess)** — Creator of the [original claude-code-docs](https://github.com/ericbuess/claude-code-docs) +- **[zarazhangrui/codebase-to-course](https://github.com/zarazhangrui/codebase-to-course)** — Inspiration for the interactive course generator skill - **[Anthropic](https://www.anthropic.com/)** — For Claude Code and the documentation ## License diff --git a/UNINSTALL.md b/UNINSTALL.md index a87ab791d..21e14631b 100644 --- a/UNINSTALL.md +++ b/UNINSTALL.md @@ -1,95 +1,44 @@ # Uninstalling Claude Code Documentation Mirror -## Quick Uninstall +## Plugin Uninstall (Recommended) -### Plugin Install +If you installed via the Claude Code plugin: -If you installed via `/plugin install`: ```bash /plugin uninstall claude-docs@claude-code-docs ``` -### Script Install (v0.3+, installed at ~/.claude-code-docs) - -From anywhere, run: +To also remove the local documentation files: ```bash -~/.claude-code-docs/uninstall.sh +rm -rf ~/.claude-code-docs ``` -Or use the docs command: -```bash -/docs uninstall -``` +## Legacy Script Uninstall -### For v0.2 or older (custom installation locations) +If you have an older script-based installation (v0.6.0 or earlier): -Navigate to your installation directory and run: ```bash -./uninstall.sh +~/.claude-code-docs/uninstall.sh ``` -## What Gets Removed - -The uninstaller will remove: +This removes: +1. Legacy `/docs` command from `~/.claude/commands/docs.md` (if present) +2. Legacy hooks from `~/.claude/settings.json` (if present) +3. Optionally, the `~/.claude-code-docs/` directory -1. **The /docs command** from `~/.claude/commands/docs.md` -2. **Any legacy hooks** from `~/.claude/settings.json` (if present from older versions) -3. **The installation directory**: - - v0.3+: `~/.claude-code-docs` - - v0.2 or older: wherever you installed it +## Manual Cleanup -## Manual Uninstall - -If you prefer to uninstall manually: - -### 1. Remove the command file: ```bash +# Remove legacy command (if present) rm -f ~/.claude/commands/docs.md -``` - -### 2. Remove any legacy hooks from Claude settings (if present): -If you installed an older version (v0.4.1 or earlier), check `~/.claude/settings.json` and remove any PreToolUse hooks that reference claude-code-docs. Current versions (v0.4.2+) do not install hooks. -### 3. Remove the installation directory: - -For v0.3+: -```bash +# Remove local documentation rm -rf ~/.claude-code-docs ``` -For older versions: -```bash -rm -rf /path/to/your/claude-code-docs -``` - -## Multiple Installations - -If you have multiple installations (e.g., from testing different versions), the uninstaller will notify you about other locations it finds. You'll need to remove each one separately. - -To find all installations: -```bash -find ~ -name "claude-code-docs" -type d 2>/dev/null | grep -v ".claude-code-docs" -``` - -## Backup Created - -The uninstaller may create a backup of your Claude settings at `~/.claude/settings.json.backup` before removing hooks, just in case. - -## Complete Removal - -After uninstalling, there should be no traces left except: -- The backup file `~/.claude/settings.json.backup` (if hooks were removed) -- Any custom files you added to the installation directory - ## Reinstalling -**Plugin install (recommended):** ```bash /plugin marketplace add costiash/claude-code-docs /plugin install claude-docs@claude-code-docs ``` - -**Script install:** -```bash -curl -fsSL https://raw.githubusercontent.com/costiash/claude-code-docs/main/install.sh | bash -``` diff --git a/enhancements/CAPABILITIES.md b/enhancements/CAPABILITIES.md deleted file mode 100644 index 3e5416424..000000000 --- a/enhancements/CAPABILITIES.md +++ /dev/null @@ -1,325 +0,0 @@ -# Enhanced Documentation Capabilities - -This document describes the actual capabilities of the enhanced edition of claude-code-docs, based on the fetched documentation from docs.anthropic.com. - -## Documentation Coverage - -### Path Statistics - -The enhanced edition provides comprehensive coverage of Anthropic's documentation: - -- **Total Paths Tracked**: 573 documentation paths (in `paths_manifest.json`) -- **Files Downloaded**: 571 actual .md files -- **Auto-Discovery**: Paths discovered from official sitemaps, regenerated automatically - -### Category Breakdown - -Documentation is organized into 6 primary categories: - -1. **API Reference** (377 paths - 65.8%) - - Complete API documentation - - Administration API (users, workspaces, API keys, invites) - - Agent SDK documentation - - Multi-language SDK docs (Python, TypeScript, Go, Java, Kotlin, Ruby) - - Messages API, Files API, Batch processing APIs, Skills API - -2. **Core Documentation** (82 paths - 14.3%) - - About Claude (models, pricing, security, compliance) - - Build with Claude (prompt engineering, text generation, streaming) - - Test and Evaluate (guardrails, success metrics, testing) - - Use case guides and examples - - Getting started and quickstart guides - -3. **Prompt Library** (65 paths - 11.3%) - - Coding assistants (code consultant, bug buster, function fabricator) - - Data processing (CSV converter, data organizer, spreadsheet sorcerer) - - Writing tools (grammar genie, prose polisher, memo maestro) - - Creative prompts (storytelling sidekick, pun-dit, cosmic keystrokes) - - Professional tools (meeting scribe, career coach, interview crafter) - -4. **Claude Code** (46 paths - 8.0%) - - CLI-specific documentation - - IDE integrations (VS Code, JetBrains) - - CI/CD integrations (GitHub Actions, GitLab CI/CD) - - Cloud platforms (Amazon Bedrock, Google Vertex AI) - - Advanced features (MCP, hooks, plugins, skills) - - Configuration and troubleshooting - -5. **Release Notes** (2 paths - 0.3%) - - API release notes - - System prompts updates - -6. **Resources** (1 path - 0.2%) - - Resources overview - -## Search Capabilities - -### Path Search - -**Command**: `--search ` - -Fuzzy search across all 573 documentation paths with intelligent matching: - -- **Pattern matching**: Finds paths containing search terms -- **Fuzzy matching**: Suggests similar paths when exact match not found -- **Relevance ranking**: Orders results by relevance -- **Category filtering**: Can filter by documentation category -- **Multiple matches**: Shows all relevant results - -**Example queries**: -- `--search mcp` - Finds MCP-related documentation -- `--search "claude code"` - Finds Claude Code specific docs -- `--search api` - Finds API reference pages -- `--search hooks` - Finds hook configuration and guides - -### Full-Text Search - -**Command**: `--search-content ` - -Searches within documentation content (not just path names): - -- **Content indexing**: Searches actual documentation text -- **Keyword extraction**: Finds relevant documents by content keywords -- **Stop word filtering**: Ignores common words for better results -- **Ranking**: Orders results by relevance to query - -**Implementation**: -- Pre-built search index: `docs/.search_index.json` -- Index builder: `scripts/build_search_index.py` -- Index size: ~45KB for 571 documents -- Search speed: <100ms per query - -## Validation Features - -### Path Validation - -**Command**: `--validate` - -Validates HTTP reachability of all documentation paths: - -- **Reachability testing**: Tests each path against docs.anthropic.com -- **Parallel validation**: Uses ThreadPoolExecutor for fast validation -- **Progress tracking**: Shows real-time validation progress -- **Detailed reports**: Generates comprehensive validation reports -- **Broken link detection**: Identifies and reports unreachable paths - -**Validation metrics**: -- Average validation time: ~60 seconds for 573 paths -- Concurrent requests: Configurable (default: 10) -- Request timeout: 10 seconds per path -- Error handling: Retries with exponential backoff - -### Validation Reports - -Validation generates detailed reports including: - -- Total paths validated -- Successful validations (HTTP 200) -- Failed validations with error codes -- Alternative suggestions for broken links -- Timestamp and metadata - -## Advanced Features - -### Change Detection - -**Technology**: SHA256-based hashing - -Efficiently updates only changed documentation: - -- Calculates content hash for each document -- Compares with stored hashes in manifest -- Fetches only documents that changed -- Maintains last_updated timestamps - -**Benefits**: -- Faster updates (only fetch what changed) -- Reduced bandwidth usage -- Lower API load -- Better performance - -### Batch Operations - -**Script**: `scripts/main.py` - -Advanced fetching with enterprise features: - -- **Batch fetching**: Update all 573 paths efficiently -- **Category updates**: Update specific categories only -- **Rate limiting**: 0.5s delay between requests -- **Retry logic**: Exponential backoff on failures -- **Progress tracking**: Real-time progress indicators -- **Error recovery**: Continues on individual failures - -**Performance**: -- Fetch speed: ~32 seconds per 100 paths -- Memory usage: ~35 MB -- Success rate: >99% - -### Path Management - -**Tools included**: - -1. **Extract Paths** (`scripts/extract_paths.py`) - - Extract paths from sitemap - - Clean duplicates and artifacts - - Categorize by documentation section - - Validate path format - -2. **Clean Manifest** (`scripts/clean_manifest.py`) - - Remove broken paths - - Update reachability status - - Generate validation reports - - Maintain manifest integrity - -3. **Update Sitemap** (`scripts/update_sitemap.py`) - - Generate hierarchical trees - - Update search index - - Maintain compatibility - - Export path lists - -## Technical Implementation - -### Python Architecture - -**Core scripts**: - -- `main.py` (662 lines) - Enhanced documentation fetcher -- `lookup_paths.py` (597 lines) - Search and validation -- `update_sitemap.py` (504 lines) - Sitemap management -- `build_search_index.py` - Full-text search indexer - -**Dependencies**: -- Python 3.9+ -- requests library -- Standard library modules (json, pathlib, concurrent.futures) - -### Data Structures - -**paths_manifest.json**: -```json -{ - "metadata": { - "generated_at": "timestamp", - "total_paths": 573, - "source": "sitemap_discovery", - "last_regenerated": "timestamp" - }, - "categories": { - "api_reference": [...], - "core_documentation": [...], - "prompt_library": [...], - "claude_code": [...], - ... - } -} -``` - -**docs_manifest.json**: -```json -{ - "path/to/doc.md": { - "hash": "sha256_hash", - "last_updated": "timestamp", - "original_md_url": "https://...", - "original_url": "https://..." - } -} -``` - -### Integration - -Enhanced features integrate seamlessly: - -- **Detection**: Automatic feature detection at runtime -- **Fallback**: Graceful degradation to standard mode -- **Compatibility**: Works with existing upstream scripts -- **Testing**: Comprehensive test suite (577 tests) - -## Performance Characteristics - -### Search Performance - -- **Path search**: ~90ms average -- **Content search**: <100ms per query -- **Index build**: ~2 seconds for 571 documents -- **Index size**: ~45KB (minimal disk usage) - -### Fetch Performance - -- **Speed**: ~32 seconds per 100 paths -- **Memory**: ~35 MB typical usage -- **Throughput**: ~3 documents per second -- **Scalability**: Linear scaling to thousands of paths - -### Validation Performance - -- **Full validation**: ~60 seconds for 573 paths -- **Parallel requests**: 10 concurrent by default -- **Success rate**: >99% -- **Resource usage**: Low CPU, minimal memory - -## Feature Availability - -| Capability | Without Python | With Python 3.9+ | -|-----------|----------------|------------------| -| Documentation paths tracked | 573 | 573 | -| Files downloaded | 571 | 571 | -| Search method | Topic name via AI | Path + content + AI | -| Validation | None | HTTP reachability | -| Update method | Git pull | Auto-fetch + validation | -| Category support | Yes (6 categories) | Yes (6 categories) | -| Testing | N/A | 294 tests | - -## Use Cases - -### For Users - -1. **Finding documentation**: Fast search across all Anthropic docs -2. **Staying updated**: Automatic updates when docs change -3. **Offline access**: Local copy of all documentation -4. **Category browsing**: Browse by topic area - -### For Developers - -1. **Integration testing**: Validate doc paths in CI/CD -2. **Documentation audits**: Check for broken links -3. **Content analysis**: Search documentation programmatically -4. **Custom tooling**: Build on top of path manifest - -### For Contributors - -1. **Path discovery**: Find new documentation to mirror -2. **Quality assurance**: Validate all paths work -3. **Coverage analysis**: Track documentation coverage -4. **Update automation**: Automated fetching and validation - -## Future Capabilities - -Potential enhancements being considered: - -- Search ranking improvements -- Additional documentation sources -- Version tracking and history -- API for programmatic access -- Enhanced categorization -- Related document suggestions - -## Limitations - -Current limitations to be aware of: - -- Requires Python 3.9+ for enhanced features -- Requires internet connection for validation -- Rate limiting applies to batch operations -- Search quality depends on indexed content -- Some dynamically generated content may not be captured - -## Getting Help - -For questions about capabilities: - -1. Check this document for feature details -2. See `EXAMPLES.md` for usage examples -3. See `README.md` for installation help -4. Review test suite for advanced usage patterns diff --git a/enhancements/EXAMPLES.md b/enhancements/EXAMPLES.md deleted file mode 100644 index d3dd3aa68..000000000 --- a/enhancements/EXAMPLES.md +++ /dev/null @@ -1,574 +0,0 @@ -# Enhanced Features Usage Examples - -This guide provides practical examples for using the enhanced documentation features in claude-code-docs. - -## Table of Contents - -1. [Using Enhancements in Claude Code](#using-enhancements-in-claude-code) -2. [Using the /docs Command](#using-the-docs-command) -3. [Command-Line Reference](#command-line-reference) - -## Using Enhancements in Claude Code - -The enhanced edition is designed primarily for use within Claude Code via the `/docs` command. This section shows how to effectively leverage the expanded documentation coverage. - -### Finding Documentation Topics - -**Search for specific topics**: - -``` -/docs mcp -``` - -Returns all MCP-related documentation including: -- Build with Claude: MCP integration guide -- Claude Code: MCP configuration -- Agent SDK: MCP server implementation -- Agents and Tools: MCP overview - -**Search for API documentation**: - -``` -/docs api messages -``` - -Finds: -- API Reference: Messages endpoint -- API Reference: Messages streaming -- Build with Claude: Working with messages - -**Search Claude Code specific docs**: - -``` -/docs claude code hooks -``` - -Locates: -- Claude Code: Hooks overview -- Claude Code: Hooks guide -- Claude Code: Hook configuration - -### Browsing by Category - -**View core documentation**: - -``` -/docs --category core_documentation -``` - -Lists all 151 core documentation paths including: -- About Claude (models, pricing, security) -- Build with Claude (prompt engineering, streaming, files) -- Test and Evaluate (guardrails, testing) -- Use case guides - -**Browse API reference**: - -``` -/docs --category api_reference -``` - -Shows all 91 API reference paths: -- Administration API -- Agent SDK -- Messages API -- Files API -- Skills API - -**Explore prompt library**: - -``` -/docs --category prompt_library -``` - -Lists 64 prompt templates for various use cases. - -### Finding Specific Features - -**Looking for tool use documentation**: - -``` -/docs tool use -``` - -Returns: -- Build with Claude: Tool use overview -- Agents and Tools: Tool use implementation -- API Reference: Tool definitions -- Claude Code: Custom tools - -**Finding prompt engineering guides**: - -``` -/docs prompt engineering -``` - -Locates: -- Build with Claude: Prompt engineering overview -- Chain of thought prompting -- System prompts guide -- Claude 4 best practices - -**Searching for integration guides**: - -``` -/docs github actions -``` -or -``` -/docs vs code -``` - -Finds integration-specific documentation. - -### Natural Language Queries - -The enhanced search understands natural language: - -``` -/docs how to use extended thinking -``` - -Finds: -- About Claude: Extended thinking models -- Build with Claude: Extended thinking guide -- Prompt Engineering: Extended thinking tips - -``` -/docs batch processing api -``` - -Locates: -- Build with Claude: Batch processing -- API Reference: Creating message batches -- API Reference: Retrieving batch results - -## Using the /docs Command - -### Basic Search - -**Simple topic search**: - -```bash -/docs hooks -``` - -**Response includes**: -- Claude Code: Hooks guide -- Claude Code: Hooks reference -- API Reference: Hook configuration - -### Search with Options - -**Search in specific category**: - -```bash -/docs --category claude_code hooks -``` - -Only returns results from Claude Code documentation. - -**List all categories**: - -```bash -/docs --list-categories -``` - -Shows: -- core_documentation (151) -- api_reference (91) -- claude_code (68) -- resources (68) -- prompt_library (64) -- release_notes (4) -- uncategorized (3) - -### Viewing Documentation - -**Open specific documentation**: - -```bash -/docs mcp -``` - -Claude Code displays the content of matching documentation files. - -**Multiple matches**: - -When multiple documents match, you'll see: -1. List of all matching paths -2. Option to view specific document -3. Related documentation suggestions - -### Advanced Search Features - -**Content-based search** (searches within documentation text): - -```bash -/docs --search-content "streaming responses" -``` - -Finds documents containing the phrase "streaming responses" in their content, not just in path names. - -**Fuzzy matching**: - -If you mistype or use approximate terms: - -```bash -/docs promt engeneering -``` - -The system suggests: -- Did you mean: "prompt engineering"? -- Showing results for: prompt engineering - -### Validation - -**Check documentation availability**: - -```bash -/docs --validate -``` - -Validates that all 573 documentation paths are reachable. - -**Output includes**: -- Total paths checked: 573 -- Successful: 571 -- Failed: 2 (navigation pages) -- Validation time: ~60s - -**Verify specific path**: - -```bash -/docs --validate /en/docs/build-with-claude/mcp -``` - -Checks if specific path is reachable. - -## Command-Line Reference - -### Direct Script Usage - -For advanced users or automation, you can use the Python scripts directly. - -#### Search Operations - -**Path search**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --search "mcp" -``` - -**Content search**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --search-content "model context protocol" -``` - -**Category filtering**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --search "hooks" --category claude_code -``` - -#### Validation Operations - -**Full validation**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --validate -``` - -**Parallel validation** (adjust concurrency): - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --validate --workers 20 -``` - -**Quiet validation** (errors only): - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --validate --quiet -``` - -#### Update Operations - -**Update all documentation**: - -```bash -python ~/.claude-code-docs/scripts/main.py --update-all -``` - -**Update specific category**: - -```bash -python ~/.claude-code-docs/scripts/main.py --update-category core_documentation -``` - -**Check what needs updating** (dry run): - -```bash -python ~/.claude-code-docs/scripts/main.py --verify -``` - -**Force update** (ignore hashes): - -```bash -python ~/.claude-code-docs/scripts/main.py --update-all --force -``` - -#### Path Management - -**Build search index**: - -```bash -python ~/.claude-code-docs/scripts/build_search_index.py -``` - -**Extract paths from sitemap**: - -```bash -python ~/.claude-code-docs/scripts/extract_paths.py -``` - -**Clean broken paths**: - -```bash -python ~/.claude-code-docs/scripts/clean_manifest.py -``` - -**Update sitemap**: - -```bash -python ~/.claude-code-docs/scripts/update_sitemap.py -``` - -### Common Patterns - -#### Daily Workflow - -**Morning documentation check**: - -```bash -# Update any changed docs -python ~/.claude-code-docs/scripts/main.py --update-all - -# Validate all paths -python ~/.claude-code-docs/scripts/lookup_paths.py --validate -``` - -#### Integration Testing - -**In CI/CD pipeline**: - -```bash -# Validate docs are accessible -python ~/.claude-code-docs/scripts/lookup_paths.py --validate || exit 1 - -# Update docs -python ~/.claude-code-docs/scripts/main.py --update-all - -# Rebuild search index -python ~/.claude-code-docs/scripts/build_search_index.py -``` - -#### Content Analysis - -**Find all documents mentioning a topic**: - -```bash -# Search content -python ~/.claude-code-docs/scripts/lookup_paths.py --search-content "extended thinking" > results.txt - -# Count matches -cat results.txt | grep -c "Found" -``` - -#### Maintenance - -**Clean and rebuild**: - -```bash -# Clean broken paths -python ~/.claude-code-docs/scripts/clean_manifest.py - -# Rebuild everything -python ~/.claude-code-docs/scripts/main.py --update-all --force - -# Rebuild search index -python ~/.claude-code-docs/scripts/build_search_index.py - -# Validate all paths -python ~/.claude-code-docs/scripts/lookup_paths.py --validate -``` - -### Flag Reference - -#### Common Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--search ` | Search path names | `--search mcp` | -| `--search-content ` | Search content | `--search-content "streaming"` | -| `--category ` | Filter by category | `--category api_reference` | -| `--validate` | Validate paths | `--validate` | -| `--list-categories` | List all categories | `--list-categories` | -| `--version` | Show version info | `--version` | -| `--status` | Show installation status | `--status` | -| `--quiet` | Minimal output | `--validate --quiet` | -| `--verbose` | Detailed output | `--update-all --verbose` | - -#### Update Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--update-all` | Update all docs | `--update-all` | -| `--update-category ` | Update category | `--update-category core` | -| `--verify` | Check for changes | `--verify` | -| `--force` | Force update | `--update-all --force` | - -#### Validation Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--workers ` | Concurrent requests | `--validate --workers 10` | -| `--timeout ` | Request timeout | `--validate --timeout 15` | -| `--report` | Generate report | `--validate --report` | - -### Tips and Tricks - -**1. Combining flags for precise results**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py \ - --search "streaming" \ - --category api_reference -``` - -**2. Using wildcards in searches**: - -```bash -/docs "claude code*" -``` - -**3. Excluding categories**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py \ - --search "api" \ - --exclude-category prompt_library -``` - -**4. Export search results**: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py \ - --search "mcp" \ - --format json > mcp_docs.json -``` - -**5. Batch operations**: - -```bash -# Update multiple categories -for cat in core_documentation api_reference claude_code; do - python ~/.claude-code-docs/scripts/main.py --update-category $cat -done -``` - -## Frequently Asked Questions - -### How do I find all documentation about a topic? - -Use both path and content search: - -```bash -/docs --search "topic" -/docs --search-content "topic" -``` - -### How do I know if a document exists? - -Use validation: - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py \ - --validate /en/docs/path/to/doc -``` - -### How do I update just one category? - -```bash -python ~/.claude-code-docs/scripts/main.py \ - --update-category category_name -``` - -### How do I see what changed? - -```bash -python ~/.claude-code-docs/scripts/main.py --verify -``` - -This shows which documents have changed (by hash) without fetching them. - -### How do I search for exact phrases? - -Use quotes: - -```bash -/docs "exact phrase here" -``` - -### How do I get a list of all available paths? - -```bash -python ~/.claude-code-docs/scripts/lookup_paths.py --list-all -``` - -or view the paths_manifest.json directly: - -```bash -jq '.categories' ~/.claude-code-docs/paths_manifest.json -``` - -### How do I check which version I have installed? - -Check version and feature availability: - -```bash -~/.claude-code-docs/scripts/claude-docs-helper.sh --version -``` - -This shows: -- Helper script version -- Template version -- Python version (if available) -- Enhanced features status -- Available feature list - -For installation status: - -```bash -~/.claude-code-docs/scripts/claude-docs-helper.sh --status -``` - -This displays: -- Installation location -- Standard features status -- Enhanced features status -- Documentation file counts -- Manifest statistics - -## Getting Help - -For additional help: - -1. **Feature questions**: See `CAPABILITIES.md` -2. **Installation help**: See `README.md` -3. **Contributing**: See `CONTRIBUTING.md` -4. **Upstream compatibility**: See root `CLAUDE.md` - -## Examples Repository - -More examples and use cases: See the test suite in `tests/` directory for programmatic usage patterns. diff --git a/enhancements/FEATURES.md b/enhancements/FEATURES.md deleted file mode 100644 index c9d596547..000000000 --- a/enhancements/FEATURES.md +++ /dev/null @@ -1,204 +0,0 @@ -# Enhanced Features - -This fork extends [ericbuess/claude-code-docs](https://github.com/ericbuess/claude-code-docs) with additional capabilities. - -## What's Enhanced - -### 1. Active Documentation Path Tracking - -**Enhanced Edition**: 573 documentation paths tracked in manifest covering: -- API Reference (377 paths - 65.8%) - Complete API docs, multi-language SDK -- Core Documentation (82 paths - 14.3%) - Guides, tutorials, best practices -- Prompt Library (65 paths - 11.3%) - Ready-to-use prompt templates -- Claude Code (46 paths - 8.0%) - CLI-specific docs, hooks, MCP -- Release Notes (2 paths - 0.3%) -- Resources (1 path - 0.2%) - -**Files Downloaded**: 571 actual .md files - -See `paths_manifest.json` for full list. - -### 2. Full-Text Search - -**Command**: `/docs --search-content 'query'` - -Searches across all documentation content, not just path names. - -**Implementation**: -- `scripts/build_search_index.py` - Builds searchable index -- `docs/.search_index.json` - Pre-built search index -- Keyword extraction and ranking -- Stop word filtering - -### 3. Path Validation - -**Command**: `/docs --validate` - -Validates all 573 paths are reachable. - -**Features**: -- HTTP reachability testing -- Parallel validation (ThreadPoolExecutor) -- Detailed reports -- Broken link detection - -**Implementation**: `scripts/lookup_paths.py` (597 lines) - -### 4. Advanced Path Search - -**Command**: `/docs --search 'query'` - -Fuzzy search across all 573 paths with relevance ranking. - -**Features**: -- Levenshtein distance matching -- Category filtering -- Multiple match ranking -- Suggestion system - -### 5. Comprehensive Testing - -**Location**: `tests/` directory - -**Coverage**: -- 294 tests (unit + integration + validation) -- 294 passing (99.3% pass rate) -- 2 skipped (intentional) -- pytest + pytest-cov - -**Run**: `pytest` or `pytest --cov=scripts` - -### 6. Enhanced Fetching - -**Script**: `scripts/main.py` (662 lines) - -**Features**: -- Batch fetching of 573 paths -- SHA256-based change detection (only fetch what changed) -- Retry logic with exponential backoff -- Rate limiting (0.5s between requests) -- Progress tracking -- Error recovery - -**Usage**: -```bash -python scripts/main.py --update-all # Fetch all 573 docs -python scripts/main.py --update-category core # Update specific category -python scripts/main.py --verify # Check what needs updating -``` - -### 7. Path Management Tools - -**Extract Paths** (`scripts/extract_paths.py` - 534 lines): -- Extract paths from sitemap -- Clean duplicates and artifacts -- Categorize by section -- Validate format - -**Clean Manifest** (`scripts/clean_manifest.py` - 172 lines): -- Remove broken paths -- Update reachability status -- Generate validation reports - -**Update Sitemap** (`scripts/update_sitemap.py` - 504 lines): -- Generate hierarchical trees -- Update search index -- Maintain compatibility with upstream manifest format - -### 8. Developer Documentation - -**Location**: `docs-dev/` - -**Files**: -- `DEVELOPMENT.md` (650 lines) - Contributor guide -- `CAPABILITIES.md` (870 lines) - Feature documentation -- `EXAMPLES.md` (620 lines) - Usage examples and FAQ -- `analysis/` - 4 analysis documents from Phase 1 -- `specs/` - 3 implementation planning documents - -### 9. GitHub Actions Enhancements - -**Standard Workflows** (from upstream): -- `update-docs.yml` - Fetch docs every 3 hours - -**Enhanced Workflows** (ours): -- `test.yml` - Run 577 tests on push/PR -- `validate.yml` - Daily path validation -- `coverage.yml` - Coverage reporting - -## Installation - -### Single Installation with Graceful Degradation - -```bash -curl -fsSL https://raw.githubusercontent.com/costiash/claude-code-docs/main/install.sh | bash -``` - -**Always Installed**: -- 573 documentation paths tracked in manifest -- 571 files downloaded -- AI-powered `/docs` command -- Auto-update system -- Python enhancement scripts - -**Runtime Features** (automatic detection): -- **Without Python 3.9+**: Basic documentation reading via `/docs` -- **With Python 3.9+**: Full-text search, validation, fuzzy matching, auto-regeneration - -## Feature Availability - -| Feature | Without Python | With Python 3.9+ | -|---------|----------------|------------------| -| Documentation paths | 573 tracked | 573 tracked | -| Files downloaded | 571 | 571 | -| Search | Topic name via AI | Full-text + fuzzy + AI | -| Validation | None | HTTP reachability | -| Updates | Git pull | Auto-fetch + validation | -| Testing | N/A | 294 tests | -| Dependencies | git, jq, curl | + Python 3.9+, requests | - -## Contributing Enhancements Upstream - -These enhancements are designed to be contributed back to upstream as optional features: - -**Proposed PRs**: -1. **Optional Enhanced Mode** - Install script with Python features -2. **Extended Path Coverage** - 573 paths manifest -3. **Full-Text Search** - Search capability (opt-in) -4. **Testing Framework** - Test suite for validation -5. **Developer Documentation** - Enhanced docs - -**Design Principles**: -- All enhancements are **optional** (don't break standard mode) -- **Backward compatible** with upstream -- **Well tested** (294 tests, 99.3% pass rate) -- **Documented** (comprehensive docs) -- **Modular** (can adopt pieces independently) - -## Performance - -### Benchmarks - -**Fetch Performance**: -- ~32 seconds per 100 paths (10x faster than 2min target) -- Memory usage: 35 MB (70x below 500 MB limit) - -**Search Performance**: -- Path search: ~90ms average -- Content search: < 100ms per query -- Index build time: ~2 seconds for 571 docs -- Index size: ~45KB - -**Validation Performance**: -- Full validation: ~60 seconds for 573 paths (parallel) -- Configurable concurrency - -## License - -Enhancements are provided under the same license as upstream. See LICENSE file. - -## Acknowledgments - -Built on the excellent foundation of [ericbuess/claude-code-docs](https://github.com/ericbuess/claude-code-docs). - -Enhanced features developed through Phase 1-7 implementation plan (see `docs-dev/specs/IMPLEMENTATION_PLAN.md`). diff --git a/enhancements/README.md b/enhancements/README.md deleted file mode 100644 index 540dd65ad..000000000 --- a/enhancements/README.md +++ /dev/null @@ -1,252 +0,0 @@ -# Enhancements Directory - -This directory contains comprehensive documentation for the enhanced features of claude-code-docs. - -## Overview - -The enhanced edition extends [ericbuess/claude-code-docs](https://github.com/ericbuess/claude-code-docs) with optional Python-based capabilities while maintaining full backward compatibility. This directory documents those enhancements. - -## What's Inside - -### Core Documentation - -- **[FEATURES.md](FEATURES.md)** - Complete feature list and technical details - - Documentation coverage (573 active paths tracked) - - Full-text search capabilities - - Path validation tools - - Advanced search and filtering - - Comprehensive testing (620 tests) - - Performance benchmarks - -- **[CAPABILITIES.md](CAPABILITIES.md)** - Detailed capability documentation - - Documentation coverage breakdown (6 categories) - - Search capabilities (path + content search) - - Validation features (HTTP reachability testing) - - Advanced features (change detection, batch operations) - - Technical implementation details - - Performance characteristics - -- **[EXAMPLES.md](EXAMPLES.md)** - Practical usage examples - - Using enhancements in Claude Code - - The `/docs` command with examples - - Command-line usage patterns - - Common workflows - - Tips and tricks - -## Quick Start - -### For Users - -If you've installed the enhanced edition, you can: - -1. **Search documentation**: `/docs ` -2. **Browse categories**: `/docs --list-categories` -3. **Validate paths**: `/docs --validate` -4. **Content search**: `/docs --search-content ` - -See [EXAMPLES.md](EXAMPLES.md) for detailed usage. - -### For Developers - -If you're working on the codebase: - -1. **Understand capabilities**: Read [CAPABILITIES.md](CAPABILITIES.md) -2. **See technical details**: Read [FEATURES.md](FEATURES.md) -3. **Learn patterns**: Review [EXAMPLES.md](EXAMPLES.md) -4. **Check tests**: See `tests/` directory - -## Architecture - -### Single Installation with Graceful Degradation - -The enhanced edition uses a single installation approach: - -**Always Installed**: -- 573 documentation paths tracked in manifest -- 571 files downloaded -- Python scripts for enhanced features - -**Runtime Behavior** (automatic feature detection): -- **Without Python 3.9+**: Basic documentation reading via `/docs` command -- **With Python 3.9+**: Full-text search, validation, fuzzy matching, auto-regeneration - -No separate "modes" - features activate automatically based on Python availability. - -### Key Components - -**Documentation Coverage**: -- 6 categories of documentation -- 573 total paths -- All available English documentation - -**Search System**: -- Path-based search (fuzzy matching) -- Content-based search (full-text) -- Category filtering -- Relevance ranking - -**Validation System**: -- HTTP reachability testing -- Parallel validation (ThreadPoolExecutor) -- Detailed reporting -- Broken link detection - -**Update System**: -- SHA256-based change detection -- Selective fetching (only changed docs) -- Batch operations -- Rate limiting and retry logic - -## Category Breakdown - -The 573 documentation paths are organized into: - -1. **API Reference** (377 paths - 65.8%) - - Complete API docs, Admin API, Agent SDK, multi-language SDK docs (Python, TypeScript, Go, Java, Kotlin, Ruby) - -2. **Core Documentation** (82 paths - 14.3%) - - About Claude, Build with Claude, Test and Evaluate, Guides - -3. **Prompt Library** (65 paths - 11.3%) - - 65 unique prompt templates - -4. **Claude Code** (46 paths - 8.0%) - - CLI-specific docs, hooks, skills, MCP, IDE integrations - -5. **Release Notes** (2 paths - 0.3%) - - Overview and system prompts updates - -6. **Resources** (1 path - 0.2%) - - Resources overview - -## Performance - -Key performance metrics: - -- **Search**: <100ms per query -- **Fetch**: ~32s per 100 paths -- **Validation**: ~60s for all 573 paths -- **Memory**: ~35 MB typical usage -- **Index size**: ~45KB - -## Files in This Directory - -``` -enhancements/ -├── README.md # This file - directory overview -├── FEATURES.md # Complete feature list and specs -├── CAPABILITIES.md # Detailed capability documentation -└── EXAMPLES.md # Usage examples and patterns -``` - -## Related Documentation - -### In Repository Root - -- **README.md** - Main repository documentation -- **CONTRIBUTING.md** - Contribution guidelines -- **CLAUDE.md** - Project architecture and instructions -- **CHANGELOG.md** - Version history - -### For Developers - -- **docs-dev/** - Developer documentation (if exists) -- **tests/** - Test suite (294 tests) -- **scripts/** - Python implementation scripts - -## Use Cases - -### Individual Users - -- Quick access to Anthropic documentation -- Offline documentation browsing -- Fast search across all docs -- Topic discovery - -### Development Teams - -- CI/CD integration testing -- Documentation validation -- Custom tooling development -- Content analysis - -### Contributors - -- Path discovery and coverage -- Quality assurance -- Update automation -- Feature development - -## Getting Started - -1. **Installation**: Follow installation guide in root README.md -2. **Basic usage**: See [EXAMPLES.md](EXAMPLES.md) Quick Start -3. **Advanced features**: Read [CAPABILITIES.md](CAPABILITIES.md) -4. **Development**: See [FEATURES.md](FEATURES.md) technical details - -## Contributing to Enhancements - -Interested in contributing? See: - -1. Root **CONTRIBUTING.md** for general guidelines -2. **CLAUDE.md** for project architecture -3. **FEATURES.md** for technical implementation -4. **tests/** directory for test patterns - -## Upstream Compatibility - -All enhancements are designed to be: - -- **Optional**: Standard mode works without Python -- **Backward compatible**: Doesn't break upstream functionality -- **Well tested**: 294 tests with 99.3% pass rate (294 passing, 2 skipped) -- **Documented**: Comprehensive documentation -- **Modular**: Can adopt features independently - -## Potential Upstream Contribution - -These enhancements are designed for potential contribution back to upstream: - -**Proposed PRs**: -1. Optional enhanced mode installation -2. Extended path coverage (573 paths) -3. Full-text search capability -4. Testing framework -5. Enhanced documentation - -See [FEATURES.md](FEATURES.md) for details on upstream contribution strategy. - -## Support - -### Questions? - -- **Feature questions**: See [CAPABILITIES.md](CAPABILITIES.md) -- **Usage help**: See [EXAMPLES.md](EXAMPLES.md) -- **Installation**: See root README.md -- **Contributing**: See CONTRIBUTING.md - -### Issues? - -If you encounter issues with enhanced features: - -1. Check [EXAMPLES.md](EXAMPLES.md) for correct usage -2. Verify Python 3.9+ is installed -3. Check paths_manifest.json exists -4. Run validation: `/docs --validate` -5. Review test output: `pytest tests/ -v` - -## Version Information - -Current enhanced edition version: See CHANGELOG.md in repository root - -Last documentation update: 2025-11-06 - -## License - -Enhancements provided under same license as upstream. See LICENSE file in repository root. - -## Acknowledgments - -Built on the excellent foundation of [ericbuess/claude-code-docs](https://github.com/ericbuess/claude-code-docs). - -Enhanced features developed to provide comprehensive coverage of Anthropic's documentation ecosystem while maintaining full compatibility with upstream. diff --git a/index.html b/index.html index 1a123c9b8..9888d812c 100644 --- a/index.html +++ b/index.html @@ -27,15 +27,11 @@

Claude Code Docs

Native Claude Code Plugin with auto-discovery Skill and AI-powered documentation search.

-
Plugin Install (Recommended)
+
Install
/plugin marketplace add costiash/claude-code-docs
/plugin install claude-docs@claude-code-docs
-
-
Script Install (Alternative)
- curl -fsSL https://raw.githubusercontent.com/costiash/claude-code-docs/main/install.sh | bash -

Redirecting to GitHub repository...

-

11 doc categories · 6 SDK languages · auto-updated · zero dependencies

+

multi-language SDK coverage · auto-updated every 3 hours · zero dependencies

diff --git a/install.sh b/install.sh index 704cc9404..7f8623b6c 100755 --- a/install.sh +++ b/install.sh @@ -1,779 +1,115 @@ #!/bin/bash set -euo pipefail -# Claude Code Docs Installer v0.5.1 - Bug fixes and CI improvements -# This script installs claude-code-docs to ~/.claude-code-docs -# Installation Strategy: Always perform a fresh installation at the fixed location -# 1. Remove any existing installation at ~/.claude-code-docs (with user confirmation) -# 2. Clone fresh from GitHub -# 3. Set up commands and hooks -# 4. Clean up any old installations in other locations +# Claude Code Docs Installer v1.0.0 +# Migration wrapper: routes to plugin install when possible, +# falls back to git clone for environments without plugin support. -echo "Claude Code Docs Installer v0.5.1" -echo "===============================" - -# Target version for upgrade messaging -TARGET_VERSION="0.5.1" -TARGET_DOCS="" # Set after install from DOC_COUNT +echo "Claude Code Docs v1.0.0" +echo "=======================" +echo "" -# Fixed installation location INSTALL_DIR="$HOME/.claude-code-docs" +REPO_URL="https://github.com/costiash/claude-code-docs.git" -# Branch to use for installation -INSTALL_BRANCH="main" - -# Detect OS type -if [[ "$OSTYPE" == "darwin"* ]]; then - OS_TYPE="macos" - echo "✓ Detected macOS" -elif [[ "$OSTYPE" == "linux-gnu"* ]]; then - OS_TYPE="linux" - echo "✓ Detected Linux" -else - echo "❌ Error: Unsupported OS type: $OSTYPE" - echo "This installer supports macOS and Linux only" - exit 1 -fi - -# Check dependencies -echo "Checking dependencies..." -for cmd in git jq curl; do - if ! command -v "$cmd" &> /dev/null; then - echo "❌ Error: $cmd is required but not installed" - echo "Please install $cmd and try again" - exit 1 - fi -done -echo "✓ All dependencies satisfied" - - -# Function to detect current installation version -detect_current_version() { - if [[ ! -d "$INSTALL_DIR" ]]; then - echo "none|0|false" - return - fi - - local version="unknown" - local doc_count=0 - local has_packages="false" - - # Get version from helper script (try multiple locations) - if [[ -f "$INSTALL_DIR/scripts/claude-docs-helper.sh" ]]; then - version=$(grep -m1 'ENHANCED_VERSION=' "$INSTALL_DIR/scripts/claude-docs-helper.sh" 2>/dev/null | cut -d'"' -f2 || echo "unknown") - elif [[ -f "$INSTALL_DIR/claude-docs-helper.sh" ]]; then - version=$(grep -m1 'ENHANCED_VERSION=' "$INSTALL_DIR/claude-docs-helper.sh" 2>/dev/null | cut -d'"' -f2 || echo "unknown") - fi - - # Count docs - doc_count=$(find "$INSTALL_DIR/docs" -name "*.md" 2>/dev/null | wc -l | tr -d ' ') - - # Check for modular packages (new in v0.5.0) - [[ -d "$INSTALL_DIR/scripts/fetcher" && -d "$INSTALL_DIR/scripts/lookup" ]] && has_packages="true" - - echo "$version|$doc_count|$has_packages" -} - -# Function to show upgrade information -show_upgrade_info() { - local current_info="$1" - - IFS='|' read -r cur_version cur_docs cur_packages <<< "$current_info" - - # Skip if no existing installation - [[ "$cur_version" == "none" ]] && return - - # Skip if already on target version - [[ "$cur_version" == "$TARGET_VERSION" ]] && return - +# Check if Claude Code is available +if [ -d "$HOME/.claude" ]; then + echo "Claude Code detected." echo "" - echo "════════════════════════════════════════════════════════════════" - echo " UPGRADE DETECTED " - echo "════════════════════════════════════════════════════════════════" + echo "The recommended installation method is the Claude Code plugin." + echo "Run these two commands inside Claude Code:" echo "" - echo " Current: v$cur_version ($cur_docs documentation files)" - echo " Target: v$TARGET_VERSION" + echo " /plugin marketplace add costiash/claude-code-docs" + echo " /plugin install claude-docs@claude-code-docs" echo "" - echo " What's New in v$TARGET_VERSION:" - echo " • 2x documentation coverage" - echo " • Domain-based filename convention (claude-code__*.md)" - echo " • Modular Python packages (fetcher/, lookup/)" - echo " • Safety thresholds for sync protection" - echo " • Paths tracked across 6 categories" + echo "The plugin provides:" + echo " - /docs command for documentation lookups" + echo " - Auto-discovery Skill (Claude reads docs automatically)" + echo " - Session-start auto-updates" + echo " - Content search and fuzzy matching" echo "" - echo "════════════════════════════════════════════════════════════════" - echo "" -} -# Function to check and remove existing installation at ~/.claude-code-docs -check_and_remove_existing_install() { - # Check if installation directory already exists - if [[ ! -d "$INSTALL_DIR" ]]; then - return 0 # Nothing to remove - fi + # Check for legacy script-install artifacts + legacy_found=false - # Check for uncommitted changes if it's a git repo - local has_uncommitted_changes=false - if [[ -d "$INSTALL_DIR/.git" ]]; then - local original_dir=$(pwd) - if cd "$INSTALL_DIR" 2>/dev/null; then - if [[ -n "$(git status --porcelain 2>/dev/null)" ]]; then - has_uncommitted_changes=true - fi - cd "$original_dir" || exit 1 + if [ -f "$HOME/.claude/commands/docs.md" ]; then + # Check if the command references claude-docs-helper.sh (legacy indicator) + if grep -q "claude-docs-helper" "$HOME/.claude/commands/docs.md" 2>/dev/null; then + legacy_found=true fi fi - # Auto-proceed if no uncommitted changes OR auto-install mode enabled - if [[ "$has_uncommitted_changes" == "false" ]] || [[ "${CLAUDE_DOCS_AUTO_INSTALL:-}" == "yes" ]]; then - if [[ "${CLAUDE_DOCS_AUTO_INSTALL:-}" == "yes" ]]; then - echo "🔄 Auto-install mode: Removing existing installation..." - else - echo "🔄 Existing installation detected - updating to latest version..." + if [ -f "$HOME/.claude/settings.json" ]; then + if grep -q "claude-code-docs" "$HOME/.claude/settings.json" 2>/dev/null; then + legacy_found=true fi - rm -rf "$INSTALL_DIR" - echo "✓ Ready for fresh installation" - echo "" - return 0 fi - # Only prompt if there are uncommitted changes - echo "" - echo "⚠️ WARNING: Existing installation has uncommitted changes!" - echo " Location: $INSTALL_DIR" - echo " All local modifications will be lost." - echo "" - - # Try to get user confirmation - if [[ -t 0 ]]; then - # Interactive terminal - read -p "Continue and delete existing installation? [y/N]: " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - echo "Installation cancelled. Your changes are preserved." - exit 0 - fi - else - # Non-interactive (piped input, CI/CD) - echo "❌ Cannot proceed: Non-interactive mode with uncommitted changes" - echo "" - echo "Options:" - echo " • Commit your changes: cd $INSTALL_DIR && git add . && git commit" - echo " • Force auto-install: CLAUDE_DOCS_AUTO_INSTALL=yes curl ... | bash" - echo " • Download and run interactively: curl ... -o install.sh && bash install.sh" + if [ "$legacy_found" = true ]; then + echo "Legacy script-install artifacts detected." echo "" - exit 1 - fi - - # Remove the directory - echo "Removing existing installation..." - rm -rf "$INSTALL_DIR" - echo "✓ Existing installation removed" - echo "" -} - -# Function to find existing installations from configs -find_existing_installations() { - local paths=() - - # Check command file for paths - if [[ -f ~/.claude/commands/docs.md ]]; then - # Look for paths in the command file - # v0.1 format: LOCAL DOCS AT: /path/to/claude-code-docs/docs/ - # v0.2+ format: Execute: /path/to/claude-code-docs/helper.sh - while IFS= read -r line; do - # v0.1 format - if [[ "$line" =~ LOCAL\ DOCS\ AT:\ ([^[:space:]]+)/docs/ ]]; then - local path="${BASH_REMATCH[1]}" - path="${path/#\~/$HOME}" - [[ -d "$path" ]] && paths+=("$path") - fi - # v0.2+ format - if [[ "$line" =~ Execute:.*claude-code-docs ]]; then - # Extract path from various formats - local path=$(echo "$line" | grep -o '[^ "]*claude-code-docs[^ "]*' | head -1) - path="${path/#\~/$HOME}" - - # Get directory part - if [[ -d "$path" ]]; then - paths+=("$path") - elif [[ -d "$(dirname "$path")" ]] && [[ "$(basename "$(dirname "$path")")" == "claude-code-docs" ]]; then - paths+=("$(dirname "$path")") - fi - fi - done < ~/.claude/commands/docs.md - fi - - # Check settings.json hooks for paths - if [[ -f ~/.claude/settings.json ]]; then - local hooks=$(jq -r '.hooks.PreToolUse[]?.hooks[]?.command // empty' ~/.claude/settings.json 2>/dev/null) - while IFS= read -r cmd; do - if [[ "$cmd" =~ claude-code-docs ]]; then - # Extract paths from v0.1 complex hook format - # Look for patterns like: "/path/to/claude-code-docs/.last_check" - local v01_paths=$(echo "$cmd" | grep -o '"[^"]*claude-code-docs[^"]*"' | sed 's/"//g' || true) - while IFS= read -r path; do - [[ -z "$path" ]] && continue - # Extract just the directory part - if [[ "$path" =~ (.*/claude-code-docs)(/.*)?$ ]]; then - path="${BASH_REMATCH[1]}" - path="${path/#\~/$HOME}" - [[ -d "$path" ]] && paths+=("$path") - fi - done <<< "$v01_paths" - - # Also try v0.2+ simpler format - local found=$(echo "$cmd" | grep -o '[^ "]*claude-code-docs[^ "]*' || true) - while IFS= read -r path; do - [[ -z "$path" ]] && continue - path="${path/#\~/$HOME}" - # Clean up path to get the claude-code-docs directory - if [[ "$path" =~ (.*/claude-code-docs)(/.*)?$ ]]; then - path="${BASH_REMATCH[1]}" + if [ -t 0 ]; then + read -p "Clean up legacy artifacts? (y/N): " -n 1 -r + echo + if [[ $REPLY =~ ^[Yy]$ ]]; then + # Remove legacy /docs command if it references the helper script + if [ -f "$HOME/.claude/commands/docs.md" ]; then + if grep -q "claude-docs-helper" "$HOME/.claude/commands/docs.md" 2>/dev/null; then + rm -f "$HOME/.claude/commands/docs.md" + echo " Removed legacy /docs command" fi - [[ -d "$path" ]] && paths+=("$path") - done <<< "$found" - fi - done <<< "$hooks" - fi - - # Also check current directory if running from an installation - if [[ -f "./docs/docs_manifest.json" && "$(pwd)" != "$INSTALL_DIR" ]]; then - paths+=("$(pwd)") - fi - - # Deduplicate and exclude new location - if [[ ${#paths[@]} -gt 0 ]]; then - printf '%s\n' "${paths[@]}" | grep -v "^$INSTALL_DIR$" | sort -u - fi -} - -# Function to check if Python features are available -check_python_features() { - # Check Python version (need 3.9+ for enhanced search/validation features) - if ! command -v python3 &> /dev/null; then - return 1 - fi - - local python_version=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null || echo "0.0") - local python_major=$(echo "$python_version" | cut -d. -f1) - local python_minor=$(echo "$python_version" | cut -d. -f2) - - if [[ "$python_major" -lt 3 ]] || [[ "$python_major" -eq 3 && "$python_minor" -lt 9 ]]; then - return 1 - fi - - # Check if paths_manifest.json exists - if [[ ! -f "$INSTALL_DIR/paths_manifest.json" ]]; then - return 1 - fi - - # Python features available if we have Python 3.9+ and the manifest - return 0 -} - -# Function to cleanup old installations -cleanup_old_installations() { - # Use the global OLD_INSTALLATIONS array that was populated before config updates - if [[ ${#OLD_INSTALLATIONS[@]} -eq 0 ]]; then - return - fi - - echo "" - echo "Cleaning up old installations..." - echo "Found ${#OLD_INSTALLATIONS[@]} old installation(s) to remove:" - - for old_dir in "${OLD_INSTALLATIONS[@]}"; do - # Skip empty paths - if [[ -z "$old_dir" ]]; then - continue - fi - - echo " - $old_dir" - - # SAFETY CHECK 1: Never delete current working directory - if [[ "$(pwd 2>/dev/null)" == "$old_dir" ]]; then - echo " ⚠️ Preserved (current working directory)" - continue - fi - - # SAFETY CHECK 2: Never delete development repos (pattern: /home/*/claude-code-docs) - if [[ "$old_dir" =~ ^/home/[^/]+/claude-code-docs$ ]]; then - echo " ⚠️ Preserved (likely development repository)" - continue - fi - - # SAFETY CHECK 3: Check if it's a development repo with GitHub remote - if [[ -d "$old_dir/.git" ]]; then - local original_dir=$(pwd) - if cd "$old_dir" 2>/dev/null; then - # Check for GitHub remote pointing to main repo - local has_github_remote=$(git remote -v 2>/dev/null | grep -c "github.com.*claude-code-docs" || echo "0") - - if [[ "$has_github_remote" -gt 0 ]]; then - cd "$original_dir" || exit 1 - echo " ⚠️ Preserved (development repository with GitHub remote)" - continue fi - # Check if it has uncommitted changes - if [[ -z "$(git status --porcelain 2>/dev/null)" ]]; then - cd "$original_dir" || exit 1 - rm -rf "$old_dir" - echo " ✓ Removed (clean installation copy)" - else - cd "$original_dir" || exit 1 - echo " ⚠️ Preserved (has uncommitted changes)" + # Remove legacy hooks from settings.json + if [ -f "$HOME/.claude/settings.json" ] && command -v jq >/dev/null 2>&1; then + if jq -e '.hooks.PreToolUse' "$HOME/.claude/settings.json" >/dev/null 2>&1; then + jq '.hooks.PreToolUse = [(.hooks.PreToolUse // [])[] | select(.hooks[0].command | contains("claude-code-docs") | not)]' \ + "$HOME/.claude/settings.json" > "$HOME/.claude/settings.json.tmp" && \ + mv "$HOME/.claude/settings.json.tmp" "$HOME/.claude/settings.json" + echo " Cleaned legacy hooks from settings.json" + fi fi - else - echo " ⚠️ Could not access directory" + + echo "" + echo "Legacy artifacts cleaned up." fi else - echo " ⚠️ Preserved (not a git repo)" + echo "Run this script interactively to clean up, or install the plugin to replace them." fi - done -} - -# Main installation logic -echo "" - -# STAGE 0: Detect current version before any changes (for upgrade messaging) -CURRENT_VERSION_INFO=$(detect_current_version) -show_upgrade_info "$CURRENT_VERSION_INFO" - -# STAGE 1: Check and remove existing installation at fixed location -check_and_remove_existing_install - -# STAGE 2: Find old installations from configs (for cleanup later) -echo "Checking for existing installations in other locations..." -existing_installs=() -while IFS= read -r line; do - [[ -n "$line" ]] && existing_installs+=("$line") -done < <(find_existing_installations) -if [[ ${#existing_installs[@]} -gt 0 ]]; then - OLD_INSTALLATIONS=("${existing_installs[@]}") # Save for later cleanup -else - OLD_INSTALLATIONS=() # Initialize empty array -fi + fi -if [[ ${#existing_installs[@]} -gt 0 ]]; then - echo "Found ${#existing_installs[@]} old installation(s) in other locations:" - for install in "${existing_installs[@]}"; do - echo " - $install" - done echo "" - echo "These will be cleaned up after installation." -else - echo "No installations found in other locations." -fi + echo "After installing the plugin, restart Claude Code." -# STAGE 3: Fresh installation at ~/.claude-code-docs (atomic) -echo "" -echo "Installing to ~/.claude-code-docs..." - -# Create a temporary directory for atomic installation -TEMP_INSTALL_DIR=$(mktemp -d "${TMPDIR:-/tmp}/claude-code-docs.XXXXXXXXXX") || { - echo "❌ Error: Failed to create temporary directory" - echo " Please check disk space and permissions" - exit 1 -} - -# Ensure temp directory is cleaned up on exit -trap 'rm -rf "$TEMP_INSTALL_DIR"' EXIT - -# Clone to temporary directory -echo " Downloading from GitHub..." -if ! git clone -b "$INSTALL_BRANCH" https://github.com/costiash/claude-code-docs.git "$TEMP_INSTALL_DIR" 2>&1; then +else + echo "Claude Code not detected (no ~/.claude directory)." echo "" - echo "❌ Error: Failed to clone repository from GitHub" - echo " Possible causes:" - echo " • No internet connection" - echo " • GitHub is down" - echo " • git is not installed correctly" + echo "Falling back to git clone..." + echo "NOTE: Plugin install is recommended when Claude Code is available." echo "" - echo " Please check your network connection and try again" - exit 1 -fi -echo " Download complete, installing..." - -# Move to final location (atomic operation) -if ! mv "$TEMP_INSTALL_DIR" "$INSTALL_DIR" 2>/dev/null; then - echo "" - echo "❌ Error: Failed to move installation to $INSTALL_DIR" - echo " Please check permissions and try again" - exit 1 -fi - -# Remove trap since we've successfully moved the directory -trap - EXIT - -cd "$INSTALL_DIR" || { - echo "❌ Error: Failed to access installation directory" - exit 1 -} -echo "✓ Repository cloned successfully" - -# Now we're in $INSTALL_DIR, set up the new script-based system -echo "" -echo "Setting up Claude Code Docs v$TARGET_VERSION..." - -# Copy enhanced helper script (not the template!) -echo "Installing helper script..." -if [[ -f "$INSTALL_DIR/scripts/claude-docs-helper.sh" ]]; then - cp "$INSTALL_DIR/scripts/claude-docs-helper.sh" "$INSTALL_DIR/claude-docs-helper.sh" - chmod +x "$INSTALL_DIR/claude-docs-helper.sh" - echo "✓ Enhanced helper script installed" -else - echo " ⚠️ Enhanced script missing, attempting recovery..." - # Try to fetch just the enhanced script - if curl -fsSL "https://raw.githubusercontent.com/costiash/claude-code-docs/$INSTALL_BRANCH/scripts/claude-docs-helper.sh" -o "$INSTALL_DIR/claude-docs-helper.sh" 2>/dev/null; then - chmod +x "$INSTALL_DIR/claude-docs-helper.sh" - echo " ✓ Enhanced helper script downloaded directly" + if [ -d "$INSTALL_DIR" ]; then + echo "Updating existing installation..." + cd "$INSTALL_DIR" && git pull --ff-only origin main || { + echo "Update failed. Try: rm -rf $INSTALL_DIR && re-run this script" + exit 1 + } else - echo " ❌ Failed to install helper script" - echo " Please check your installation and try again" - exit 1 + git clone --depth 1 "$REPO_URL" "$INSTALL_DIR" || { + echo "Clone failed. Check your network connection." + exit 1 + } fi -fi - -# Always update command (in case it points to old location) -echo "Setting up /docs command..." -mkdir -p ~/.claude/commands -# Remove old command if it exists -if [[ -f ~/.claude/commands/docs.md ]]; then - echo " Updating existing command..." -fi - -# Create AI-powered docs command with intent-driven approach -cat > ~/.claude/commands/docs.md << 'EOF' -# Claude Code Documentation Assistant - -You are a documentation assistant for Claude Code. Your mission: **answer the user's question directly with minimal interaction**. - -## Core Philosophy - -📖 **Read this first**: `~/.claude-code-docs/CLAUDE.md` contains comprehensive guidance on: -- Intent-driven documentation search -- When to synthesize vs when to ask -- Category labels and context detection -- Content search strategies -- Example workflows - -**Key principles from CLAUDE.md**: -1. **Synthesize by default** - Read multiple docs silently, present unified answer -2. **Only ask when contexts are incompatible** - Different products with different workflows -3. **Content search over path matching** - Find information even without exact paths -4. **Hide complexity** - Users don't need to know document structure - -## Your Workflow - -### Step 1: Analyze User Intent - -Extract from `$ARGUMENTS`: -- **What** they want to know (keywords, concepts) -- **Which product** context (if specified): "agent sdk", "cli", "api" -- **Type** of query: how-to, reference, integration, etc. - -### Step 2: Execute Search - -Use the helper script with appropriate command: - -```bash -# Content search (requires Python 3.9+) -~/.claude-code-docs/claude-docs-helper.sh --search-content "" - -# Path search -~/.claude-code-docs/claude-docs-helper.sh --search "" - -# Direct topic lookup -~/.claude-code-docs/claude-docs-helper.sh - -# Special commands -~/.claude-code-docs/claude-docs-helper.sh -t # freshness check -~/.claude-code-docs/claude-docs-helper.sh "what's new" # recent changes -``` - -### Step 3: Analyze Results & Decide - -Check which product contexts the results span: - -**Same context** (e.g., all Agent SDK) → **SYNTHESIZE**: -- Read ALL matching docs silently -- Extract relevant sections -- Present unified answer -- Cite sources at end - -**Different contexts** (e.g., CLI vs API vs SDK) → **ASK**: -- Use `AskUserQuestion` tool -- Present product options with user-friendly labels (see CLAUDE.md) -- After selection → synthesize within that context - -### Step 4: Present Naturally - -- Don't dump raw tool output -- Synthesize information from multiple sources -- Include code examples where relevant -- Always cite sources with links -- Suggest related topics - -## Quick Reference - -### User-Friendly Product Labels - -Use these when asking for clarification: - -| When docs are in | Say to user | -|------------------|-------------| -| `/docs/en/*` | Claude Code CLI | -| `/en/api/*` | Claude API | -| `/en/docs/agent-sdk/*` | Claude Agent SDK | -| `/en/docs/build-with-claude/*` | Claude Documentation | -| `/en/resources/prompt-library/*` | Prompt Library | - -### Example Interactions - -**Example 1: Clear context → Synthesize** -``` -User: /docs how do I use memory in agent sdk? - -You: -1. Extract: intent=how-to, context=agent_sdk, keywords=["memory"] -2. Search: content search in agent_sdk for "memory" -3. Find: python.md, overview.md, sessions.md (all Agent SDK) -4. Decision: Same context → Read all three, synthesize -5. Present: "In the Claude Agent SDK, memory works as follows..." - [Unified explanation from all three docs] - Sources: [links] -``` - -**Example 2: Ambiguous → Ask, then synthesize** -``` -User: /docs skills - -You: -1. Extract: intent=general, context=unclear, keywords=["skills"] -2. Search: content search for "skills" -3. Find: Agent SDK (5 docs), CLI (2 docs), API (7 docs) -4. Decision: Different products → Ask user - -Use AskUserQuestion: -"Skills exist in different Claude products: - -○ 1. Claude Agent SDK - Build custom agent capabilities -○ 2. Claude Code CLI - Install/run pre-built skills -○ 3. Claude API - Programmatic skill management - -Which are you working with?" - -5. User selects: 1 (Agent SDK) -6. Filter to Agent SDK, read all 5 docs, synthesize -7. Present unified Agent SDK skills explanation -``` - -## Error Handling - -- **No Python 3.9+**: Explain gracefully, suggest alternatives (direct lookups, list topics) -- **No results**: Suggest fuzzy matches, offer to search related terms -- **Ambiguous with no clear product boundary**: Ask for clarification - -## User's Request - -The user requested: "$ARGUMENTS" - -**Your task**: Follow the workflow above. Reference CLAUDE.md for detailed guidance on ambiguity resolution and synthesis strategies. - -## Execution Steps - -1. **Analyze the user's request** to determine routing: - - **Simple keyword** (e.g., "hooks", "mcp", "memory"): Route to content search - - **Question** (e.g., "how do I...", "what are..."): Route to content search - - **Exact filename** (e.g., "docs__en__hooks"): Route to direct lookup - - **Special flags** (e.g., "-t", "what's new"): Pass through directly - -2. **Execute appropriate command:** - - **For keywords/questions**: `~/.claude-code-docs/claude-docs-helper.sh --search-content "$ARGUMENTS"` - - **For exact filenames**: `~/.claude-code-docs/claude-docs-helper.sh "$ARGUMENTS"` - - **For special flags**: `~/.claude-code-docs/claude-docs-helper.sh "$ARGUMENTS"` - -3. **Analyze search results** (if using --search-content): - - Check which product contexts the results span - - **Same context**: Read ALL matching docs using exact filenames, synthesize unified answer - - **Different contexts**: Use AskUserQuestion with **ANTHROPIC PRODUCT NAMES** users know: - - "Claude Code" (NOT "CLI" or "claude_code") - - "Claude API" (NOT "api_reference") - - "Agent SDK" (NOT "agent-sdk paths") - - "Prompt Library", etc. - -4. **Always present naturally** - don't dump raw output, add context and links -EOF - -echo "✓ Created /docs command" - -# Clean up any old hooks from previous installations -if [ -f ~/.claude/settings.json ]; then - echo "Cleaning up old hooks..." - # Remove ALL hooks that contain "claude-code-docs" anywhere in the command - # This catches old installations at any path - jq '.hooks.PreToolUse = [(.hooks.PreToolUse // [])[] | select(.hooks[0].command | contains("claude-code-docs") | not)]' ~/.claude/settings.json > ~/.claude/settings.json.tmp - - # Clean up empty structures - jq 'if .hooks.PreToolUse == [] then .hooks |= del(.PreToolUse) else . end | if .hooks == {} then del(.hooks) else . end' ~/.claude/settings.json.tmp > ~/.claude/settings.json - rm -f ~/.claude/settings.json.tmp - echo "✓ Cleaned up old hooks" -fi - -# Note: Do NOT modify docs_manifest.json - it's tracked by git and would break updates - -# Clean up old installations now that v0.3 is set up -cleanup_old_installations - -# Verify installation -echo "" -echo "Verifying installation..." -VERIFY_FAILED=false - -# Check critical files exist -if [[ ! -f "$INSTALL_DIR/claude-docs-helper.sh" ]]; then - echo " ❌ Helper script missing" - VERIFY_FAILED=true -else - echo " ✓ Helper script installed" -fi - -if [[ ! -f "$INSTALL_DIR/scripts/claude-docs-helper.sh.template" ]]; then - echo " ❌ Template script missing" - VERIFY_FAILED=true -else - echo " ✓ Template script installed" -fi - -if [[ ! -d "$INSTALL_DIR/docs" ]]; then - echo " ❌ Documentation directory missing" - VERIFY_FAILED=true -else DOC_COUNT=$(find "$INSTALL_DIR/docs" -name "*.md" 2>/dev/null | wc -l | tr -d ' ') - if [[ "$DOC_COUNT" -lt 100 ]]; then - echo " ⚠️ Only $DOC_COUNT documentation files found (expected 250+)" - else - echo " ✓ Documentation files installed ($DOC_COUNT files)" - fi -fi - -if [[ ! -f ~/.claude/commands/docs.md ]]; then - echo " ❌ /docs command not created" - VERIFY_FAILED=true -else - echo " ✓ /docs command created" -fi - -# Test that helper script executes -if ! "$INSTALL_DIR/claude-docs-helper.sh" --help >/dev/null 2>&1; then - echo " ❌ Helper script fails to execute" - VERIFY_FAILED=true -else - echo " ✓ Helper script executes correctly" -fi - -if [[ "$VERIFY_FAILED" == "true" ]]; then - echo "" - echo "⚠️ Installation completed with warnings. Some components may not work correctly." - echo " Try reinstalling or check the issues above." -else - echo " ✓ All verification checks passed" -fi - -# Success message -echo "" -echo "✅ Claude Code Docs v$TARGET_VERSION installed successfully!" -echo "" - -# Set TARGET_DOCS from the doc count computed during verification -TARGET_DOCS="${DOC_COUNT:-0}" - -# Show upgrade summary if this was an upgrade -IFS='|' read -r prev_version prev_docs prev_packages <<< "$CURRENT_VERSION_INFO" -if [[ "$prev_version" != "none" && "$prev_version" != "$TARGET_VERSION" ]]; then - echo "┌─────────────────────────────────────────────────────────────────┐" - echo "│ UPGRADE COMPLETE │" - echo "├─────────────────────────────────────────────────────────────────┤" - printf "│ %-63s │\n" "Before: v$prev_version ($prev_docs documentation files)" - printf "│ %-63s │\n" "After: v$TARGET_VERSION ($TARGET_DOCS documentation files)" - echo "│ │" - echo "│ New Features: │" - echo "│ ✓ 2x documentation coverage │" - echo "│ ✓ Domain-based file naming (claude-code__*.md) │" - echo "│ ✓ Modular Python packages │" - echo "│ ✓ Safety thresholds for sync │" - echo "└─────────────────────────────────────────────────────────────────┘" - echo "" -fi - -echo "📚 Command: /docs (user)" -echo "📂 Location: ~/.claude-code-docs" -echo "" -echo "Usage examples:" -echo " /docs hooks # Read hooks documentation" -echo " /docs -t # Check when docs were last updated" -echo " /docs what's new # See recent documentation changes" -echo "" -echo "🔄 Updates: Run '/docs -t' to check for and pull latest documentation" -echo "" - -# Show what's installed -echo "📦 Installed Components:" -echo " • Documentation paths tracked (6 categories)" -echo " • AI-powered /docs command" -echo "" - -# Check if Python features are available and show appropriate message -if check_python_features; then - echo "✨ Python Features: AVAILABLE (Python 3.9+ detected)" - echo "" - - # Show category summary - python3 -c " -import json -data = json.load(open('$INSTALL_DIR/paths_manifest.json')) -total = data['metadata']['total_paths'] -cats = data['categories'] - -print(f'📚 Documentation Coverage: {total} paths across {len(cats)} categories') -print('') -print('Categories:') -for i, (cat, paths) in enumerate(cats.items(), 1): - cat_name = cat.replace('_', ' ').title() - print(f' {i}. {cat_name}: {len(paths)} paths') - -print('') -print('Python-Enhanced Commands:') -print(' ~/.claude-code-docs/claude-docs-helper.sh --search \"keyword\"') -print(' ~/.claude-code-docs/claude-docs-helper.sh --search-content \"term\"') -print(' ~/.claude-code-docs/claude-docs-helper.sh --validate') -print(' ~/.claude-code-docs/claude-docs-helper.sh --status') -" 2>/dev/null || { - # Fallback if Python fails - echo "📚 Python features available" - echo " Run: ~/.claude-code-docs/claude-docs-helper.sh --status" - } -else - echo "ℹ️ Python Features: NOT AVAILABLE" echo "" - echo "Basic documentation reading works perfectly!" - echo "Install Python 3.9+ to enable:" - echo " • Full-text content search (--search-content)" - echo " • Fuzzy path search (--search)" - echo " • Path validation (--validate)" - echo " • Enhanced AI routing capabilities" + echo "Documentation installed: $DOC_COUNT files at $INSTALL_DIR" echo "" - echo "Without Python, you can:" - echo " • Read all documentation paths via /docs command" - echo " • Use AI-powered semantic queries" - echo " • Check documentation freshness" - echo " • View recent changes" + echo "To use with Claude Code later, install the plugin:" + echo " /plugin marketplace add costiash/claude-code-docs" + echo " /plugin install claude-docs@claude-code-docs" fi echo "" -echo "💡 Tip: Run '/docs -t' periodically to get latest documentation updates" \ No newline at end of file +echo "Documentation: https://github.com/costiash/claude-code-docs" diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 19a6169b4..4c7ef75a0 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-docs", - "version": "0.6.0", + "version": "1.1.0", "description": "Searchable local mirror of Claude documentation. Provides the /docs command for instant access to API references, guides, and tutorials. Auto-discovery Skill reads docs automatically when you ask Claude-related questions. Docs auto-update via SessionStart hook.", "author": { "name": "costiash" diff --git a/plugin/commands/docs.md b/plugin/commands/docs.md index f5dc5908b..34bee6f89 100644 --- a/plugin/commands/docs.md +++ b/plugin/commands/docs.md @@ -1,84 +1,54 @@ # Claude Code Documentation — Plugin Command -You are a documentation assistant for Claude Code. Answer the user's question using locally-stored documentation. +You are a documentation assistant. Route the user's request to the appropriate skill. ## Documentation Location -Docs are stored at `~/.claude-code-docs/docs/` as markdown files. If this directory doesn't exist, inform the user: +Docs are stored at `~/.claude-code-docs/docs/`. If this directory doesn't exist, inform the user: -> Documentation not found. Run this to set up: +> Documentation not found. Set up with: > ``` -> git clone https://github.com/costiash/claude-code-docs.git ~/.claude-code-docs +> /plugin marketplace add costiash/claude-code-docs +> /plugin install claude-docs@claude-code-docs > ``` +> Then restart Claude Code so the SessionStart hook can clone the docs. -## How to Handle Requests +## Routing -### Step 1: Understand Intent +Analyze `$ARGUMENTS` and route: -Analyze `$ARGUMENTS` to determine: -- **Direct lookup**: User names a specific topic (e.g., "hooks", "mcp", "memory") -- **Information search**: User asks a question (e.g., "how do I use extended thinking?") -- **Discovery**: User wants to browse (e.g., "show me all MCP docs") -- **Freshness check**: `-t` flag or "what's new" +**No arguments / help** (empty, `--help`, `-h`, `help`): +→ Show brief usage: +> `/docs ` — Look up documentation (e.g., `/docs hooks`, `/docs agent sdk python`) +> `/docs --course ` — Generate an interactive HTML course on a topic +> `/docs --report` — Generate an HTML changelog of recent doc changes (with course buttons) +> `/docs -t` — Check documentation freshness +> `/docs what's new` — Show recent documentation changes +> `/docs ` — Ask a question about Claude (e.g., `/docs how do I configure MCP?`) -### Step 2: Find Relevant Documentation +**Freshness check** (`-t`, `--check`, `--freshness`, or user asks about freshness/health/validation): +→ Use the `claude-docs-validate` skill to check doc health and freshness. -**For direct lookup** — find files matching the topic: -1. Use Glob to find: `~/.claude-code-docs/docs/*$TOPIC*.md` -2. Common patterns: - - Claude Code CLI docs: `claude-code__.md` - - Platform docs: `docs__en__
__.md` -3. Read the matching file(s) +**What's new** (`what's new`, `recent changes`, `updates`): +→ Run: `cd ~/.claude-code-docs && git log --oneline -10 -- docs/` +→ Present the recent commits naturally. -**For information search** — search content: -1. Use Grep to search: `grep -ri "" ~/.claude-code-docs/docs/` -2. Read the top matching files -3. Extract relevant sections +**Changelog report** (`--report`, `--report `, `changelog`, `docs report`): +→ Use the `claude-docs-changelog` skill to generate an interactive HTML changelog report with course generation buttons. -**For discovery** — list available docs: -1. Use Glob: `~/.claude-code-docs/docs/*.md` -2. Filter by pattern if topic specified -3. Present organized list with categories +**Stats** (`--stats`, `stats`, `count`): +→ Count docs: `ls ~/.claude-code-docs/docs/*.md | wc -l` +→ Report total doc count and last update time. -**For freshness check** (`-t`): -1. Check git status: `cd ~/.claude-code-docs && git log -1 --format="%ci" && git pull --dry-run 2>&1` -2. Report last update time and whether updates are available -3. If updates available, run `cd ~/.claude-code-docs && git pull` +**Uninstall** (`uninstall`): +→ Tell the user: `/plugin uninstall claude-docs@claude-code-docs` +→ Optionally clean up: `rm -rf ~/.claude-code-docs` -### Step 3: Categorize Results +**Course generation** (`--course `, `course `): +→ Use the `claude-docs-course` skill to generate an interactive HTML course on the given topic. -When results span multiple product areas, use these labels: -- Files matching `claude-code__*.md` → **Claude Code CLI** -- Files matching `docs__en__agent-sdk__*.md` → **Claude Agent SDK** -- Files matching `docs__en__api__*.md` → **Claude API** -- Files matching `docs__en__build-with-claude__*.md` → **Claude Documentation** -- Files matching `docs__en__resources__prompt-library__*.md` → **Prompt Library** - -### Step 4: Present Results - -**Same product context** → Read ALL matching docs silently, synthesize unified answer, cite sources. - -**Different product contexts** → Ask user which product area with AskUserQuestion: -``` -"This topic exists in multiple Claude products: -○ 1. Claude Code CLI - ... -○ 2. Claude API - ... -Which are you working with?" -``` - -After selection → synthesize within that context. - -### Step 5: Always Include - -- Natural language synthesis (don't dump raw file contents) -- Source links: `claude-code__*.md` → `https://code.claude.com/docs/en/`, `docs__en__*.md` → `https://platform.claude.com/en/docs/` -- Suggest related topics when relevant - -## Special Commands - -- `$ARGUMENTS` is `-t` → Run freshness check -- `$ARGUMENTS` is `what's new` → Show recent git log: `cd ~/.claude-code-docs && git log --oneline -10` -- `$ARGUMENTS` is `uninstall` → Show plugin uninstall as primary: `/plugin uninstall claude-docs@claude-code-docs`, with manual fallback: `rm -rf ~/.claude-code-docs` +**Everything else** (topic lookups, questions, searches): +→ Use the `claude-docs` skill to find and present documentation. ## User's Request diff --git a/plugin/skills/claude-docs-changelog/SKILL.md b/plugin/skills/claude-docs-changelog/SKILL.md new file mode 100644 index 000000000..ef6323a1c --- /dev/null +++ b/plugin/skills/claude-docs-changelog/SKILL.md @@ -0,0 +1,294 @@ +--- +name: claude-docs-changelog +description: > + Generate a self-contained HTML changelog report showing recent documentation + changes with interactive course generation buttons. Use this skill when the + user asks for a docs changelog, documentation report, what changed recently, + recent doc updates as a report, or runs `/docs --report`. Discovers changes + via git history, categorizes them, summarizes what's new, and produces a + stunning Obsidian & Amber themed HTML report where each entry has a + "Create Course" button that copies the course command to clipboard. +--- + +# Documentation Changelog Report + +Generate a self-contained HTML report showing recent documentation changes. The report groups changes by category, summarizes what's new or updated, and includes a "Create Course" button on each card so the user can instantly generate an interactive course for any topic that caught their eye. + +## When to Trigger + +- User says "docs changelog", "docs report", "what changed in the docs", "recent doc updates report" +- User runs `/docs --report`, `/docs changelog`, or `/docs --report ` +- User asks for a visual summary of documentation changes + +## The Process (3 Phases) + +### Phase 1: Discover Changes + +**Find what changed in the documentation directory:** + +```bash +cd ~/.claude-code-docs && git log --since="" --name-status --pretty=format:"%H %ai %s" -- docs/ +``` + +**Default timeframe:** Last 7 days. The user can specify a different window: +- `/docs --report` → last 7 days +- `/docs --report 24h` → last 24 hours +- `/docs --report 30d` → last 30 days +- `/docs --report 2026-03-20` → since that date + +**Parse the output:** +- `A` = Added (new doc) +- `M` = Modified (updated doc) +- `D` = Deleted (removed doc) + +If there are no changes in the timeframe, tell the user and suggest a wider window. + +**Categorize each file** using the same patterns from `manifest-reference.md`: + +| File pattern | Category | Label | +|---|---|---| +| `claude-code__*.md` | cli | Claude Code CLI | +| `docs__en__agent-sdk__*.md` | sdk | Agent SDK | +| `docs__en__api__*.md` | api | Claude API | +| `docs__en__agents-and-tools__*.md` | tools | Agents & Tools | +| `docs__en__build-with-claude__*.md` | platform | Claude Platform | +| `docs__en__about-claude__*.md` | about | About Claude | +| `docs__en__resources__prompt-library__*.md` | prompts | Prompt Library | +| `docs__en__test-and-evaluate__*.md` | testing | Testing & Evaluation | +| `docs__en__release-notes__*.md` | releases | Release Notes | + +**Limit scope:** If there are more than 30 changed files, focus on the most recent 30 and note how many were omitted. + +### Phase 2: Analyze Changes + +For each changed file (or the most significant ones if there are many): + +1. **Read the file** to understand the current content +2. If the file was modified (not new), run `git diff` on it to see what specifically changed +3. **Extract key points:** What's new? What was updated? What are the highlights? +4. **Write a 1-2 sentence summary** of the change +5. **Extract 3-6 bullet points** describing specific additions or updates + +**For new files (A):** Read the full file and summarize what it covers. +**For modified files (M):** Focus on what changed in the diff, not the entire file. +**For deleted files (D):** Just note what was removed with a one-line description. + +Group related changes (e.g., if 6 SDK language docs were all updated the same way, combine them into one card). + +### Phase 3: Generate the HTML Report + +Generate a single self-contained HTML file using the **Obsidian & Amber** design system. Save to: + +```bash +mkdir -p ~/.claude-code-docs/courses +``` + +Name the file: `~/.claude-code-docs/courses/changelog-.html` (e.g., `changelog-2026-03-28.html`) + +**HTML structure:** + +``` +├── Header (title, date range, sync status badge) +├── Stats bar (count per category with colored numbers) +├── Key Highlights box (3-6 most notable changes) +├── Section per category +│ ├── Section heading (icon, label, count) +│ └── Cards per changed doc +│ ├── Title + tag (New/Updated/Removed) +│ ├── Summary paragraph +│ ├── Bullet list of key changes +│ ├── Source link → official docs URL +│ └── "Create Course" button +└── Footer (generated from, doc count, date) +``` + +**Design rules (Obsidian & Amber):** + +Use these exact CSS variables from the course design system: + +```css +:root { + --bg: #0D0D16; + --surface: #161624; + --surface-hover: #1C1A28; + --border: #2A2840; + --text: #E8E0D4; + --text-muted: #5C5852; + --accent: #F0A050; + --accent-dim: rgba(240, 160, 80, 0.08); + --blue: #60A0E0; + --blue-dim: rgba(96, 160, 224, 0.08); + --green: #50C8A0; + --green-dim: rgba(80, 200, 160, 0.08); + --purple: #C080E0; + --purple-dim: rgba(192, 128, 224, 0.08); + --red: #F06060; + --red-dim: rgba(240, 96, 96, 0.06); + --radius: 10px; +} +``` + +**Typography:** Use the same fonts as the course skill: +```html + +``` +- `Instrument Serif` for h1/h2 headings +- `Outfit` for body text +- `JetBrains Mono` for code and badges + +**Include the grain overlay** (same as course design system): +```css +body::after { + content: ''; + position: fixed; top: 0; left: 0; + width: 100%; height: 100%; + pointer-events: none; z-index: 9999; opacity: 0.035; + background-image: url("data:image/svg+xml,..."); /* same noise SVG */ +} +``` + +**Card styling:** +- Background: `--surface` with `--border` border +- Hover: border shifts to `--accent` muted, subtle glow +- Inner shadow highlight: `inset 0 1px 0 rgba(255,255,255,0.04)` + +**Tags:** +- `New` → green badge (`--green-dim` bg, `--green` text) +- `Updated` → blue badge (`--blue-dim` bg, `--blue` text) +- `Removed` → red badge (`--red-dim` bg, `--red` text) +- `Beta` → purple badge (`--purple-dim` bg, `--purple` text) + +**Category icons:** +- CLI: `>_` (terminal prompt) +- SDK: `{}` (code braces) +- API: `⟡` (diamond) +- Platform: `◈` (nested diamond) +- Prompt Library: `✎` (pen) +- Other: `●` (dot) + +### The "Create Course" Button + +Each card gets a button in its footer area that lets the user generate a course for that topic. + +**Button behavior (JavaScript):** +1. On click, copy the command `/docs --course ` to the clipboard +2. Show a toast notification: "Copied! Paste in Claude Code to generate a course." +3. The toast auto-dismisses after 3 seconds + +**Button HTML pattern:** +```html + +``` + +**Button CSS:** +```css +.course-btn { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 14px; + border-radius: 999px; + border: 1px solid var(--accent); + background: var(--accent-dim); + color: var(--accent); + font-family: 'Outfit', sans-serif; + font-size: 0.78rem; + font-weight: 600; + cursor: pointer; + transition: all 0.2s; +} +.course-btn:hover { + background: var(--accent); + color: var(--bg); + box-shadow: 0 0 20px rgba(240, 160, 80, 0.25); +} +.course-btn-icon { + font-size: 0.65rem; +} +``` + +**Toast notification:** +```css +.toast { + position: fixed; + bottom: 2rem; + left: 50%; + transform: translateX(-50%) translateY(20px); + background: var(--surface); + border: 1px solid var(--accent); + color: var(--accent); + padding: 0.75rem 1.5rem; + border-radius: var(--radius); + font-family: 'Outfit', sans-serif; + font-size: 0.88rem; + font-weight: 500; + box-shadow: 0 8px 32px rgba(0,0,8,0.5), 0 0 20px rgba(240,160,80,0.15); + opacity: 0; + transition: opacity 0.3s, transform 0.3s; + z-index: 10000; +} +.toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); +} +``` + +**JavaScript:** +```javascript +function copyCourseCmd(btn) { + const topic = btn.dataset.topic; + const cmd = '/docs --course ' + topic; + navigator.clipboard.writeText(cmd).then(() => { + showToast('Copied! Paste in Claude Code: ' + cmd); + }).catch(() => { + // Fallback for older browsers + const ta = document.createElement('textarea'); + ta.value = cmd; document.body.appendChild(ta); + ta.select(); document.execCommand('copy'); + document.body.removeChild(ta); + showToast('Copied! Paste in Claude Code: ' + cmd); + }); +} + +function showToast(msg) { + let toast = document.getElementById('toast'); + if (!toast) { + toast = document.createElement('div'); + toast.id = 'toast'; + toast.className = 'toast'; + document.body.appendChild(toast); + } + toast.textContent = msg; + toast.classList.add('show'); + clearTimeout(toast._timeout); + toast._timeout = setTimeout(() => toast.classList.remove('show'), 3000); +} +``` + +### Phase 4: Open and Present + +After generating the HTML: +1. Open it in the browser +2. Tell the user where it's saved: `~/.claude-code-docs/courses/changelog-.html` +3. Summarize the key findings: "Found X changes across Y categories in the last Z days." +4. Mention they can click "Create Course" on any card to copy the course generation command + +## URL Generation + +Use the same URL rules as the `claude-docs` skill: +- `claude-code__.md` → `https://code.claude.com/docs/en/` +- `docs__en__.md` → `https://platform.claude.com/en/docs/` (replace `__` with `/`) + +## Topic Extraction for Course Buttons + +The `data-topic` attribute on each course button should be the human-readable topic name extracted from the filename: +- `claude-code__hooks.md` → `hooks` +- `claude-code__hooks-guide.md` → `hooks guide` +- `docs__en__agent-sdk__python.md` → `Agent SDK Python` +- `docs__en__build-with-claude__prompt-caching.md` → `prompt caching` +- `docs__en__agents-and-tools__tool-use__overview.md` → `tool use` + +Strip the category prefix, replace `__` and `-` with spaces, and capitalize naturally. diff --git a/plugin/skills/claude-docs-changelog/examples/changelog-report.md b/plugin/skills/claude-docs-changelog/examples/changelog-report.md new file mode 100644 index 000000000..058f51f1a --- /dev/null +++ b/plugin/skills/claude-docs-changelog/examples/changelog-report.md @@ -0,0 +1,45 @@ +# Example: Documentation Changelog Report + +## User Query +> /docs --report + +## Skill Reasoning +- User requests a docs changelog report +- Default timeframe: last 7 days +- Strategy: git log → categorize → analyze → generate HTML + +## Actions + +### Phase 1: Discover Changes +1. Run: `cd ~/.claude-code-docs && git log --since="7 days ago" --name-status --pretty=format:"%H %ai %s" -- docs/` +2. Parse output — found 12 changed files: + - 5 Modified in `claude-code__*.md` (CLI category) + - 6 Modified in `docs__en__agent-sdk__*.md` (SDK category) + - 1 Added: `docs__en__agent-sdk__tool-search.md` (SDK, new) + +### Phase 2: Analyze Changes +1. Read each changed file + `git diff` for modified files +2. Group related changes (e.g., 5 SDK language docs with same update → 1 card) +3. Extract highlights: + - New: Tool Search feature in Agent SDK + - Updated: Desktop app, Sandboxing, Plugin Marketplaces, Common Workflows + - Updated: Custom Tools, MCP, Python/TypeScript SDKs, User Input + +### Phase 3: Generate HTML +1. Create `~/.claude-code-docs/courses/changelog-2026-03-28.html` +2. Structure: header → stats bar → highlights → CLI section (5 cards) → SDK section (6 cards) → Platform section (1 card) +3. Each card gets a "Create Course" button with `data-topic` extracted from filename +4. Course button copies `/docs --course ` to clipboard on click + +### Phase 4: Open and Present +- Open in browser +- "Found 12 changes across 3 categories in the last 7 days. Saved to `~/.claude-code-docs/courses/changelog-2026-03-28.html`" + +## Output +Self-contained HTML file with: +- Obsidian & Amber dark theme (matching course design system) +- Stats bar: 5 CLI, 6 SDK (1 new), 1 Platform +- Key highlights box with top 6 changes +- 8 cards (grouped) with summaries, bullet lists, source links +- Each card has a "Create Course" button → copies clipboard command +- Toast notification on button click diff --git a/plugin/skills/claude-docs-course/SKILL.md b/plugin/skills/claude-docs-course/SKILL.md new file mode 100644 index 000000000..97fee7184 --- /dev/null +++ b/plugin/skills/claude-docs-course/SKILL.md @@ -0,0 +1,343 @@ +--- +name: claude-docs-course +description: > + Generate an interactive, self-contained HTML course on any Claude documentation + topic. Use this skill when the user wants to create an interactive course, + tutorial, or deep-dive walkthrough about a Claude feature, API concept, SDK + pattern, or prompt engineering technique. Triggers on: "create a course about", + "interactive tutorial for", "teach me about X interactively", "make a course on", + "I'd like a course", "/docs --course", "/docs course", or when the user accepts + the post-docs course prompt. Produces a stunning single-page HTML file with + scroll-based navigation, animated visualizations, quizzes, and code translations + drawn from official Claude documentation. +--- + +# Docs-to-Course + +Transform any Claude documentation topic into a stunning, interactive single-page HTML course. The output is a single self-contained HTML file (no dependencies except Google Fonts) that teaches the topic through scroll-based modules, animated visualizations, embedded quizzes, and plain-English translations of real API examples and configuration snippets from the official docs. + +## First-Run Welcome + +When the skill is first triggered and the user hasn't specified a topic yet, introduce yourself: + +> **I can turn any Claude topic into an interactive course — visual explanations, animated diagrams, and hands-on quizzes, all in a single HTML file.** +> +> Tell me a topic: +> - **A Claude Code feature** — e.g., "create a course on hooks" +> - **An API concept** — e.g., "make a course about tool use" +> - **An SDK pattern** — e.g., "interactive tutorial for Agent SDK sessions" +> - **A technique** — e.g., "teach me about extended thinking interactively" +> +> I'll read through the official documentation, design a learning arc, and generate a beautiful single-page HTML course with animated protocol diagrams, code explanations, and interactive quizzes. Opens right in your browser — no setup needed. + +If the user just came from a `/docs` response, the topic is already known — skip the welcome and start building. + +## Who This Is For + +The target learner is a **developer building with Claude** — someone who has general technical literacy but wants to deeply understand a specific Claude feature, API concept, or SDK pattern before using it in their project. + +**Assume general technical literacy.** The learner knows what APIs, functions, JSON, and HTTP requests are. They don't need basic programming concepts explained. But they DO need Claude-specific concepts, patterns, and terminology explained thoroughly — tokens, context windows, tool_use blocks, stop sequences, system prompts, streaming events, hook matchers, MCP servers, etc. + +**Their goals are practical:** +- **Master a Claude feature** before using it in production — understand not just the API surface, but the mental model, edge cases, and best practices +- **Make confident architectural decisions** — know which Claude feature to use for a given problem, understand tradeoffs +- **Debug effectively** — when something doesn't work as expected, know where to look and what to check +- **Stay current** — Claude's capabilities evolve fast; deep understanding beats surface-level familiarity +- **Communicate precisely** — use the correct terminology when discussing Claude integrations with teammates + +**They are NOT beginners at programming.** They're experienced developers who are new (or deepening) in a specific Claude feature. The course should respect their time and intelligence while making the Claude-specific material stick. + +## Why This Approach Works + +Documentation is comprehensive but flat — it lists features, parameters, and examples without a learning arc. This skill transforms documentation into a **structured learning experience** with visual explanations, interactive elements, and progressive disclosure. + +The learner already has context: they've used Claude, they've called the API, they may have built with some features already. The course meets them where they are: "You've been passing messages to the API — here's what's actually happening under the hood, and here's how to unlock the advanced patterns." + +Every module answers **"when and why would I use this?"** before "how does it work?" The answer is always practical: *because this pattern solves a real problem you'll encounter when building with Claude.* + +The single-file constraint is intentional: one HTML file means zero setup, instant sharing with teammates, works offline, and forces tight design decisions. + +--- + +## The Process (4 Phases) + +### Phase 1: Topic Discovery + +Before writing course HTML, deeply understand the topic by reading all relevant documentation. Thoroughness here pays off — the more you understand, the better the course. + +**How to find documentation files:** + +Search `~/.claude-code-docs/docs/` using this hierarchy (try simpler strategies first): + +1. **Direct Glob** — for concrete topic names: + ``` + Glob: ~/.claude-code-docs/docs/**.md + ``` + +2. **Scoped Glob** — when the product context is known: + | Context | Glob pattern | + |---------|-------------| + | Claude Code CLI | `~/.claude-code-docs/docs/claude-code__**.md` | + | Agent SDK | `~/.claude-code-docs/docs/docs__en__agent-sdk__**.md` | + | Claude API | `~/.claude-code-docs/docs/docs__en__api__**.md` | + | Build guides | `~/.claude-code-docs/docs/docs__en__build-with-claude__**.md` | + | Agents & tools | `~/.claude-code-docs/docs/docs__en__agents-and-tools__**.md` | + +3. **Content search** — for questions or compound topics: + ```bash + bash ~/.claude-code-docs/plugin/skills/claude-docs/scripts/content-search.sh "" "" + ``` + +4. **Fuzzy search** — for approximate names: + ```bash + bash ~/.claude-code-docs/plugin/skills/claude-docs/scripts/fuzzy-search.sh "" + ``` + +**What to read:** +- Read the top 5-8 matching docs for the topic +- Read 1-2 adjacent/related docs for context (e.g., if the topic is "hooks", also skim the skills and settings docs) +- Cap at 10 docs total to avoid context exhaustion + +**What to extract:** +- Concept definitions and mental models — how does this feature actually work? +- API endpoints, parameters, and their purposes +- Real code examples (Python, TypeScript, cURL, JSON configs) — these become your code translations +- Configuration options and their defaults +- Common patterns and recommended approaches +- Edge cases, gotchas, and error scenarios +- Connections to related features + +**Figure out the learning story yourself** from the documentation. Don't ask the user to explain the topic — build the narrative from what the docs reveal. The course should open by explaining why this feature exists and what problem it solves, then progressively peel back layers. + +### Phase 2: Curriculum Design + +Structure the course as 4-7 modules. Documentation topics are typically more focused than entire codebases, so fewer modules are usually appropriate. The arc starts from what the learner already knows (general Claude usage) and moves toward what they don't (deep feature knowledge). + +| Module Position | Purpose | Example for "hooks" | +|---|---|---| +| 1 | "What is this and why should you care?" | What hooks are, what problems they solve, what you can automate | +| 2 | "The mental model" | Hook lifecycle diagram, event types, when each fires | +| 3 | "See it in action" | Real hook configs with code translations, walking through examples | +| 4 | "The details that matter" | Matcher patterns, JSON schemas, timeout handling, async behavior | +| 5 | "Patterns and recipes" | Common use cases — auto-formatting, CI/CD gates, security checks | +| 6 | "Connect the dots" | How hooks relate to skills, MCP, permissions — the bigger picture | + +Not every topic needs all 6. A narrow feature (like "prompt caching") might only need 3-4 modules. A broad one (like "tool use") might need 6-7. Adapt the arc to the topic's depth. + +**The key principle:** Every module should connect to a practical skill — building better, debugging faster, or making smarter architecture decisions. If a module doesn't help the learner DO something, cut it or reframe it until it does. + +**Each module should contain:** +- 3-6 screens (sub-sections that flow within the module) +- At least one code-with-English translation (API calls, config snippets, CLI commands) +- At least one interactive element (quiz, visualization, or animation) +- One or two "aha!" callout boxes with practical insights +- A metaphor that grounds the Claude concept in something tangible — but NEVER reuse the same metaphor across modules. Pick metaphors that organically fit each specific concept. Examples: hooks are "tripwires that trigger actions", streaming is a "live news ticker", tool use is a "Swiss army knife Claude carries", context windows are "working memory on a desk", prompt caching is "bookmarking your place in a conversation". + +**Mandatory interactive elements (every course must include ALL of these):** +- **Protocol Conversation** — at least one across the course. iMessage/chat-style conversations between system actors (Client App, Claude API, Claude Model, Tool Server) showing how they exchange messages. These bring protocol-level concepts to life. +- **Data Flow Animation** — at least one across the course. Step-by-step visualization of data moving through the system — API request lifecycles, streaming event flows, hook execution chains. +- **Code ↔ English Translation Blocks** — at least one per module. Real code from the documentation (API calls, JSON configs, CLI commands) with plain-English translation on the right. +- **Quizzes** — at least one per module (multiple-choice, scenario, drag-and-drop, or spot-the-bug). +- **Glossary Tooltips** — on every Claude-specific term, first use per module. + +These five element types are the backbone of every course. Other interactive elements (architecture diagrams, layer toggles, pattern cards, etc.) are optional and should be added when they fit. But the five above must ALWAYS be present — no exceptions. + +**Do NOT present the curriculum for approval — just build it.** The user wants a course, not a planning document. Design the curriculum internally, then go straight to generating the HTML. If they want changes, they'll tell you after seeing the result. + +### Phase 3: Build the Course + +Generate a single HTML file with embedded CSS and JavaScript. Read `references/design-system.md` for the complete CSS design tokens, typography, and color system. Read `references/interactive-elements.md` for implementation patterns of every interactive element type. + +**Build order (task by task):** + +1. **Foundation first** — HTML shell with all module sections (empty), complete CSS design system, navigation bar with progress tracking, scroll-snap behavior, keyboard navigation, and scroll-triggered animations. After this step, you should have a working skeleton you can scroll through. + +2. **One module at a time** — Fill in each module's content, code translations, and interactive elements. Don't try to write all modules in one pass — the quality drops. Build Module 1, verify it works, then Module 2, etc. + +3. **Polish pass** — After all modules are built, do a final pass for transitions, mobile responsiveness, and visual consistency. + +**Critical implementation rules:** +- The file must be completely self-contained (only external dependency: Google Fonts CDN) +- Use CSS `scroll-snap-type: y proximity` (NOT `mandatory` — mandatory traps users in long modules) +- Use `min-height: 100dvh` with `100vh` fallback for sections +- Only animate `transform` and `opacity` for GPU performance +- Wrap all JS in an IIFE, use `passive: true` on scroll listeners, throttle with `requestAnimationFrame` +- Include touch support for drag-and-drop, keyboard navigation (arrow keys), and ARIA attributes + +### Phase 4: Save, Review, and Open + +**Save the course** to the dedicated courses directory: + +```bash +mkdir -p ~/.claude-code-docs/courses +``` + +Name the file based on the topic: `~/.claude-code-docs/courses/.html` +- Use kebab-case: "prompt caching" → `prompt-caching.html`, "tool use" → `tool-use.html` +- If a file with that name already exists, append a number: `hooks-2.html` + +After saving, open the file in the browser for the user to review. Walk them through what was built — the module arc, the key interactive elements, and the learning progression. Tell them where the file is saved so they can share it or revisit it later. Ask for feedback on content, design, and interactivity. + +--- + +## Content Philosophy + +These principles are what separate a great course from a generic tutorial. They should guide every content decision: + +### Show, Don't Tell — Aggressively Visual +Developers' eyes glaze over text blocks too. The course should feel closer to an interactive reference than a wall of documentation. Follow these hard rules: + +**Text limits:** +- Max **2-3 sentences** per text block. If you're writing a fourth sentence, stop and convert it into a visual instead. +- No text block should ever be wider than the content width AND taller than ~4 lines. If it is, break it up with a visual element. +- Every screen must be **at least 50% visual** (diagrams, code blocks, cards, animations, badges — anything that isn't a paragraph). + +**Convert text to visuals:** +- A list of 3+ items → **cards with icons** (pattern cards, feature cards) +- A sequence of steps → **flow diagram with arrows** or **numbered step cards** +- "Client sends request to API" → **animated data flow** or **protocol conversation** +- "This parameter does X, that parameter does Y" → **side-by-side comparison columns** or **config badges** +- Explaining what code does → **code↔English translation block** (not a paragraph *about* the code) +- Comparing two approaches → **side-by-side columns** with visual contrast + +**Visual breathing room:** +- Use generous spacing between elements (`--space-8` to `--space-12` between sections) +- Alternate between full-width visuals and narrow text blocks to create rhythm +- Every module should have at least one "hero visual" — a diagram, animation, or interactive element that dominates the screen and teaches the core concept at a glance + +### Code ↔ English Translations +Every code example gets a side-by-side plain English translation. Left panel: real code from the documentation (API calls, JSON configs, CLI commands) with syntax highlighting. Right panel: line-by-line plain English explaining what each part does and *why*. + +**Critical: No horizontal scrollbars on code.** All code must use `white-space: pre-wrap` so it wraps instead of scrolling. Readability beats preserving indentation structure. + +**Critical: Use documentation examples exactly as-is.** Never modify, simplify, or trim code examples from the docs. The learner should be able to find the exact same example in the official documentation — that builds trust and makes the course a companion to the docs, not a replacement. Instead of editing code to make it shorter, *choose* naturally short, punchy examples (5-15 lines) from the docs that illustrate the concept well. + +### One Concept Per Screen +No walls of text. Each screen within a module teaches exactly one idea. If you need more space, add another screen — don't cram. + +### Metaphors First, Then Reality +Introduce every new Claude concept with a metaphor from everyday life. Then immediately ground it: "In Claude's API, this looks like..." The metaphor builds intuition; the code grounds it in reality. + +**Critical: No recycled metaphors.** Each concept deserves its own metaphor that feels natural to *that specific idea*. Context windows as "desk space", tokens as "word fragments in a shredder", system prompts as "stage directions for an actor", tool use as "a Swiss army knife", streaming as "a live ticker". Pick the metaphor that makes the concept click, not the one that's easiest to reach for. + +### Learn by Tracing +Follow what actually happens when the developer makes a familiar API call — trace the request end-to-end. "You've been sending messages to Claude — here's the full lifecycle of that request, from your code to Claude's response, step by step." This works because the learner has *already used the feature* — now they're seeing the machinery behind it. + +### Make It Memorable +Use "aha!" callout boxes for practical insights. Use humor where natural (not forced). Give system actors personality in protocol conversations — Claude, the API gateway, the tool server are "characters" in the story, not abstract boxes. + +### Glossary Tooltips — Claude-Specific Terms +Every Claude-specific term gets a dashed-underline tooltip on first use in each module. Hover on desktop or tap on mobile to see a 1-2 sentence definition grounded in practical usage. + +**Tooltip scope for developer audience:** Don't tooltip basic programming terms (function, variable, JSON, API). DO tooltip: +- Claude-specific concepts: tokens, context window, stop sequences, tool_use blocks, content blocks, thinking blocks +- Anthropic-specific terms: Messages API, Admin API, prompt caching, extended thinking, adaptive thinking +- Claude Code terms: hooks, matchers, skills, MCP servers, CLAUDE.md, sub-agents +- Agent SDK terms: sessions, agent loop, tool search, slash commands +- Protocol terms: SSE (Server-Sent Events), streaming deltas, stop_reason values +- Acronyms on first use — even common ones in a Claude context (MCP, SSE, IIFE, ARIA) + +**The vocabulary IS the learning.** Each tooltip should teach the term in a way that helps the learner USE it correctly — e.g., "**stop_reason** — tells you *why* Claude stopped generating. `end_turn` means Claude finished naturally. `tool_use` means Claude wants to call a tool. Check this to decide your next action." + +**Cursor:** Use `cursor: pointer` on terms (not `cursor: help`). The question-mark cursor feels clinical — a pointer feels clickable and inviting. + +**Tooltip overflow fix:** Translation blocks and other containers with `overflow: hidden` will clip tooltips. To fix this, the tooltip JS must use `position: fixed` and calculate coordinates from `getBoundingClientRect()` instead of relying on CSS `position: absolute` within the container. Append tooltips to `document.body` rather than inside the term element. + +### Quizzes That Test Application, Not Memory + +Quizzes should test whether the learner can use their knowledge to solve a real problem, not whether they can regurgitate parameter names. + +**What to quiz (in order of value):** +1. **"What would you use?" scenarios** — "You want to let Claude browse the web during a conversation. Which feature would you configure?" Tests whether they understood the feature landscape. +2. **Debugging scenarios** — "Your streaming response cuts off mid-sentence with stop_reason: max_tokens. What's happening and what should you change?" Tests practical understanding. +3. **Architecture decisions** — "You're building an agent that needs to remember context across sessions. Which approach would you use: prompt caching, the Files API, or external storage?" Tests tradeoff reasoning. +4. **Configuration challenges** — "Write the hook matcher JSON that would block all file deletions during CI runs." Tests whether they can apply the syntax. + +**What NOT to quiz:** +- Definitions ("What is a token?") — that's what the glossary tooltips are for +- Parameter recall ("What's the default max_tokens?") — that's what docs are for +- Exact syntax ("Write the correct API call") — this isn't a coding exam +- Anything that can be answered by scrolling up — that tests scrolling, not understanding + +**Quiz tone:** +- Wrong answers get encouraging, helpful explanations ("Not quite — here's why...") +- Correct answers get brief reinforcement of the underlying principle ("Exactly! This works because...") +- Never punitive, never score-focused. No "You got 3/5!" — the quiz is a thinking exercise, not an exam + +**How many quizzes:** One per module, placed at the end. 3-5 questions per quiz. Each question should make the learner pause and *think*. + +--- + +## Topic Scope Control + +Documentation topics vary wildly in breadth. A clear scoping strategy prevents courses from becoming unfocused. + +**Narrow topics** (hooks, prompt caching, streaming) — 3-5 modules, read all relevant docs. These make the best courses. + +**Medium topics** (tool use, Agent SDK, MCP) — 5-7 modules. May need to prioritize which aspects to cover deeply vs. mention in passing. + +**Broad topics** (Claude API, "everything about Claude Code") — Too broad for a single course. Narrow to a specific sub-topic and suggest related courses: +> "The Claude API is too broad for one course. I'll focus on **the Messages API and tool use** — the core of building with Claude. For streaming, batch processing, and admin APIs, you can generate separate courses." + +**Rule of thumb:** If you'd need to read more than 10 doc files to cover the topic, it's too broad. Narrow it. + +--- + +## Design Identity — Obsidian & Amber + +The visual design should feel like discovering knowledge in a **luxury developer observatory** — deep, atmospheric, and unmistakable. Read `references/design-system.md` for the full token system, but here are the non-negotiable principles: + +- **Dark obsidian palette**: Deep navy-black backgrounds (#0D0D16) with warm undertones — never pure black, never cold gray. The darkness creates focus; the warmth creates comfort. +- **Amber accent**: Warm amber-gold (#F0A050) as the signature color. Used sparingly — for interactive highlights, active states, and glow effects. Amber evokes lamplight, discovery, and illumination. +- **Editorial typography**: Instrument Serif for display headings — sharp, elegant serifs that create immediate visual identity. The contrast between serif headings and clean sans body text (Outfit) is the signature of this theme. NEVER use Inter, Roboto, Arial, Space Grotesk, or any generic sans-serif for headings. +- **Generous whitespace**: Modules breathe against the dark background. Max 3-4 short paragraphs per screen. +- **Alternating depths**: Even/odd modules alternate between two dark tones for subtle visual rhythm +- **Inky code blocks**: Near-black (#08080F) with amber-tinted syntax highlighting that echoes the theme accent +- **Grain texture**: Subtle analog noise overlay across all surfaces — adds warmth and prevents the "dead screen" flatness of digital dark themes +- **Amber glow**: Interactive elements emit a soft amber glow on hover and focus, drawing the eye like lamplight +- **Glass-morphism**: Elevated surfaces use backdrop-filter blur with faint border highlights for depth + +--- + +## Gotchas — Common Failure Points + +Check every one of these before considering a course complete. + +### Tooltip Clipping +Translation blocks use `overflow: hidden` for code wrapping. If tooltips use `position: absolute` inside the term element, they get clipped by the container. **Fix:** Tooltips must use `position: fixed` and be appended to `document.body`. Calculate position from `getBoundingClientRect()`. This is the #1 bug in every build. + +### Under-Tooltipping Claude Terms +The most common failure is under-tooltipping. Claude-specific terms like MCP, SSE, content blocks, stop_reason, tool_use, matchers, CLAUDE.md, sub-agents — all need tooltips on first use per module. **Rule:** if a term is specific to Claude/Anthropic and wouldn't be known to a developer who hasn't used Claude before, tooltip it. + +### Walls of Text +The course looks like reformatted documentation instead of a visual learning experience. This happens when you write more than 2-3 sentences in a row without a visual break. Every screen must be at least 50% visual. + +### Recycled Metaphors +Using the same metaphor for different concepts. Every module needs its own metaphor that feels inevitable for that specific concept. + +### Documentation Example Modifications +Trimming, simplifying, or "cleaning up" code examples from the docs. The learner should be able to find the exact same code in the official documentation. Choose naturally short examples rather than editing longer ones. + +### Topic Scope Creep +Trying to cover everything related to a topic instead of staying focused. If the topic is "hooks," don't also try to teach MCP, skills, and permissions in depth. Mention them in the "Connect the dots" module and suggest separate courses. + +### Quiz Questions That Test Memory +Asking "What's the default max_tokens?" or "Name the hook event types" — those test recall, not understanding. Every quiz question should present a scenario the learner hasn't seen and ask them to *apply* what they learned. + +### Scroll-Snap Mandatory +Using `scroll-snap-type: y mandatory` traps users inside long modules. Always use `proximity`. + +### Module Quality Degradation +Trying to write all modules in one pass causes later modules to be thin and rushed. Build one module at a time and verify each before moving on. + +### Missing Interactive Elements +A module with only text and code blocks, no interactivity. Every module needs at least one of: quiz, data flow animation, protocol conversation, architecture diagram, drag-and-drop. + +--- + +## Reference Files + +The `references/` directory contains detailed implementation specs. Read them when you reach the relevant phase: + +- **`references/design-system.md`** — Complete CSS custom properties, color palette, typography scale, spacing system, shadows, animations, scrollbar styling. Read this before writing any CSS. +- **`references/interactive-elements.md`** — Implementation patterns for every interactive element: drag-and-drop quizzes, multiple-choice quizzes, code↔English translations, protocol conversations, message flow visualizations, architecture diagrams, pattern cards, callout boxes. Read this before building any interactive elements. diff --git a/plugin/skills/claude-docs-course/examples/course-from-docs.md b/plugin/skills/claude-docs-course/examples/course-from-docs.md new file mode 100644 index 000000000..932eb61ea --- /dev/null +++ b/plugin/skills/claude-docs-course/examples/course-from-docs.md @@ -0,0 +1,58 @@ +# Example: Interactive Course from Documentation + +## User Query +> /docs --course hooks + +## Skill Reasoning +- User requests an interactive course on "hooks" +- Strategy: Topic Discovery → find all hooks-related documentation files + +## Actions + +### Phase 1: Topic Discovery +1. **Glob:** `~/.claude-code-docs/docs/*hooks*.md` + - Results: `claude-code__hooks.md`, `claude-code__hooks-guide.md`, `docs__en__agent-sdk__hooks.md` +2. **Read all 3 files** — extract concept definitions, JSON config examples, matcher patterns, event types, lifecycle details +3. **Adjacent docs for context:** Skim `claude-code__skills.md`, `claude-code__settings.md` for related features +4. **Extracted material:** + - Hook event types: PreToolUse, PostToolUse, SessionStart, etc. + - JSON configuration format with matcher patterns + - Shell script examples for hook commands + - Agent SDK hook variants (Python/TypeScript) + +### Phase 2: Curriculum Design +Design 6-module curriculum: + +| # | Title | Key Visual | +|---|-------|-----------| +| 1 | What Are Hooks & Why They Matter | Feature cards showing automation scenarios | +| 2 | The Hook Lifecycle | Data flow animation: User action → event → matcher → hook → result | +| 3 | See It In Action | Code translations of hook JSON configs | +| 4 | Matchers & Advanced Patterns | Scenario quiz on matcher patterns | +| 5 | Common Recipes | Pattern cards: auto-format, CI gates, security checks | +| 6 | Hooks in the Ecosystem | Protocol conversation: Claude ↔ Hook Handler ↔ Tool | + +### Phase 3: Build +1. Foundation: HTML shell, CSS design system, nav, scroll-snap +2. Module 1: Intro + feature cards +3. Module 2: Lifecycle animation + event type badges +4. Module 3: Hook JSON → English translations +5. Module 4: Matcher quiz + advanced config translations +6. Module 5: Recipe pattern cards + drag-and-drop matching +7. Module 6: Protocol conversation + architecture diagram +8. Polish pass + +### Phase 4: Review +- Open HTML in browser +- Walk user through: "Here's what we built — 6 modules covering hooks from concept to advanced patterns" +- Ask for feedback + +## Output Format +A single self-contained HTML file (~80-120KB) with: +- 6 scroll-snap modules with progress nav +- Protocol conversation showing hook execution flow +- Code ↔ English translations of hook JSON configs +- Data flow animation of the hook lifecycle +- Multiple-choice quizzes testing practical hook configuration +- Glossary tooltips on terms: matchers, IIFE, ARIA, stdin, SSE, MCP +- Obsidian & Amber design aesthetic (Instrument Serif + Outfit + JetBrains Mono) diff --git a/plugin/skills/claude-docs-course/references/design-system.md b/plugin/skills/claude-docs-course/references/design-system.md new file mode 100644 index 000000000..253ea74a1 --- /dev/null +++ b/plugin/skills/claude-docs-course/references/design-system.md @@ -0,0 +1,595 @@ +# Design System Reference — Obsidian & Amber + +Complete CSS design tokens for the course. Copy this entire `:root` block into the course HTML. The theme is a refined dark aesthetic — deep obsidian backgrounds with warm amber accents that create an atmosphere of focused discovery. Serif display headings give editorial elegance; clean sans-serif body text ensures readability. Grain textures and subtle glow effects add depth without distraction. + +## Table of Contents +1. [Color Palette](#color-palette) +2. [Typography](#typography) +3. [Spacing & Layout](#spacing--layout) +4. [Shadows & Depth](#shadows--depth) +5. [Animations & Transitions](#animations--transitions) +6. [Navigation & Progress](#navigation--progress) +7. [Module Structure](#module-structure) +8. [Responsive Breakpoints](#responsive-breakpoints) +9. [Scrollbar & Background](#scrollbar--background) +10. [Grain & Atmosphere](#grain--atmosphere) + +--- + +## Color Palette + +```css +:root { + /* --- BACKGROUNDS --- + Deep obsidian with a subtle warm-navy undertone. Never pure black. + The slight blue-purple tint gives depth and avoids a "dead screen" feel. */ + --color-bg: #0D0D16; /* primary — deep obsidian */ + --color-bg-warm: #12121E; /* alternating modules — slightly lifted */ + --color-bg-code: #08080F; /* code blocks — near-black, inky */ + --color-text: #E8E0D4; /* warm cream — primary text */ + --color-text-secondary: #9A9088; /* warm muted — body text */ + --color-text-muted: #5C5852; /* dark muted — labels, timestamps */ + --color-border: #2A2840; /* subtle dark border */ + --color-border-light: #1E1C32; /* even subtler border */ + --color-surface: #161624; /* card surfaces — elevated from bg */ + --color-surface-warm: #1C1A28; /* warm card surface — for translations */ + + /* --- ACCENT: Amber --- + Warm amber-gold evokes lamplight, discovery, illumination. + This is the signature color — used sparingly for maximum impact. */ + --color-accent: #F0A050; /* amber gold */ + --color-accent-hover: #E88A30; /* deeper amber on hover */ + --color-accent-light: rgba(240, 160, 80, 0.08); /* subtle amber wash */ + --color-accent-muted: #C09060; /* desaturated amber for less emphasis */ + --color-accent-glow: rgba(240, 160, 80, 0.25); /* glow effect around interactives */ + + /* --- SEMANTIC --- */ + --color-success: #50C8A0; /* bright mint-teal */ + --color-success-light: rgba(80, 200, 160, 0.08); + --color-error: #F06060; /* warm red */ + --color-error-light: rgba(240, 96, 96, 0.08); + --color-info: #60A0E0; /* soft blue */ + --color-info-light: rgba(96, 160, 224, 0.08); + + /* --- ACTOR COLORS (assign to protocol conversation actors) --- + Chosen for contrast against dark backgrounds and against each other. + Each actor should be instantly recognizable by color alone. */ + --color-actor-1: #F0A050; /* amber — Client App */ + --color-actor-2: #50C8A0; /* teal — API Gateway */ + --color-actor-3: #C080E0; /* soft violet — Claude Model */ + --color-actor-4: #E0C060; /* warm gold — Cache / Tool */ + --color-actor-5: #60B0E0; /* sky blue — User */ +} +``` + +**Rules:** +- Even-numbered modules use `--color-bg`, odd-numbered use `--color-bg-warm` (alternating creates depth rhythm) +- Actor colors must be distinct from each other and pass a contrast test against `--color-surface` +- Code blocks always use `--color-bg-code` — darker than everything else to visually recede +- The amber accent should be used for CTAs, active states, and highlights — never for large background areas +- Interactive elements get a subtle `box-shadow: 0 0 20px var(--color-accent-glow)` on hover/focus + +--- + +## Typography + +```css +:root { + /* --- FONTS --- + Display: Instrument Serif — sharp, elegant serifs with editorial character. + Creates immediate visual identity on dark backgrounds. The contrast between + serif headings and sans body text is the signature of this theme. + Body: Outfit — modern, clean, slightly rounded terminals. Excellent legibility + at all sizes on dark backgrounds. + Mono: JetBrains Mono — developer standard, clear character distinction. */ + --font-display: 'Instrument Serif', Georgia, 'Times New Roman', serif; + --font-body: 'Outfit', -apple-system, sans-serif; + --font-mono: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace; + + /* --- TYPE SCALE (1.25 ratio) --- */ + --text-xs: 0.75rem; /* 12px — labels, badges */ + --text-sm: 0.875rem; /* 14px — secondary text, code */ + --text-base: 1rem; /* 16px — body text */ + --text-lg: 1.125rem; /* 18px — lead paragraphs */ + --text-xl: 1.25rem; /* 20px — screen headings */ + --text-2xl: 1.5rem; /* 24px — sub-module titles */ + --text-3xl: 1.875rem; /* 30px — module subtitles */ + --text-4xl: 2.25rem; /* 36px — module titles */ + --text-5xl: 3rem; /* 48px — hero text */ + --text-6xl: 3.75rem; /* 60px — module numbers */ + + /* --- LINE HEIGHTS --- */ + --leading-tight: 1.15; /* headings */ + --leading-snug: 1.3; /* subheadings */ + --leading-normal: 1.6; /* body text */ + --leading-loose: 1.8; /* relaxed reading */ +} +``` + +**Google Fonts link (put in ``):** +```html + + + +``` + +**Rules:** +- Module numbers: `--text-6xl`, font-display, italic, `--color-accent` with 20% opacity +- Module titles: `--text-4xl` or `--text-5xl`, font-display, normal weight (serifs carry their own weight — no bold needed) +- Screen headings: `--text-xl` or `--text-2xl`, font-display +- Body text: `--text-base` or `--text-lg`, font-body, weight 400, `--leading-normal` +- Code: `--text-sm`, font-mono +- Labels/badges: `--text-xs`, font-body, weight 600, uppercase, letter-spacing 0.08em +- The serif display font should NEVER be used below `--text-xl` — below that, use font-body + +--- + +## Spacing & Layout + +```css +:root { + --space-1: 0.25rem; /* 4px */ + --space-2: 0.5rem; /* 8px */ + --space-3: 0.75rem; /* 12px */ + --space-4: 1rem; /* 16px */ + --space-5: 1.25rem; /* 20px */ + --space-6: 1.5rem; /* 24px */ + --space-8: 2rem; /* 32px */ + --space-10: 2.5rem; /* 40px */ + --space-12: 3rem; /* 48px */ + --space-16: 4rem; /* 64px */ + --space-20: 5rem; /* 80px */ + --space-24: 6rem; /* 96px */ + + --content-width: 800px; /* standard reading width */ + --content-width-wide: 1000px; /* for side-by-side layouts */ + --nav-height: 52px; + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; + --radius-xl: 20px; + --radius-full: 9999px; +} +``` + +**Module layout:** +```css +.module { + min-height: 100dvh; /* fallback: 100vh */ + scroll-snap-align: start; + padding: var(--space-16) var(--space-6); + padding-top: calc(var(--nav-height) + var(--space-12)); + position: relative; /* for grain overlay pseudo-element */ +} +.module-content { + max-width: var(--content-width); + margin: 0 auto; +} +``` + +--- + +## Shadows & Depth + +```css +:root { + /* On dark backgrounds, shadows use near-black with slight blue tint + to maintain the obsidian atmosphere. Glow effects use the accent color. */ + --shadow-sm: 0 1px 3px rgba(0, 0, 8, 0.3); + --shadow-md: 0 4px 16px rgba(0, 0, 8, 0.4); + --shadow-lg: 0 8px 32px rgba(0, 0, 8, 0.5); + --shadow-xl: 0 16px 48px rgba(0, 0, 8, 0.6); + --shadow-glow: 0 0 24px var(--color-accent-glow); /* amber glow for interactives */ + --shadow-inner: inset 0 1px 0 rgba(255, 255, 255, 0.04); /* subtle top-edge highlight */ +} +``` + +**Card depth pattern:** +```css +.card { + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-md), var(--shadow-inner); + transition: box-shadow var(--duration-normal) var(--ease-out), + border-color var(--duration-normal) var(--ease-out); +} +.card:hover { + border-color: var(--color-accent-muted); + box-shadow: var(--shadow-lg), var(--shadow-glow); +} +``` + +Never use pure black `rgba(0,0,0,...)` for shadows — always use the blue-tinted `rgba(0,0,8,...)` to maintain the obsidian atmosphere. + +--- + +## Animations & Transitions + +```css +:root { + --ease-out: cubic-bezier(0.16, 1, 0.3, 1); + --ease-in-out: cubic-bezier(0.65, 0, 0.35, 1); + --ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1); /* subtle overshoot */ + --duration-fast: 150ms; + --duration-normal: 300ms; + --duration-slow: 500ms; + --duration-reveal: 700ms; + --stagger-delay: 100ms; +} +``` + +**Scroll-triggered reveal pattern:** +```css +.animate-in { + opacity: 0; + transform: translateY(24px); + transition: opacity var(--duration-reveal) var(--ease-out), + transform var(--duration-reveal) var(--ease-out); +} +.animate-in.visible { + opacity: 1; + transform: translateY(0); +} + +/* Stagger children */ +.stagger-children > .animate-in { + transition-delay: calc(var(--stagger-index, 0) * var(--stagger-delay)); +} +``` + +**Amber glow pulse (for interactive elements awaiting interaction):** +```css +@keyframes glowPulse { + 0%, 100% { box-shadow: 0 0 16px rgba(240, 160, 80, 0.1); } + 50% { box-shadow: 0 0 28px rgba(240, 160, 80, 0.2); } +} +.interactive-hint { + animation: glowPulse 3s var(--ease-in-out) infinite; +} +``` + +**JS setup for stagger:** +```javascript +document.querySelectorAll('.stagger-children').forEach(parent => { + Array.from(parent.children).forEach((child, i) => { + child.style.setProperty('--stagger-index', i); + }); +}); +``` + +**Intersection Observer (trigger reveals):** +```javascript +const observer = new IntersectionObserver((entries) => { + entries.forEach(entry => { + if (entry.isIntersecting) { + entry.target.classList.add('visible'); + observer.unobserve(entry.target); // animate only once + } + }); +}, { rootMargin: '0px 0px -10% 0px', threshold: 0.1 }); + +document.querySelectorAll('.animate-in').forEach(el => observer.observe(el)); +``` + +--- + +## Navigation & Progress + +**HTML structure:** +```html + +``` + +**Nav styling:** +```css +.nav { + position: fixed; + top: 0; left: 0; right: 0; + z-index: 100; + background: rgba(13, 13, 22, 0.85); + backdrop-filter: blur(16px) saturate(1.2); + -webkit-backdrop-filter: blur(16px) saturate(1.2); + border-bottom: 1px solid var(--color-border-light); + height: var(--nav-height); +} +.nav-inner { + max-width: var(--content-width-wide); + margin: 0 auto; + padding: 0 var(--space-6); + height: 100%; + display: flex; + align-items: center; + justify-content: space-between; +} +.nav-title { + font-family: var(--font-display); + font-size: var(--text-base); + color: var(--color-text); + letter-spacing: -0.01em; +} +.progress-bar { + position: absolute; + bottom: 0; left: 0; + height: 2px; + background: linear-gradient(90deg, var(--color-accent), var(--color-accent-hover)); + transition: width 100ms linear; + box-shadow: 0 0 8px var(--color-accent-glow); +} +``` + +**Nav dot states:** +```css +.nav-dot { + width: 10px; height: 10px; + border-radius: 50%; + border: 1.5px solid var(--color-text-muted); + background: transparent; + cursor: pointer; + transition: all var(--duration-normal) var(--ease-out); + padding: 0; +} +.nav-dot.active { + border-color: var(--color-accent); + background: var(--color-accent); + box-shadow: 0 0 10px var(--color-accent-glow); + transform: scale(1.15); +} +.nav-dot.visited { + border-color: var(--color-accent-muted); + background: var(--color-accent-muted); +} +``` + +**Progress bar (JS):** +```javascript +function updateProgressBar() { + const scrollTop = window.scrollY; + const scrollHeight = document.documentElement.scrollHeight - window.innerHeight; + const progress = (scrollTop / scrollHeight) * 100; + progressBar.style.width = progress + '%'; +} +window.addEventListener('scroll', () => { + requestAnimationFrame(updateProgressBar); +}, { passive: true }); +``` + +**Keyboard navigation:** +```javascript +document.addEventListener('keydown', (e) => { + if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) return; + if (e.key === 'ArrowDown' || e.key === 'ArrowRight') { nextModule(); e.preventDefault(); } + if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') { prevModule(); e.preventDefault(); } +}); +``` + +--- + +## Module Structure + +**HTML template for each module:** +```html +
+
+
+ 0N +

Module Title

+

One-line description of what this module teaches

+
+ +
+
+

Screen Title

+

Content...

+ +
+ +
+ +
+
+
+
+``` + +**Module number styling:** +```css +.module-number { + font-family: var(--font-display); + font-style: italic; + font-size: var(--text-6xl); + color: var(--color-accent); + opacity: 0.15; + line-height: 1; + display: block; + margin-bottom: var(--space-2); +} +.module-title { + font-family: var(--font-display); + font-size: var(--text-5xl); + color: var(--color-text); + line-height: var(--leading-tight); + margin-bottom: var(--space-3); + letter-spacing: -0.02em; +} +.module-subtitle { + font-family: var(--font-body); + font-size: var(--text-lg); + color: var(--color-text-secondary); + line-height: var(--leading-snug); + max-width: 540px; +} +.screen-heading { + font-family: var(--font-display); + font-size: var(--text-2xl); + color: var(--color-text); + margin-bottom: var(--space-4); +} +``` + +**Alternating module backgrounds:** +```css +.module:nth-child(odd) { background: var(--color-bg); } +.module:nth-child(even) { background: var(--color-bg-warm); } +``` + +--- + +## Responsive Breakpoints + +```css +/* Tablet */ +@media (max-width: 768px) { + :root { + --text-4xl: 1.875rem; + --text-5xl: 2.25rem; + --text-6xl: 3rem; + } + .translation-block { grid-template-columns: 1fr; } /* stack code/english */ + .pattern-cards { grid-template-columns: 1fr 1fr; } +} + +/* Mobile */ +@media (max-width: 480px) { + :root { + --text-4xl: 1.5rem; + --text-5xl: 1.875rem; + --text-6xl: 2.25rem; + } + .module { padding: var(--space-8) var(--space-4); } + .pattern-cards { grid-template-columns: 1fr; } + .flow-steps { flex-direction: column; } + .flow-arrow { transform: rotate(90deg); } +} +``` + +--- + +## Scrollbar & Background + +```css +/* Custom scrollbar — thin, ambient */ +::-webkit-scrollbar { width: 5px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { + background: var(--color-border); + border-radius: var(--radius-full); +} +::-webkit-scrollbar-thumb:hover { + background: var(--color-accent-muted); +} + +/* Atmospheric background — subtle amber radial at top, fading out */ +body { + background: var(--color-bg); + background-image: + radial-gradient(ellipse at 30% 0%, rgba(240, 160, 80, 0.04) 0%, transparent 50%), + radial-gradient(ellipse at 80% 100%, rgba(192, 128, 224, 0.02) 0%, transparent 40%); +} + +/* Page scroll setup */ +html { + scroll-snap-type: y proximity; + scroll-behavior: smooth; +} +``` + +--- + +## Grain & Atmosphere + +The grain overlay is the signature texture of this theme. It adds analog warmth to the digital dark surface — like looking through a vintage lens or at a printed page under lamplight. + +**CSS grain overlay (apply to body or individual modules):** +```css +body::after { + content: ''; + position: fixed; + top: 0; left: 0; + width: 100%; height: 100%; + pointer-events: none; + z-index: 9999; + opacity: 0.035; + background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E"); + background-repeat: repeat; + background-size: 256px 256px; +} +``` + +**Module separator — geometric line accent:** +```css +.module + .module::before { + content: ''; + display: block; + position: absolute; + top: 0; + left: 50%; + transform: translateX(-50%); + width: 60px; + height: 1px; + background: linear-gradient(90deg, transparent, var(--color-accent-muted), transparent); +} +``` + +**Glass-morphism pattern for elevated surfaces:** +```css +.glass { + background: rgba(22, 22, 36, 0.6); + backdrop-filter: blur(12px) saturate(1.1); + -webkit-backdrop-filter: blur(12px) saturate(1.1); + border: 1px solid rgba(255, 255, 255, 0.04); + box-shadow: var(--shadow-md), var(--shadow-inner); +} +``` + +--- + +## Code Block Globals + +All code blocks in the course — whether inside translation blocks, standalone snippets, or quiz challenges — must wrap text and never show a horizontal scrollbar. This is a teaching tool, not an IDE. + +```css +pre, code { + white-space: pre-wrap; /* wrap long lines */ + word-break: break-word; /* break mid-word if absolutely needed */ + overflow-x: hidden; /* no horizontal scrollbar — ever */ +} +/* Hide scrollbars on code containers */ +.translation-code::-webkit-scrollbar, +pre::-webkit-scrollbar { + display: none; +} +``` + +Code snippets must be **exact copies** from the official documentation — never modified, trimmed, or simplified. Choose naturally short (5-15 line) examples that illustrate the concept well. + +--- + +## Syntax Highlighting (Amber Night) + +Custom syntax theme designed for the `--color-bg-code` (#08080F) background. Warm tones dominate, with cool accents for contrast. Every color must be instantly readable against the near-black code background. + +```css +.code-keyword { color: #F0A050; } /* amber — keywords carry the theme color */ +.code-string { color: #A6E3A1; } /* soft green — strings stay calm */ +.code-function { color: #60B0E0; } /* sky blue — function names pop */ +.code-comment { color: #4A4A58; } /* muted slate — comments recede */ +.code-number { color: #F0C080; } /* warm peach — numbers glow gently */ +.code-property { color: #E8E0D4; } /* cream — object keys match body text */ +.code-operator { color: #50C8A0; } /* teal — operators are structural */ +.code-tag { color: #E08080; } /* muted rose — HTML tags */ +.code-attr { color: #C080E0; } /* soft violet — HTML attributes */ +.code-value { color: #A6E3A1; } /* soft green — attribute values */ +``` + +The amber keyword color (`#F0A050`) ties code to the overall theme accent, creating visual cohesion between the UI and the code examples. diff --git a/plugin/skills/claude-docs-course/references/interactive-elements.md b/plugin/skills/claude-docs-course/references/interactive-elements.md new file mode 100644 index 000000000..0af6be920 --- /dev/null +++ b/plugin/skills/claude-docs-course/references/interactive-elements.md @@ -0,0 +1,1214 @@ +# Interactive Elements Reference + +Implementation patterns for every interactive element type used in courses. Pick the elements that best serve each module's teaching goal. + +## Table of Contents +1. [Code ↔ English Translation Blocks](#code--english-translation-blocks) +2. [Multiple-Choice Quizzes](#multiple-choice-quizzes) +3. [Drag-and-Drop Matching](#drag-and-drop-matching) +4. [Group Chat Animation](#group-chat-animation) +5. [Message Flow / Data Flow Animation](#message-flow--data-flow-animation) +6. [Interactive Architecture Diagram](#interactive-architecture-diagram) +7. [Layer Toggle Demo](#layer-toggle-demo) +8. ["Spot the Bug" Challenge](#spot-the-bug-challenge) +9. [Scenario Quiz](#scenario-quiz) +10. [Callout Boxes](#callout-boxes) +11. [Pattern/Feature Cards](#patternfeature-cards) +12. [Flow Diagrams](#flow-diagrams) +13. [Permission/Config Badges](#permissionconfig-badges) +14. [Glossary Tooltips](#glossary-tooltips) +15. [Visual File Tree](#visual-file-tree) +16. [Icon-Label Rows](#icon-label-rows) +17. [Numbered Step Cards](#numbered-step-cards) +18. [Protocol Conversation](#protocol-conversation) + +--- + +## Code ↔ English Translation Blocks + +The most important teaching element. Shows real code from the project on the left and a plain English translation on the right, line by line. + +**HTML:** +```html +
+
+ CODE +

+const response = await fetch(url, {
+  method: 'POST',
+  headers: { 'Authorization': apiKey }
+});
+    
+
+
+ PLAIN ENGLISH +
+

Send a request to the URL and wait for a response...

+

We're sending data (POST), not just asking for it (GET)...

+

Include our API key so the server knows who we are...

+

End of the request setup.

+
+
+
+``` + +**CSS:** +```css +.translation-block { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0; + border-radius: var(--radius-md); + overflow: hidden; + box-shadow: var(--shadow-md); + margin: var(--space-8) 0; +} +.translation-code { + background: var(--color-bg-code); + color: #CDD6F4; + padding: var(--space-6); + font-family: var(--font-mono); + font-size: var(--text-sm); + line-height: 1.7; + position: relative; + overflow-x: hidden; /* NO horizontal scrollbar — ever */ +} +.translation-code pre, +.translation-code code { + white-space: pre-wrap; /* wrap long lines instead of scrolling */ + word-break: break-word; /* break mid-word if needed */ + overflow-x: hidden; +} +.translation-english { + background: var(--color-surface-warm); + padding: var(--space-6); + font-size: var(--text-sm); + line-height: 1.7; + border-left: 3px solid var(--color-accent); +} +.translation-label { + position: absolute; + top: var(--space-2); + right: var(--space-3); + font-size: var(--text-xs); + text-transform: uppercase; + letter-spacing: 0.1em; + opacity: 0.5; +} +.translation-english .translation-label { + color: var(--color-text-muted); +} +/* Responsive: stack vertically on mobile */ +@media (max-width: 768px) { + .translation-block { grid-template-columns: 1fr; } + .translation-english { border-left: none; border-top: 3px solid var(--color-accent); } +} +``` + +**Rules:** +- Each English line should correspond to 1-2 code lines +- Use conversational language, not technical jargon +- Highlight the "why" not just the "what" — e.g., "Include our API key so the server knows who we are" not "Set the Authorization header" + +--- + +## Multiple-Choice Quizzes + +For testing understanding with instant feedback. Each question has options, one correct answer, and per-question explanations. + +**HTML:** +```html +
+
+

Question text here?

+
+ + + +
+
+
+ + + + +
+``` + +**JS pattern:** +```javascript +window.selectOption = function(btn) { + // Deselect siblings + const block = btn.closest('.quiz-question-block'); + block.querySelectorAll('.quiz-option').forEach(o => o.classList.remove('selected')); + btn.classList.add('selected'); +}; + +window.checkQuiz = function(sectionId) { + const container = document.querySelector(`#${sectionId} .quiz-container`); + const questions = container.querySelectorAll('.quiz-question-block'); + let correct = 0; + + questions.forEach(q => { + const selected = q.querySelector('.quiz-option.selected'); + const feedback = q.querySelector('.quiz-feedback'); + const correctValue = q.dataset.correct; + + if (!selected) { + feedback.textContent = 'Pick an answer first!'; + feedback.className = 'quiz-feedback show warning'; + return; + } + + if (selected.dataset.value === correctValue) { + correct++; + selected.classList.add('correct'); + feedback.innerHTML = 'Exactly! ' + getExplanation(q, true); + feedback.className = 'quiz-feedback show success'; + } else { + selected.classList.add('incorrect'); + // Highlight the correct one + q.querySelector(`[data-value="${correctValue}"]`).classList.add('correct'); + feedback.innerHTML = 'Not quite. ' + getExplanation(q, false); + feedback.className = 'quiz-feedback show error'; + } + + // Disable further interaction + q.querySelectorAll('.quiz-option').forEach(o => o.disabled = true); + }); +}; +``` + +**CSS for quiz states:** +```css +.quiz-option { + display: flex; align-items: center; gap: var(--space-3); + padding: var(--space-3) var(--space-4); + border: 2px solid var(--color-border); + border-radius: var(--radius-sm); + background: var(--color-surface); + cursor: pointer; width: 100%; + transition: border-color var(--duration-fast), background var(--duration-fast); +} +.quiz-option:hover { border-color: var(--color-accent-muted); } +.quiz-option.selected { border-color: var(--color-accent); background: var(--color-accent-light); } +.quiz-option.correct { border-color: var(--color-success); background: var(--color-success-light); } +.quiz-option.incorrect { border-color: var(--color-error); background: var(--color-error-light); } +.quiz-option-radio { + width: 18px; height: 18px; border-radius: 50%; + border: 2px solid var(--color-border); + transition: all var(--duration-fast); +} +.quiz-option.selected .quiz-option-radio { + border-color: var(--color-accent); + background: var(--color-accent); + box-shadow: inset 0 0 0 3px white; +} +.quiz-feedback { + max-height: 0; overflow: hidden; opacity: 0; + transition: max-height var(--duration-normal), opacity var(--duration-normal); +} +.quiz-feedback.show { max-height: 200px; opacity: 1; padding: var(--space-3); margin-top: var(--space-2); border-radius: var(--radius-sm); } +.quiz-feedback.success { background: var(--color-success-light); color: var(--color-success); } +.quiz-feedback.error { background: var(--color-error-light); color: var(--color-error); } +``` + +--- + +## Drag-and-Drop Matching + +For matching concepts to descriptions. Supports both mouse (HTML5 Drag API) and touch. + +**HTML:** +```html +
+
+
Actor A
+
Actor B
+
Actor C
+
+
+
+

Description for Actor A

+
Drop here
+
+ +
+ + +
+``` + +**JS (mouse + touch):** +```javascript +// MOUSE: HTML5 Drag API +chips.forEach(chip => { + chip.addEventListener('dragstart', (e) => { + e.dataTransfer.setData('text/plain', chip.dataset.answer); + chip.classList.add('dragging'); + }); + chip.addEventListener('dragend', () => chip.classList.remove('dragging')); +}); + +zones.forEach(zone => { + const target = zone.querySelector('.dnd-zone-target'); + target.addEventListener('dragover', (e) => { e.preventDefault(); target.classList.add('drag-over'); }); + target.addEventListener('dragleave', () => target.classList.remove('drag-over')); + target.addEventListener('drop', (e) => { + e.preventDefault(); + target.classList.remove('drag-over'); + const answer = e.dataTransfer.getData('text/plain'); + const chip = document.querySelector(`[data-answer="${answer}"]`); + target.textContent = chip.textContent; + target.dataset.placed = answer; + chip.classList.add('placed'); + }); +}); + +// TOUCH: Custom implementation (HTML5 drag doesn't work on mobile) +chips.forEach(chip => { + chip.addEventListener('touchstart', (e) => { + e.preventDefault(); + const touch = e.touches[0]; + const clone = chip.cloneNode(true); + clone.classList.add('touch-ghost'); + clone.style.cssText = `position:fixed; z-index:1000; pointer-events:none; + left:${touch.clientX - 40}px; top:${touch.clientY - 20}px;`; + document.body.appendChild(clone); + chip._ghost = clone; + chip._answer = chip.dataset.answer; + }, { passive: false }); + + chip.addEventListener('touchmove', (e) => { + e.preventDefault(); + const touch = e.touches[0]; + if (chip._ghost) { + chip._ghost.style.left = (touch.clientX - 40) + 'px'; + chip._ghost.style.top = (touch.clientY - 20) + 'px'; + } + // Highlight zone under finger + const el = document.elementFromPoint(touch.clientX, touch.clientY); + zones.forEach(z => z.querySelector('.dnd-zone-target').classList.remove('drag-over')); + if (el && el.closest('.dnd-zone-target')) { + el.closest('.dnd-zone-target').classList.add('drag-over'); + } + }, { passive: false }); + + chip.addEventListener('touchend', (e) => { + if (chip._ghost) { chip._ghost.remove(); chip._ghost = null; } + const touch = e.changedTouches[0]; + const el = document.elementFromPoint(touch.clientX, touch.clientY); + if (el && el.closest('.dnd-zone-target')) { + const target = el.closest('.dnd-zone-target'); + target.textContent = chip.textContent; + target.dataset.placed = chip._answer; + chip.classList.add('placed'); + } + }); +}); +``` + +--- + +## Group Chat Animation + +iMessage/WeChat-style chat showing components "talking" to each other. Messages appear one by one with typing indicators. + +**HTML:** +```html +
+
+ + +
+ + + +
+ + + + 0 / N messages +
+
+``` + +**JS:** +```javascript +let chatIndex = 0; +const chatMessages = document.querySelectorAll('#chat-messages .chat-message'); + +// Actor color/avatar mapping +const actors = { + 'actor-a': { initials: 'A', color: 'var(--color-actor-1)' }, + 'actor-b': { initials: 'B', color: 'var(--color-actor-2)' }, + 'actor-c': { initials: 'C', color: 'var(--color-actor-3)' }, +}; + +window.playChatNext = function() { + if (chatIndex >= chatMessages.length) return; + const msg = chatMessages[chatIndex]; + const sender = msg.dataset.sender; + + // Show typing indicator with correct avatar + const typing = document.getElementById('chat-typing'); + const avatar = document.getElementById('typing-avatar'); + avatar.textContent = actors[sender].initials; + avatar.style.background = actors[sender].color; + typing.style.display = 'flex'; + + setTimeout(() => { + typing.style.display = 'none'; + msg.style.display = 'flex'; + msg.style.animation = 'fadeSlideUp 0.3s var(--ease-out)'; + chatIndex++; + updateChatProgress(); + }, 800); +}; + +window.playChatAll = function() { + const interval = setInterval(() => { + if (chatIndex >= chatMessages.length) { clearInterval(interval); return; } + playChatNext(); + }, 1200); +}; +``` + +**CSS for typing dots:** +```css +.typing-dot { + width: 8px; height: 8px; border-radius: 50%; + background: var(--color-text-muted); + animation: typingBounce 1.4s infinite; +} +.typing-dot:nth-child(2) { animation-delay: 0.2s; } +.typing-dot:nth-child(3) { animation-delay: 0.4s; } +@keyframes typingBounce { + 0%, 60%, 100% { transform: translateY(0); } + 30% { transform: translateY(-6px); } +} +``` + +--- + +## Message Flow / Data Flow Animation + +Step-by-step visualization of data moving between components. User clicks "Next Step" to advance. + +**HTML:** +```html +
+
+
+
A
+ Actor 1 +
+
+
B
+ Actor 2 +
+
+
C
+ Actor 3 +
+
+ +
+ +
Click "Next Step" to begin
+ +
+ + + Step 0 / N +
+
+``` + +**JS pattern:** +```javascript +const flowSteps = [ + { from: 'actor-1', to: 'actor-2', label: 'User clicks button → Actor 1 detects click event', highlight: 'actor-1' }, + { from: 'actor-1', to: 'actor-2', label: 'Actor 1 sends message to Actor 2', highlight: 'actor-2', packet: true }, + { from: 'actor-2', to: 'external', label: 'Actor 2 calls external API', highlight: 'actor-2', cloud: true }, + // etc. +]; + +let flowStep = 0; +window.flowNext = function() { + if (flowStep >= flowSteps.length) return; + const step = flowSteps[flowStep]; + + // Remove previous highlights + document.querySelectorAll('.flow-actor').forEach(a => a.classList.remove('active')); + + // Highlight current actor + document.getElementById(`flow-${step.highlight}`).classList.add('active'); + + // Animate packet if needed + if (step.packet) { + animatePacket(step.from, step.to); + } + + // Update label + document.getElementById('flow-label').textContent = step.label; + flowStep++; +}; +``` + +**CSS for active actor glow:** +```css +.flow-actor.active { + box-shadow: 0 0 0 3px var(--color-accent), 0 0 20px var(--color-accent-glow); + transform: scale(1.05); + transition: all var(--duration-normal) var(--ease-out); +} +``` + +--- + +## Interactive Architecture Diagram + +Full-system diagram where hovering/clicking a component shows a description tooltip. + +**HTML:** +```html +
+
+

Browser

+
+
📄
+ Component A +
+ +
+
+

External Services

+ +
+
Click any component to learn what it does
+
+``` + +--- + +## Layer Toggle Demo + +Shows how different layers (e.g., HTML/CSS/JS, or data/logic/UI) build on each other. Three tabs switch between views. + +**HTML:** +```html +
+
+ + + +
+
+
+ +
+ + +
+

This is the raw HTML...

+
+``` + +--- + +## "Spot the Bug" Challenge + +Show code with a deliberate bug. User clicks the buggy line. Reveal explains the issue. + +**HTML:** +```html +
+

Find the bug in this code:

+
+
+ 1 + chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { +
+
+ 2 + if (msg.action === 'fetchData') { +
+
+ 3 + fetch(url).then(r => r.json()).then(data => sendResponse(data)); +
+
+ 4 + } +
+
+ 5 + }); +
+
+
+
+``` + +**JS:** +```javascript +window.checkBugLine = function(el, isCorrect) { + const feedback = el.closest('.bug-challenge').querySelector('.bug-feedback'); + if (isCorrect) { + el.classList.add('correct'); + feedback.innerHTML = 'Found it! The listener uses an async operation (fetch) but doesn\'t return true. Chrome closes the message channel before the response can be sent. Fix: add return true; at the end.'; + feedback.className = 'bug-feedback show success'; + } else { + el.classList.add('incorrect'); + feedback.innerHTML = 'Not this line — look for where the async timing might cause problems...'; + feedback.className = 'bug-feedback show error'; + setTimeout(() => { el.classList.remove('incorrect'); feedback.className = 'bug-feedback'; }, 2000); + } +}; +``` + +--- + +## Scenario Quiz + +"What would a senior engineer do?" — situational questions with explanations. + +Same HTML/CSS/JS pattern as Multiple-Choice Quizzes, but with longer scenario descriptions and more detailed explanations. Wrap each question in a scenario context block: + +```html +
+
+ Scenario +

Your app processes a 3-hour podcast transcript. The API has a 16,000 token limit. What do you do?

+
+ +
+``` + +--- + +## Callout Boxes + +"Aha!" moments — universal CS insights. Max 2 per module. + +```html +
+
💡
+
+ Key Insight +

This pattern — splitting responsibilities into focused roles — is one of the most important ideas in software engineering. Engineers call it "separation of concerns."

+
+
+``` + +**Variants:** +- `callout-accent`: amber left border, light accent background (for CS insights) +- `callout-info`: teal left border, light info background (for "good to know") +- `callout-warning`: red left border, light error background (for common mistakes) + +--- + +## Pattern/Feature Cards + +Grid of cards highlighting engineering patterns, tech stack components, or key concepts. + +```html +
+
+
🔄
+

Caching

+

Store results to avoid redundant work — like keeping leftovers instead of cooking a new meal every time.

+
+ +
+``` + +```css +.pattern-cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: var(--space-4); +} +.pattern-card { + background: var(--color-surface); + border-radius: var(--radius-md); + padding: var(--space-6); + box-shadow: var(--shadow-sm); + transition: transform var(--duration-normal) var(--ease-out), box-shadow var(--duration-normal); +} +.pattern-card:hover { + transform: translateY(-4px); + box-shadow: var(--shadow-md); +} +``` + +--- + +## Flow Diagrams + +**Horizontal flow (desktop):** +```html +
+
+
1
+

User clicks button

+
+
+
+
2
+

Component A detects click

+
+
+ +
+``` + +Arrows rotate to `↓` on mobile via CSS transform. + +--- + +## Permission/Config Badges + +For annotating config files, permissions, or settings: + +```html +
+
+ storage + Save data between sessions (like browser bookmarks) +
+
+ activeTab + Access the currently open tab (only when the user clicks) +
+
+``` + +```css +.badge-item { + display: flex; align-items: center; gap: var(--space-4); + padding: var(--space-3) var(--space-4); + border: 1px solid var(--color-border-light); + border-radius: var(--radius-sm); + transition: border-color var(--duration-fast); +} +.badge-item:hover { border-color: var(--color-accent-muted); } +.badge-code { + font-family: var(--font-mono); + font-size: var(--text-sm); + background: var(--color-bg-code); + color: #CBA6F7; + padding: var(--space-1) var(--space-3); + border-radius: var(--radius-sm); + white-space: nowrap; +} +``` + +--- + +## Glossary Tooltips + +The most important accessibility feature for non-technical learners. Any technical term in the course text should be wrapped in a tooltip that shows a plain-English definition on hover (desktop) or tap (mobile). The learner never has to leave the page or Google anything. + +**HTML — mark up terms inline:** +```html +

The extension uses a + service worker + to handle API calls. +

+``` + +**CSS:** +```css +.term { + border-bottom: 1.5px dashed var(--color-accent-muted); + cursor: pointer; /* NOT cursor: help — pointer feels clickable and inviting */ + position: relative; +} +.term:hover, .term.active { + border-bottom-color: var(--color-accent); + color: var(--color-accent); +} + +/* The tooltip bubble — uses position: fixed and is appended to document.body + via JS so it is NEVER clipped by ancestor overflow: hidden containers + (like translation blocks). See JS section below for positioning logic. */ +.term-tooltip { + position: fixed; /* CRITICAL: fixed, not absolute — prevents clipping */ + background: var(--color-bg-code); + color: #CDD6F4; + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-sm); + font-size: var(--text-sm); + font-family: var(--font-body); + line-height: var(--leading-normal); + width: max(200px, min(320px, 80vw)); + box-shadow: var(--shadow-lg); + pointer-events: none; + opacity: 0; + transition: opacity var(--duration-fast); + z-index: 10000; /* Above everything, including nav */ +} +/* Arrow pointing down */ +.term-tooltip::after { + content: ''; + position: absolute; + top: 100%; + left: 50%; + transform: translateX(-50%); + border: 6px solid transparent; + border-top-color: var(--color-bg-code); +} +.term-tooltip.visible { + opacity: 1; +} + +/* If tooltip goes off-screen top, flip to below */ +.term-tooltip.flip { + bottom: auto; + top: calc(100% + 8px); +} +.term-tooltip.flip::after { + top: auto; + bottom: 100%; + border-top-color: transparent; + border-bottom-color: var(--color-bg-code); +} +``` + +**JS — position: fixed tooltips appended to body (never clipped by overflow):** +```javascript +// Tooltip container — appended to body so it's never clipped +let activeTooltip = null; + +function positionTooltip(term, tip) { + const rect = term.getBoundingClientRect(); + const tipWidth = 300; // approximate + let left = rect.left + rect.width / 2 - tipWidth / 2; + // Clamp to viewport + left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8)); + + // Try above first + let top = rect.top - 8; + tip.style.left = left + 'px'; + + // Position above by default, flip below if no room + document.body.appendChild(tip); + const tipHeight = tip.offsetHeight; + if (rect.top - tipHeight - 8 < 0) { + // Flip below + tip.style.top = (rect.bottom + 8) + 'px'; + tip.classList.add('flip'); + } else { + tip.style.top = (rect.top - tipHeight - 8) + 'px'; + tip.classList.remove('flip'); + } +} + +document.querySelectorAll('.term').forEach(term => { + const tip = document.createElement('span'); + tip.className = 'term-tooltip'; + tip.textContent = term.dataset.definition; + + // Hover for desktop + term.addEventListener('mouseenter', () => { + if (activeTooltip && activeTooltip !== tip) { + activeTooltip.classList.remove('visible'); + activeTooltip.remove(); + } + positionTooltip(term, tip); + requestAnimationFrame(() => tip.classList.add('visible')); + activeTooltip = tip; + }); + + term.addEventListener('mouseleave', () => { + tip.classList.remove('visible'); + setTimeout(() => { if (!tip.classList.contains('visible')) tip.remove(); }, 150); + activeTooltip = null; + }); + + // Tap for mobile + term.addEventListener('click', (e) => { + e.stopPropagation(); + if (activeTooltip && activeTooltip !== tip) { + activeTooltip.classList.remove('visible'); + activeTooltip.remove(); + } + if (tip.classList.contains('visible')) { + tip.classList.remove('visible'); + tip.remove(); + activeTooltip = null; + } else { + positionTooltip(term, tip); + requestAnimationFrame(() => tip.classList.add('visible')); + activeTooltip = tip; + } + }); +}); + +// Close tooltips when clicking elsewhere +document.addEventListener('click', () => { + if (activeTooltip) { + activeTooltip.classList.remove('visible'); + activeTooltip.remove(); + activeTooltip = null; + } +}); +``` + +**Rules:** +- Mark up EVERY technical term on first use in each module (API, DOM, callback, async, endpoint, middleware, etc.) +- Keep definitions to 1-2 sentences max, in everyday language +- Use a metaphor in the definition when it helps — e.g., "A **callback** is like leaving your phone number at a restaurant so they can call you when your table is ready" +- Don't mark the same term twice within the same screen — only on first appearance per module +- The dashed underline should be subtle enough not to distract but visible enough that curious learners discover it + +--- + +## Visual File Tree + +Use instead of paragraphs listing "this folder does X, that folder does Y." Much easier to scan. + +```html +
+
+ app/ + Pages and API routes +
+
+ api/ + Backend endpoints the frontend calls +
+
+ layout.tsx + The shell that wraps every page +
+
+
+
+ components/ + Reusable UI building blocks +
+
+ lib/ + Shared logic and utilities +
+
+``` + +```css +.file-tree { font-family: var(--font-mono); font-size: var(--text-sm); } +.ft-folder, .ft-file { + padding: var(--space-2) var(--space-3); + border-left: 2px solid var(--color-border-light); + margin-left: var(--space-4); +} +.ft-folder > .ft-name { color: var(--color-accent); font-weight: 600; } +.ft-folder > .ft-name::before { content: '📁 '; } +.ft-file > .ft-name::before { content: '📄 '; } +.ft-desc { + color: var(--color-text-secondary); + font-family: var(--font-body); + margin-left: var(--space-2); + font-size: var(--text-xs); +} +.ft-children { margin-left: var(--space-4); } +``` + +--- + +## Icon-Label Rows + +For listing components, features, or concepts visually. Replaces bullet-point paragraphs. + +```html +
+
+
🖥️
+
+ Frontend (Next.js) +

What the user sees and interacts with

+
+
+
+
+
+ API Routes +

Backend logic that runs on the server

+
+
+
+
🗄️
+
+ Database (Supabase) +

Where all the data is stored permanently

+
+
+
+``` + +```css +.icon-rows { display: flex; flex-direction: column; gap: var(--space-4); } +.icon-row { + display: flex; align-items: center; gap: var(--space-4); + padding: var(--space-4); + background: var(--color-surface); + border-radius: var(--radius-md); + box-shadow: var(--shadow-sm); +} +.icon-row p { margin: 0; color: var(--color-text-secondary); font-size: var(--text-sm); } +.icon-circle { + width: 48px; height: 48px; border-radius: 50%; + display: flex; align-items: center; justify-content: center; + font-size: 1.25rem; flex-shrink: 0; +} +``` + +--- + +## Numbered Step Cards + +For sequences that would otherwise be a numbered paragraph list. Visual, scannable, and each step stands alone. + +```html +
+
+
1
+
+ User pastes a YouTube URL +

The frontend captures the URL and extracts the video ID

+
+
+
+
2
+
+ API fetches the transcript +

A server-side route calls an external service to get the video's text

+
+
+
+
3
+
+ AI analyzes the content +

The transcript is sent to an AI model that extracts key moments

+
+
+
+``` + +```css +.step-cards { display: flex; flex-direction: column; gap: var(--space-3); } +.step-card { + display: flex; align-items: flex-start; gap: var(--space-4); + padding: var(--space-4) var(--space-5); + background: var(--color-surface); + border-radius: var(--radius-md); + border-left: 3px solid var(--color-accent); + box-shadow: var(--shadow-sm); +} +.step-num { + width: 32px; height: 32px; border-radius: 50%; + background: var(--color-accent); + color: white; font-weight: 700; + display: flex; align-items: center; justify-content: center; + font-family: var(--font-display); + flex-shrink: 0; +} +.step-body p { margin: var(--space-1) 0 0; color: var(--color-text-secondary); font-size: var(--text-sm); } +``` + +--- + +## Protocol Conversation + +A variant of the Group Chat Animation specifically designed for API and system interactions. Instead of code components, the actors are protocol-level entities: Client App, Claude API, Claude Model, Tool Server, and User. Use this to illustrate request/response flows, streaming events, tool use cycles, and hook execution chains. + +**When to use:** Any time you need to show how system components communicate — API request lifecycles, streaming event sequences, tool use round-trips, or multi-step agent loops. This is the docs-to-course equivalent of the Group Chat Animation. + +**HTML:** +```html +
+
+ Tool Use Round-Trip +
+ Client + API + Claude + Tool +
+
+ +
+ + + + + + + + + + + + + +
+ + + +
+ + + + 0 / 7 messages +
+
+``` + +**Suggested actor mapping for Claude documentation courses:** + +| Role | Avatar | Color Variable | Use For | +|------|--------|---------------|---------| +| Client App | C | `--color-actor-1` (amber) | Your application code making API calls | +| Claude API | A | `--color-actor-2` (teal) | The API gateway — auth, routing, rate limits | +| Claude (Model) | M | `--color-actor-3` (plum) | Claude's reasoning and responses | +| Tool Server | T | `--color-actor-4` (golden) | External tools, MCP servers, databases | +| User | U | `--color-actor-5` (sky blue) | The end user interacting with the app | + +**Additional CSS for protocol variant:** +```css +.protocol-chat .chat-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: var(--space-3) var(--space-4); + background: var(--color-bg-code); + border-radius: var(--radius-md) var(--radius-md) 0 0; +} +.chat-header-title { + color: #CDD6F4; + font-family: var(--font-mono); + font-size: var(--text-sm); +} +.chat-header-actors { + display: flex; + gap: var(--space-2); +} +.actor-badge { + font-size: var(--text-xs); + padding: 2px 8px; + border-radius: var(--radius-full); + background: color-mix(in srgb, var(--badge-color) 15%, transparent); + color: var(--badge-color); + font-weight: 600; +} +/* Code snippets inside chat bubbles */ +.protocol-chat .chat-bubble code { + background: var(--color-bg-code); + color: #CDD6F4; + padding: 1px 6px; + border-radius: var(--radius-sm); + font-family: var(--font-mono); + font-size: 0.85em; +} +``` + +**JS:** Uses the same pattern as the Group Chat Animation (see above). Replace actor names and IDs: + +```javascript +const protocolActors = { + 'client': { initials: 'C', color: 'var(--color-actor-1)', name: 'Client App' }, + 'api': { initials: 'A', color: 'var(--color-actor-2)', name: 'Claude API' }, + 'claude': { initials: 'M', color: 'var(--color-actor-3)', name: 'Claude' }, + 'tool': { initials: 'T', color: 'var(--color-actor-4)', name: 'Tool Server' }, + 'user': { initials: 'U', color: 'var(--color-actor-5)', name: 'User' }, +}; + +// Same playChatNext/playChatAll/resetChat logic as Group Chat Animation, +// but targeting #protocol-chat-messages and #protocol-typing elements. +``` + +**Scenario ideas for documentation courses:** +- **Messages API lifecycle** — Client → API → Claude → response +- **Tool use round-trip** — Client → Claude → "I need a tool" → Client executes → sends result → Claude responds +- **Streaming flow** — API sends message_start → content_block_start → content_block_delta (repeated) → message_stop +- **Hook execution chain** — User action → Claude proposes tool → PreToolUse hook fires → hook allows/blocks → tool executes +- **MCP server connection** — Claude Code → discovers MCP server → lists tools → calls tool → gets result +- **Agent loop** — User prompt → Claude thinks → uses tool → observes result → thinks again → responds diff --git a/plugin/skills/claude-docs-validate/SKILL.md b/plugin/skills/claude-docs-validate/SKILL.md new file mode 100644 index 000000000..c962068c8 --- /dev/null +++ b/plugin/skills/claude-docs-validate/SKILL.md @@ -0,0 +1,91 @@ +--- +name: claude-docs-validate +description: > + Check the health and freshness of locally-stored Claude documentation. + Use this skill when the user asks about documentation health, broken links, + stale docs, freshness checks, or wants to validate that their local mirror + is up-to-date and all URLs are reachable. Triggers on: "are my docs current", + "check doc health", "validate documentation", "broken links", "stale docs". +--- + +# Claude Documentation Validation Skill + +Check whether the local documentation mirror at `~/.claude-code-docs/` is healthy and up-to-date. + +## When to Use This Skill + +Activate when the user asks about: +- Documentation freshness or staleness +- Broken links or unreachable docs +- Health checks on their local mirror +- Whether docs need updating + +## Validation Workflow + +### Step 1: Check if docs exist + +Verify `~/.claude-code-docs/docs/` exists and contains `.md` files. If not: +> Documentation not found. Run this in Claude Code to install: +> ``` +> /plugin marketplace add costiash/claude-code-docs +> /plugin install claude-docs@claude-code-docs +> ``` + +### Step 2: Check freshness via git + +```bash +cd ~/.claude-code-docs && git log -1 --format="%ci %s" +``` + +Report when docs were last updated. If older than 24 hours, suggest: +```bash +cd ~/.claude-code-docs && git pull +``` + +### Step 3: Run URL validation (if user asks for it) + +For a quick spot-check (recommended first): +```bash +bash ~/.claude-code-docs/plugin/skills/claude-docs-validate/scripts/validate-paths.sh --quick +``` + +For a full scan (all docs — takes 1-2 minutes): +```bash +bash ~/.claude-code-docs/plugin/skills/claude-docs-validate/scripts/validate-paths.sh +``` + +### Step 4: Present results + +- Report summary: total checked, reachable, broken, timed out +- For broken paths, suggest: + - Run `cd ~/.claude-code-docs && git pull` to get latest + - If still broken after pull, the upstream page may have moved + - Report persistent issues at https://github.com/costiash/claude-code-docs/issues + +### Step 5: Doc statistics (if user asks for stats/count) + +Report documentation coverage: +```bash +# Total docs +ls ~/.claude-code-docs/docs/*.md | wc -l + +# By category +echo "Claude Code: $(ls ~/.claude-code-docs/docs/claude-code__*.md 2>/dev/null | wc -l)" +echo "Agent SDK: $(ls ~/.claude-code-docs/docs/docs__en__agent-sdk__*.md 2>/dev/null | wc -l)" +echo "API Reference:$(ls ~/.claude-code-docs/docs/docs__en__api__*.md 2>/dev/null | wc -l)" +echo "Build Guides: $(ls ~/.claude-code-docs/docs/docs__en__build-with-claude__*.md 2>/dev/null | wc -l)" +echo "Tools: $(ls ~/.claude-code-docs/docs/docs__en__agents-and-tools__*.md 2>/dev/null | wc -l)" +``` + +## Troubleshooting + +| Issue | Solution | +|---|---| +| "Documentation not found" | Plugin not installed or docs not cloned. Re-run `/plugin install claude-docs@claude-code-docs` | +| Many broken URLs | Likely a sitemap change. Run `git pull` first, then re-validate | +| Timeout errors | Network issue or Anthropic site is slow. Try again later | +| "Permission denied" | Check that `~/.claude-code-docs/` is readable | + +## Reference Files + +- `examples/validate-docs.md` — Example validation workflow diff --git a/plugin/skills/claude-docs-validate/examples/validate-docs.md b/plugin/skills/claude-docs-validate/examples/validate-docs.md new file mode 100644 index 000000000..1f7db9d0b --- /dev/null +++ b/plugin/skills/claude-docs-validate/examples/validate-docs.md @@ -0,0 +1,28 @@ +# Example: Documentation Validation + +## User Query +> /docs -t + +or + +> Are my docs up to date? + +## Skill Reasoning +- User asks about documentation freshness/health +- Strategy: Run validation workflow + +## Actions +1. Check `~/.claude-code-docs/docs/` exists +2. Run: `cd ~/.claude-code-docs && git log -1 --format="%ci %s"` + - Result: "2026-03-28 12:20:11 +0000 Update Claude Code docs - 2026-03-28" +3. (Optional) Run: `validate-paths.sh --quick` + - Result: "18/20 reachable, 2 broken" + +## Output Format +"Your documentation was last updated on March 28, 2026 (today). + +Quick health check: 18/20 sampled docs are reachable. 2 returned errors: +- `docs__en__resources__prompt-library__code-clarifier.md` → 404 +- `docs__en__resources__prompt-library__meeting-scribe.md` → 404 + +These prompt library pages may have been removed upstream. Run `cd ~/.claude-code-docs && git pull` to sync latest, or report persistent issues at https://github.com/costiash/claude-code-docs/issues." diff --git a/plugin/skills/claude-docs-validate/scripts/validate-paths.sh b/plugin/skills/claude-docs-validate/scripts/validate-paths.sh new file mode 100755 index 000000000..309c78250 --- /dev/null +++ b/plugin/skills/claude-docs-validate/scripts/validate-paths.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +set -euo pipefail + +# validate-paths.sh — HTTP reachability checks for Claude documentation +# Usage: validate-paths.sh [--quick] +# --quick: sample 20 random docs instead of all +# Output: summary + list of broken paths +# Exit: 0 if all reachable, 1 if any broken + +DOCS_DIR="${DOCS_DIR:-${HOME}/.claude-code-docs/docs}" +QUICK_SAMPLE=20 +MAX_PARALLEL=5 +TIMEOUT=10 + +quick_mode=false +if [ "${1:-}" = "--quick" ]; then + quick_mode=true +fi + +if [ ! -d "$DOCS_DIR" ]; then + echo "Documentation directory not found: $DOCS_DIR" >&2 + exit 1 +fi + +filename_to_url() { + local fname="$1" + fname="${fname%.md}" + + if [[ "$fname" == claude-code__* ]]; then + local page="${fname#claude-code__}" + page=$(echo "$page" | sed 's/__/\//g') + echo "https://code.claude.com/docs/en/${page}" + elif [[ "$fname" == docs__en__* ]]; then + local path="${fname#docs__en__}" + path=$(echo "$path" | sed 's/__/\//g') + echo "https://platform.claude.com/en/docs/${path}" + else + echo "" + fi +} + +mapfile -t all_files < <(find "$DOCS_DIR" -maxdepth 1 -name "*.md" -exec basename {} \; | sort) + +if [ ${#all_files[@]} -eq 0 ]; then + echo "No documentation files found" >&2 + exit 1 +fi + +if [ "$quick_mode" = true ]; then + mapfile -t check_files < <(printf '%s\n' "${all_files[@]}" | shuf | head -n "$QUICK_SAMPLE") + echo "Validating ${#check_files[@]} random docs (quick mode)..." +else + check_files=("${all_files[@]}") + echo "Validating all ${#check_files[@]} docs..." +fi + +total=0 +reachable=0 +broken=0 +timeout_count=0 +skipped=0 +redirected=0 +broken_list="" +redirect_list="" + +check_url() { + local fname="$1" + local url + url=$(filename_to_url "$fname") + + if [ -z "$url" ]; then + echo "SKIP $fname" + return + fi + + local status + status=$(curl -sI --max-time "$TIMEOUT" -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000") + + if [ "$status" = "200" ]; then + echo "OK $fname" + elif [ "$status" = "301" ] || [ "$status" = "308" ]; then + echo "REDIRECT_PERM $fname $status $url" + elif [ "$status" = "302" ] || [ "$status" = "307" ]; then + echo "OK $fname" + elif [ "$status" = "000" ]; then + echo "TIMEOUT $fname $url" + else + echo "BROKEN $fname $status $url" + fi +} + +export -f filename_to_url check_url +export DOCS_DIR TIMEOUT + +results=$(printf '%s\n' "${check_files[@]}" | xargs -P "$MAX_PARALLEL" -I{} bash -c 'check_url "$@"' _ {}) + +while IFS= read -r line; do + case "$line" in + OK*) + total=$((total + 1)) + reachable=$((reachable + 1)) + ;; + BROKEN*) + total=$((total + 1)) + broken=$((broken + 1)) + broken_list="${broken_list}${line#BROKEN }\n" + ;; + TIMEOUT*) + total=$((total + 1)) + timeout_count=$((timeout_count + 1)) + broken_list="${broken_list}${line#TIMEOUT } (timeout)\n" + ;; + REDIRECT_PERM*) + total=$((total + 1)) + reachable=$((reachable + 1)) + redirected=$((redirected + 1)) + redirect_list="${redirect_list}${line#REDIRECT_PERM }\n" + ;; + SKIP*) + skipped=$((skipped + 1)) + ;; + esac +done <<< "$results" + +echo "" +echo "=== Validation Summary ===" +echo "Total checked: $total" +echo "Reachable: $reachable" +echo "Redirected: $redirected (permanent — URL may have moved)" +echo "Broken: $broken" +echo "Timeout: $timeout_count" +echo "Skipped: $skipped" + +if [ -n "$redirect_list" ]; then + echo "" + echo "=== Permanent Redirects (URLs may need updating) ===" + echo -e "$redirect_list" +fi + +if [ -n "$broken_list" ]; then + echo "" + echo "=== Broken Paths ===" + echo -e "$broken_list" +fi + +if [ "$broken" -gt 0 ] || [ "$timeout_count" -gt 0 ]; then + exit 1 +fi + +exit 0 diff --git a/plugin/skills/claude-docs/SKILL.md b/plugin/skills/claude-docs/SKILL.md index cbdadea2a..96f40191e 100644 --- a/plugin/skills/claude-docs/SKILL.md +++ b/plugin/skills/claude-docs/SKILL.md @@ -1,5 +1,5 @@ --- -name: claude-docs-search +name: claude-docs description: > Search and read locally-stored Claude documentation covering Claude Code CLI, Claude API (Messages, tool use, vision, streaming, batch), Agent SDK (Python and @@ -10,7 +10,7 @@ description: > custom tools, MCP), model capabilities (context windows, extended thinking, pricing, rate limits, vision), prompt engineering best practices, or troubleshooting any Claude-related error. This skill provides instant access to - 574+ official documentation files without web searches — always prefer it over + official documentation files without web searches — always prefer it over web lookups for Claude and Anthropic topics. --- @@ -22,66 +22,164 @@ You have access to a local mirror of Claude's official documentation at `~/.clau Activate when the user asks about: - Claude Code features: hooks, skills, MCP, plugins, settings, slash commands, sub-agents -- Claude API: messages, tool use, streaming, batch processing, embeddings +- Claude API: messages, tool use, streaming, batch processing - Agent SDK: Python/TypeScript SDK, sessions, custom tools, subagents - Prompt engineering: best practices, system prompts, chain of thought - Any topic covered by platform.claude.com or code.claude.com -## How to Search +## Search Strategy -### Filename-Based Category Inference +Use this hierarchy — try simpler strategies first, escalate if needed: -Documentation files follow naming conventions: -- `claude-code__.md` → Claude Code CLI docs (hooks, mcp, skills, etc.) -- `docs__en__agent-sdk__.md` → Agent SDK docs -- `docs__en__api____.md` → API reference (Python, TypeScript, Go, Java, Kotlin, Ruby) -- `docs__en__build-with-claude__.md` → Guides and tutorials -- `docs__en__resources__prompt-library__.md` → Prompt templates +### 1. Direct Lookup (user names a specific topic) -### Search Strategy +User says "hooks", "mcp", "memory" — a concrete topic name. -**Step 1 — Scope by context if the user names a product:** +``` +Glob: ~/.claude-code-docs/docs/**.md +``` + +If Glob returns matches, read the top 1-3 files and synthesize. + +### 2. Scoped Search (user specifies a product context) + +User says "hooks in agent sdk", "api rate limits", "cli plugins". -| User mentions | Try first | +Scope the Glob to the product prefix: + +| User mentions | Glob pattern | |---|---| | "Claude Code", "CLI", "hooks", "skills", "plugins" | `~/.claude-code-docs/docs/claude-code__**.md` | | "Agent SDK", "SDK", "Python SDK", "TypeScript SDK" | `~/.claude-code-docs/docs/docs__en__agent-sdk__**.md` | -| "API", "messages endpoint", "tool use" | `~/.claude-code-docs/docs/docs__en__api__*.md` + Grep | -| "agents and tools", "MCP connector" | `~/.claude-code-docs/docs/docs__en__agents-and-tools__*.md` | +| "API", "messages endpoint", "tool use" | `~/.claude-code-docs/docs/docs__en__api__**.md` | +| "agents and tools", "MCP connector" | `~/.claude-code-docs/docs/docs__en__agents-and-tools__**.md` | -If the user doesn't name a product, search broadly. +If scoped Glob misses, fall back to content search (step 3). -**Step 2 — Glob for candidate files:** -``` -Glob: ~/.claude-code-docs/docs/**.md +### 3. Semantic/Content Search (user asks a question) + +User says "best practices for extended thinking", "how do I configure streaming". + +**Keyword extraction:** Strip filler words and keep domain-specific terms: +- "how do I configure streaming" → `"streaming"` `"configure"` +- "best practices for extended thinking" → `"extended"` `"thinking"` +- "what's the difference between hooks and MCP" → `"hooks"` `"mcp"` +- "why is my tool use not working" → `"tool-use"` (combine compound concepts with hyphens) + +Run the content search script with extracted keywords: + +```bash +bash ~/.claude-code-docs/plugin/skills/claude-docs/scripts/content-search.sh "" "" ``` -**Step 3 — If Glob finds matches**, Read the most relevant files (up to 3-4) +The script outputs filenames with match scores. Read the top 3-5 matching files and synthesize. + +If the script is not available or returns no results, fall back to Grep: -**Step 4 — If Glob finds nothing**, use Grep for content search: ``` Grep: "" in ~/.claude-code-docs/docs/ ``` -**Step 5 — If both Glob and Grep return nothing:** -- Try alternative keywords (synonyms, related terms) -- Check if the topic exists under a different name (e.g., "function calling" → "tool use") -- Suggest the user run `/docs -t` to check if docs are installed and up to date -- Let the user know the topic may not be covered in the local mirror +### 4. Fuzzy Search (user has an approximate name) + +User says "something about checkpoint", "that caching doc". + +```bash +bash ~/.claude-code-docs/plugin/skills/claude-docs/scripts/fuzzy-search.sh "" +``` + +The script outputs ranked filenames. Read the top match. + +## Synthesis Rules + +### Same Product Context → SYNTHESIZE + +When all matching docs belong to the same product (all Claude Code CLI, all Agent SDK, etc.): +- Read ALL matching docs silently — do not ask the user which to read +- Extract relevant sections +- Present one unified answer +- Cite sources at the end -### Synthesis Instructions +### Different Product Contexts → ASK -- Read ALL matching docs within the same product context -- Synthesize a unified answer — don't dump raw file contents -- Include code examples from the docs when relevant -- Cite sources with official URLs (see below) -- If results span different products, ask user which context they mean +When matches span different products (e.g., CLI + API + Agent SDK): +- Ask the user which product context they mean +- Use these user-friendly labels (see `manifest-reference.md` for complete list): -### Determining Source URLs +| File pattern | Say to user | +|---|---| +| `claude-code__*.md` | **Claude Code** | +| `docs__en__agent-sdk__*.md` | **Agent SDK** | +| `docs__en__api__*.md` | **Claude API** | +| `docs__en__build-with-claude__*.md` | **Claude Documentation** | +| `docs__en__agents-and-tools__*.md` | **Agents & Tools** | +| `docs__en__resources__prompt-library__*.md` | **Prompt Library** | + +After selection → read all docs in that context and synthesize. + +### SDK Language Disambiguation + +When the user specifies a programming language, narrow the API docs to that SDK: + +| User mentions | Narrow search to | +|---|---| +| "Python", "pip", "anthropic" (Python import) | `docs__en__api__python__*` or `docs__en__agent-sdk__python*` | +| "TypeScript", "npm", "@anthropic-ai/sdk" | `docs__en__api__typescript__*` or `docs__en__agent-sdk__typescript*` | +| "Go", "golang" | `docs__en__api__go__*` | +| "Java", "Maven", "Gradle" | `docs__en__api__java__*` | +| "Ruby", "gem" | `docs__en__api__ruby__*` | +| "C#", ".NET", "NuGet" | `docs__en__api__csharp__*` | + +If no language is mentioned but the query is about SDK methods, present the **Python** docs first (most common) and note that TypeScript equivalents exist. + +## URL Generation + +Always include source links in your response: +- `claude-code__.md` → `https://code.claude.com/docs/en/` (replace `__` with `/`) +- `docs__en__.md` → `https://platform.claude.com/en/docs/` (replace leading `docs__en__` then remaining `__` with `/`) + +**Examples:** +- `claude-code__hooks.md` → `https://code.claude.com/docs/en/hooks` +- `docs__en__agent-sdk__python.md` → `https://platform.claude.com/en/docs/agent-sdk/python` +- `docs__en__api__messages__create.md` → `https://platform.claude.com/en/docs/api/messages/create` + +## Common Synonyms + +When a search returns no results or too few, try these known synonyms: + +| User says | Search for | +|---|---| +| "function calling" | "tool use", "tool-use" | +| "system instructions" | "system prompt" | +| "JSON mode" | "structured outputs" | +| "thinking" | "extended thinking", "adaptive thinking" | +| "caching" | "prompt caching", "prompt-caching" | +| "files API" | "files", "pdf support" | +| "sub-agents" | "subagents", "sub-agents" | +| "environment variables" | "settings", "configuration" | +| "CI/CD" | "github actions", "gitlab" | + +## No Results + +If all search strategies return nothing: +1. Try synonyms from the table above +2. Try broader or narrower keywords +3. Suggest the user run `/docs -t` to check if docs are installed and current +4. Let them know the topic may not be in the local mirror + +## Post-Response Course Prompt + +After presenting documentation to the user, always append this emphasized block at the bottom of your response: + +--- +> **Want to go deeper?** I can create an interactive course on this topic — visual explanations, animated diagrams, and hands-on quizzes in a single HTML file you can open in your browser. +> Just say **"create a course on [topic]"** or run `/docs --course [topic]`. -- Files starting with `claude-code__` → `https://code.claude.com/docs/en/` (strip `.md` extension, replace `claude-code__` prefix and `__` with `/`) -- Files starting with `docs__en__` → `https://platform.claude.com/en/docs/` (strip `.md` extension, replace `docs__en__` prefix with `en/docs/` and remaining `__` with `/`) +Replace `[topic]` with the actual topic the user asked about. ## Reference Files -- `manifest-reference.md` — Documentation about the manifest structure and categories +- `manifest-reference.md` — Category-to-label mapping (single source of truth) +- `examples/direct-lookup.md` — Example: topic → Glob → synthesize +- `examples/semantic-search.md` — Example: question → content-search.sh → synthesize +- `examples/cross-context.md` — Example: ambiguous → ask context → synthesize diff --git a/plugin/skills/claude-docs/examples/cross-context.md b/plugin/skills/claude-docs/examples/cross-context.md new file mode 100644 index 000000000..cadbaaefb --- /dev/null +++ b/plugin/skills/claude-docs/examples/cross-context.md @@ -0,0 +1,47 @@ +# Example: Cross-Context Disambiguation + +## User Query +> /docs skills + +## Skill Reasoning +- User names a specific topic: "skills" +- Strategy: Direct lookup (Priority 1) +- Multiple product contexts expected + +## Actions +1. Glob: `~/.claude-code-docs/docs/*skills*.md` +2. Results span 3 product contexts: + - `claude-code__skills.md` → **Claude Code** + - `docs__en__agent-sdk__skills.md` → **Agent SDK** + - `docs__en__api__beta__skills.md` and related → **Claude API** + - `docs__en__agents-and-tools__agent-skills__*.md` → **Agents & Tools** +3. Different contexts → ASK the user + +## Output Format +"Skills exist across several Claude products with different purposes: + +1. **Claude Code** — Install and run pre-built skills in the CLI +2. **Agent SDK** — Build custom agent capabilities in Python/TypeScript +3. **Claude API** — Programmatic skill management endpoints +4. **Agents & Tools** — Agent skill patterns and best practices + +Which are you working with?" + +[After user selects, e.g., "1. Claude Code"] + +→ Read `claude-code__skills.md`, synthesize, present with source link. + +--- + +## User Query (with SDK context) +> /docs how do I create messages in Python? + +## Skill Reasoning +- User mentions "Python" → SDK language disambiguation applies +- Narrow API docs to `docs__en__api__python__*` +- Topic: "messages" + "create" + +## Actions +1. Glob: `~/.claude-code-docs/docs/docs__en__api__python__messages__create.md` → exact match +2. Read and present the Python SDK example +3. Note: "TypeScript equivalent: [Messages Create](https://platform.claude.com/en/docs/api/typescript/messages/create)" diff --git a/plugin/skills/claude-docs/examples/direct-lookup.md b/plugin/skills/claude-docs/examples/direct-lookup.md new file mode 100644 index 000000000..afe0a1a66 --- /dev/null +++ b/plugin/skills/claude-docs/examples/direct-lookup.md @@ -0,0 +1,30 @@ +# Example: Direct Lookup + +## User Query +> /docs hooks + +## Skill Reasoning +- User names a specific topic: "hooks" +- Strategy: Direct lookup (Priority 1) +- No product context specified — search broadly + +## Actions +1. Glob: `~/.claude-code-docs/docs/*hooks*.md` +2. Results: + - `claude-code__hooks.md` (Claude Code CLI) + - `claude-code__hooks-guide.md` (Claude Code CLI) + - `docs__en__agent-sdk__hooks.md` (Agent SDK) +3. All Claude Code files are same context → read both, synthesize +4. Agent SDK file is different context → note but include since "hooks" is unambiguous enough + +## Output Format +"Claude Code hooks allow you to run shell commands at specific points in Claude's workflow... + +[Synthesized explanation from both CLI docs] + +For Agent SDK hooks, see also the [Agent SDK hooks guide](https://platform.claude.com/en/docs/agent-sdk/hooks). + +Sources: +- [Hooks](https://code.claude.com/docs/en/hooks) +- [Hooks Guide](https://code.claude.com/docs/en/hooks-guide) +- [Agent SDK Hooks](https://platform.claude.com/en/docs/agent-sdk/hooks)" diff --git a/plugin/skills/claude-docs/examples/semantic-search.md b/plugin/skills/claude-docs/examples/semantic-search.md new file mode 100644 index 000000000..081efc552 --- /dev/null +++ b/plugin/skills/claude-docs/examples/semantic-search.md @@ -0,0 +1,29 @@ +# Example: Semantic Search + +## User Query +> /docs best practices for extended thinking + +## Skill Reasoning +- User asks a question — no exact filename match for "best practices for extended thinking" +- Strategy: Semantic/Content search (Priority 3) +- **Keyword extraction:** Strip filler words → `"extended"` `"thinking"` +- Check synonym table: "thinking" → also try "extended thinking", "adaptive thinking" + +## Actions +1. Glob: `~/.claude-code-docs/docs/*extended*thinking*.md` → matches found + - `docs__en__build-with-claude__extended-thinking.md` +2. Run: `content-search.sh "extended" "thinking"` for additional results +3. Results (sorted by relevance): + - `docs__en__build-with-claude__adaptive-thinking.md` (2 matches — keywords + preview) + - `docs__en__build-with-claude__extended-thinking.md` (2 matches — keywords + filename) + - `docs__en__api__messages__create.md` (1 match — mentions thinking parameter) +4. All are platform docs (same context) → read top 2-3, synthesize + +## Output Format +"Extended thinking (also called adaptive thinking) lets Claude work through complex problems step by step before responding... + +[Synthesized best practices from the matched docs] + +Sources: +- [Extended Thinking](https://platform.claude.com/en/docs/build-with-claude/extended-thinking) +- [Adaptive Thinking](https://platform.claude.com/en/docs/build-with-claude/adaptive-thinking)" diff --git a/plugin/skills/claude-docs/manifest-reference.md b/plugin/skills/claude-docs/manifest-reference.md index 62b5d9ad4..1fcf33f04 100644 --- a/plugin/skills/claude-docs/manifest-reference.md +++ b/plugin/skills/claude-docs/manifest-reference.md @@ -40,6 +40,23 @@ When presenting results to users: - `release_notes` → "Release Notes" - `resources` → "Resources" +## URL Construction + +Convert filenames to source URLs: + +| Filename | URL | +|---|---| +| `claude-code__hooks.md` | `https://code.claude.com/docs/en/hooks` | +| `claude-code__hooks-guide.md` | `https://code.claude.com/docs/en/hooks-guide` | +| `docs__en__api__messages__create.md` | `https://platform.claude.com/en/docs/api/messages/create` | +| `docs__en__agent-sdk__python.md` | `https://platform.claude.com/en/docs/agent-sdk/python` | +| `docs__en__build-with-claude__vision.md` | `https://platform.claude.com/en/docs/build-with-claude/vision` | +| `docs__en__resources__prompt-library__code-clarifier.md` | `https://platform.claude.com/en/docs/resources/prompt-library/code-clarifier` | + +**Rules:** +- `claude-code__.md` → `https://code.claude.com/docs/en/` +- `docs__en__.md` → `https://platform.claude.com/en/docs/` (replace `__` with `/`) + ## Dynamic Discovery To count available docs: diff --git a/plugin/skills/claude-docs/scripts/content-search.sh b/plugin/skills/claude-docs/scripts/content-search.sh new file mode 100755 index 000000000..c5ba82021 --- /dev/null +++ b/plugin/skills/claude-docs/scripts/content-search.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -uo pipefail +trap '' PIPE + +# content-search.sh — Full-text keyword search across Claude documentation +# Usage: content-search.sh [keyword2] [keyword3] ... +# Searches .search_index.json if available, falls back to grep. +# Output: matching filenames with match counts, sorted by relevance (descending). + +DOCS_DIR="${DOCS_DIR:-${HOME}/.claude-code-docs/docs}" +INDEX_FILE="${DOCS_DIR}/.search_index.json" + +if [ $# -eq 0 ]; then + echo "Usage: content-search.sh [keyword2 ...]" >&2 + exit 1 +fi + +# Sanitize keywords: lowercase, alphanumeric + hyphens only +keywords=() +for arg in "$@"; do + clean=$(echo "$arg" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9 -]//g' | xargs) + [ -n "$clean" ] && keywords+=("$clean") +done + +if [ ${#keywords[@]} -eq 0 ]; then + echo "No valid keywords provided" >&2 + exit 1 +fi + +if [ ! -d "$DOCS_DIR" ]; then + echo "Documentation directory not found: $DOCS_DIR" >&2 + echo "Install docs: /plugin marketplace add costiash/claude-code-docs" >&2 + exit 1 +fi + +# Strategy 1: Use search index if available and jq is installed +if [ -f "$INDEX_FILE" ] && command -v jq >/dev/null 2>&1; then + jq_filter='.index | to_entries[] | {file: .value.file_path, title: .value.title, kw: .value.keywords, preview: .value.content_preview} |' + + count_parts=() + for kw in "${keywords[@]}"; do + escaped=$(echo "$kw" | sed 's/\\/\\\\/g; s/"/\\"/g') + count_parts+=("(if (.kw | map(select(contains(\"${escaped}\"))) | length > 0) or (.title | ascii_downcase | contains(\"${escaped}\")) or (.file | ascii_downcase | contains(\"${escaped}\")) or (.preview | ascii_downcase | contains(\"${escaped}\")) then 1 else 0 end)") + done + + count_expr=$(IFS='+'; echo "${count_parts[*]}") + + results=$(jq -r "${jq_filter} (.file) + \"\t\" + (${count_expr} | tostring)" "$INDEX_FILE" 2>/dev/null \ + | awk -F'\t' '$2 > 0' \ + | sort -t$'\t' -k2 -rn \ + | head -20) + + if [ -n "$results" ]; then + echo "$results" + exit 0 + fi +fi + +# Strategy 2: Fallback to grep + +declare -A file_scores 2>/dev/null || { + # Bash 3 (macOS default) doesn't support associative arrays — use temp file + score_file=$(mktemp) + trap 'rm -f "$score_file"' EXIT + + for kw in "${keywords[@]}"; do + grep -rli "$kw" "$DOCS_DIR"/*.md 2>/dev/null || true + done | sort | uniq -c | sort -rn | head -20 \ + | while read -r count filepath; do + echo -e "$(basename "$filepath")\t$count" + done > "$score_file" + + cat "$score_file" + exit 0 +} + +# Bash 4+ path with associative arrays +for kw in "${keywords[@]}"; do + while IFS= read -r filepath; do + fname=$(basename "$filepath") + file_scores["$fname"]=$(( ${file_scores["$fname"]:-0} + 1 )) + done < <(grep -rli "$kw" "$DOCS_DIR"/*.md 2>/dev/null || true) +done + +for fname in "${!file_scores[@]}"; do + echo -e "${fname}\t${file_scores[$fname]}" +done | sort -t$'\t' -k2 -rn | head -20 + +exit 0 diff --git a/plugin/skills/claude-docs/scripts/fuzzy-search.sh b/plugin/skills/claude-docs/scripts/fuzzy-search.sh new file mode 100755 index 000000000..7dc3890a3 --- /dev/null +++ b/plugin/skills/claude-docs/scripts/fuzzy-search.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +set -euo pipefail + +# fuzzy-search.sh — Fuzzy filename matching for Claude documentation +# Usage: fuzzy-search.sh +# Tokenizes query, matches against filenames in docs/, scores by match quality. +# Output: ranked list of filenames (top 10), one per line. + +DOCS_DIR="${DOCS_DIR:-${HOME}/.claude-code-docs/docs}" + +if [ $# -eq 0 ]; then + echo "Usage: fuzzy-search.sh " >&2 + exit 1 +fi + +query=$(echo "$*" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9 -]//g' | xargs) + +if [ -z "$query" ]; then + echo "No valid query provided" >&2 + exit 1 +fi + +if [ ! -d "$DOCS_DIR" ]; then + echo "Documentation directory not found: $DOCS_DIR" >&2 + exit 1 +fi + +read -ra tokens <<< "$query" + +score_file=$(mktemp) +trap 'rm -f "$score_file"' EXIT + +for filepath in "$DOCS_DIR"/*.md; do + [ -f "$filepath" ] || continue + fname=$(basename "$filepath" .md) + fname_lower=$(echo "$fname" | tr '[:upper:]' '[:lower:]' | tr '_' ' ' | tr '-' ' ') + + score=0 + + # Exact full-query match in filename + if echo "$fname_lower" | grep -q "$query"; then + score=$((score + 100)) + fi + + # Also try hyphenated form (e.g., "tool use" → "tool-use") + query_hyphen=$(echo "$query" | tr ' ' '-') + if [ "$query_hyphen" != "$query" ] && echo "$fname_lower" | grep -q "$query_hyphen"; then + score=$((score + 90)) + fi + + # Also try space form of hyphenated query (e.g., "sub-agents" → "sub agents") + query_spaced=$(echo "$query" | tr '-' ' ') + if [ "$query_spaced" != "$query" ] && echo "$fname_lower" | grep -q "$query_spaced"; then + score=$((score + 90)) + fi + + matched_tokens=0 + for token in "${tokens[@]}"; do + token_spaced=$(echo "$token" | tr '-' ' ') + if echo "$fname_lower" | grep -q "$token" || echo "$fname_lower" | grep -q "$token_spaced"; then + # Longer tokens are more specific, weight them higher + token_len=${#token} + if [ "$token_len" -ge 6 ]; then + score=$((score + 15)) + else + score=$((score + 10)) + fi + matched_tokens=$((matched_tokens + 1)) + fi + done + + if [ "$matched_tokens" -eq "${#tokens[@]}" ] && [ "${#tokens[@]}" -gt 1 ]; then + score=$((score + 50)) + fi + + if [ "$score" -gt 0 ]; then + echo -e "${score}\t${fname}.md" >> "$score_file" + fi +done + +sort -t$'\t' -k1 -rn "$score_file" | head -10 | cut -f2 + +exit 0 diff --git a/pyproject.toml b/pyproject.toml index f6fe411a8..153fc00b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "claude-code-docs" -version = "0.5.0" +version = "1.0.0" description = "Claude Code documentation mirror with automated updates and enhanced features" readme = "README.md" requires-python = ">=3.9" @@ -78,3 +78,8 @@ source = [ "*/claude-code-docs/scripts/", "*/work/claude-code-docs/claude-code-docs/scripts/", ] + +[dependency-groups] +dev = [ + "shellcheck-py>=0.11.0.1", +] diff --git a/test-skills.sh b/test-skills.sh new file mode 100755 index 000000000..f09100107 --- /dev/null +++ b/test-skills.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +set -euo pipefail + +# test-skills.sh — Mechanical test harness for plugin skill quality +# Runs content-search and fuzzy-search with known queries, checks expected results. +# Output: PASS: (total passed tests out of total) + +DOCS_DIR="${DOCS_DIR:-$(cd "$(dirname "$0")" && pwd)/docs}" +SCRIPTS_DIR="$(cd "$(dirname "$0")" && pwd)/plugin/skills/claude-docs/scripts" + +export DOCS_DIR + +pass=0 +fail=0 +total=0 + +check() { + local description="$1" + local script="$2" + shift 2 + local expected="$1" + shift + local args=("$@") + + total=$((total + 1)) + local output + output=$("$SCRIPTS_DIR/$script" "${args[@]}" 2>/dev/null) || output="" + + if echo "$output" | grep -q "$expected"; then + pass=$((pass + 1)) + else + fail=$((fail + 1)) + echo "FAIL: $description — expected '$expected' in output" >&2 + fi +} + +# === Content Search Tests === +check "content: hooks" content-search.sh claude-code__hooks.md "hooks" +check "content: mcp" content-search.sh claude-code__mcp.md "mcp" +check "content: extended thinking" content-search.sh docs__en__build-with-claude__extended-thinking.md "extended" "thinking" +check "content: streaming" content-search.sh docs__en__build-with-claude__streaming.md "streaming" +check "content: prompt caching" content-search.sh docs__en__build-with-claude__prompt-caching.md "prompt" "caching" +check "content: rate limits" content-search.sh docs__en__api__rate-limits.md "rate" "limits" +check "content: agent sdk python" content-search.sh docs__en__agent-sdk__python.md "agent" "sdk" "python" +check "content: vision" content-search.sh docs__en__build-with-claude__vision.md "vision" + +# === Fuzzy Search Tests === +check "fuzzy: hooks" fuzzy-search.sh claude-code__hooks.md "hooks" +check "fuzzy: mcp" fuzzy-search.sh claude-code__mcp.md "mcp" +check "fuzzy: plugins" fuzzy-search.sh claude-code__plugins.md "plugins" +check "fuzzy: agent sdk" fuzzy-search.sh docs__en__agent-sdk "agent sdk" +check "fuzzy: streaming" fuzzy-search.sh streaming "streaming" +check "fuzzy: skills" fuzzy-search.sh skills "skills" +check "fuzzy: vision" fuzzy-search.sh vision "vision" + +# === Edge Case Tests === +check "content: computer use" content-search.sh docs__en__agents-and-tools__tool-use__computer-use-tool.md "computer" +check "content: batch processing" content-search.sh docs__en__build-with-claude__batch-processing.md "batch" "processing" +check "content: prompt engineering" content-search.sh docs__en__build-with-claude__prompt-engineering "prompt" "engineering" +check "fuzzy: tool use overview" fuzzy-search.sh docs__en__agents-and-tools__tool-use__overview.md "tool use overview" +check "fuzzy: batch" fuzzy-search.sh batch "batch" + +# === Robustness Tests === +check "content: citations" content-search.sh docs__en__build-with-claude__citations.md "citations" +check "content: embeddings" content-search.sh docs__en__build-with-claude__embeddings.md "embeddings" +check "fuzzy: quickstart" fuzzy-search.sh claude-code__quickstart.md "quickstart" +check "fuzzy: settings" fuzzy-search.sh claude-code__settings.md "settings" +check "fuzzy: desktop" fuzzy-search.sh claude-code__desktop.md "desktop" + +# === Additional Search Coverage === +check "content: sandboxing" content-search.sh claude-code__sandboxing.md "sandboxing" +check "content: context windows" content-search.sh docs__en__build-with-claude__context-windows.md "context" "windows" +check "fuzzy: headless" fuzzy-search.sh claude-code__headless.md "headless" +check "fuzzy: tool use" fuzzy-search.sh docs__en__agents-and-tools__tool-use "tool use" +check "fuzzy: hooks guide" fuzzy-search.sh claude-code__hooks-guide.md "hooks guide" +check "content: devcontainer" content-search.sh claude-code__devcontainer.md "devcontainer" +check "content: jetbrains" content-search.sh claude-code__jetbrains.md "jetbrains" + +# === Synonym-Adjacent Tests === +check "content: structured outputs" content-search.sh docs__en__build-with-claude__structured-outputs.md "structured" "outputs" +check "content: github actions" content-search.sh claude-code__github-actions.md "github" "actions" +check "fuzzy: sub-agents" fuzzy-search.sh claude-code__sub-agents.md "sub-agents" + +# === SDK Disambiguation Tests === +check "content: python sdk" content-search.sh docs__en__api__sdks__python.md "python" "sdk" +check "fuzzy: typescript sdk" fuzzy-search.sh docs__en__api__sdks__typescript.md "typescript sdk" +check "fuzzy: go sdk" fuzzy-search.sh docs__en__api__sdks__go.md "go sdk" + +# === URL Conversion Tests (extracted from validate-paths.sh) === +_filename_to_url() { + local fname="$1" + fname="${fname%.md}" + if [[ "$fname" == claude-code__* ]]; then + local page="${fname#claude-code__}" + page=$(echo "$page" | sed 's/__/\//g') + echo "https://code.claude.com/docs/en/${page}" + elif [[ "$fname" == docs__en__* ]]; then + local path="${fname#docs__en__}" + path=$(echo "$path" | sed 's/__/\//g') + echo "https://platform.claude.com/en/docs/${path}" + else + echo "" + fi +} + +check_url() { + local desc="$1" input="$2" expected="$3" + total=$((total + 1)) + local got + got=$(_filename_to_url "$input") + if [ "$got" = "$expected" ]; then + pass=$((pass + 1)) + else + fail=$((fail + 1)) + echo "FAIL: $desc — expected '$expected', got '$got'" >&2 + fi +} + +check_url "url: claude-code simple" "claude-code__hooks.md" "https://code.claude.com/docs/en/hooks" +check_url "url: claude-code nested" "claude-code__hooks-guide.md" "https://code.claude.com/docs/en/hooks-guide" +check_url "url: platform simple" "docs__en__api__overview.md" "https://platform.claude.com/en/docs/api/overview" +check_url "url: platform deep" "docs__en__api__messages__create.md" "https://platform.claude.com/en/docs/api/messages/create" +check_url "url: agent sdk" "docs__en__agent-sdk__python.md" "https://platform.claude.com/en/docs/agent-sdk/python" +check_url "url: build-with-claude" "docs__en__build-with-claude__vision.md" "https://platform.claude.com/en/docs/build-with-claude/vision" +check_url "url: prompt library" "docs__en__resources__prompt-library__code-clarifier.md" "https://platform.claude.com/en/docs/resources/prompt-library/code-clarifier" +check_url "url: unknown prefix" "random-file.md" "" + +# === Additional Coverage === +check "content: model config" content-search.sh claude-code__model-config.md "model" "config" +check "fuzzy: security" fuzzy-search.sh claude-code__security.md "security" +check "fuzzy: network config" fuzzy-search.sh claude-code__network-config.md "network config" +check "content: pricing" content-search.sh docs__en__about-claude__pricing.md "pricing" +check "fuzzy: troubleshooting" fuzzy-search.sh claude-code__troubleshooting.md "troubleshooting" +check "content: pdf support" content-search.sh docs__en__build-with-claude__pdf-support.md "pdf" +check "content: data residency" content-search.sh docs__en__build-with-claude__data-residency.md "residency" +check "content: glossary" content-search.sh docs__en__about-claude__glossary.md "glossary" +check "fuzzy: analytics" fuzzy-search.sh claude-code__analytics.md "analytics" +check "fuzzy: costs" fuzzy-search.sh claude-code__costs.md "costs" +check "content: model overview" content-search.sh docs__en__about-claude__models__overview.md "models" "overview" +check "content: error handling" content-search.sh docs__en__api__errors.md "errors" +check "fuzzy: output styles" fuzzy-search.sh claude-code__output-styles.md "output styles" +check "fuzzy: checkpointing" fuzzy-search.sh claude-code__checkpointing.md "checkpointing" +check "fuzzy: monitoring usage" fuzzy-search.sh claude-code__monitoring-usage.md "monitoring usage" +check "fuzzy: interactive" fuzzy-search.sh claude-code__interactive-mode.md "interactive" +check "content: data usage" content-search.sh claude-code__data-usage.md "data" "usage" +check "fuzzy: vs code" fuzzy-search.sh claude-code__vs-code.md "vs code" +check "fuzzy: terminal" fuzzy-search.sh claude-code__terminal-config.md "terminal" +check "content: fast mode" content-search.sh docs__en__build-with-claude__fast-mode.md "fast" "mode" +check "fuzzy: legal compliance" fuzzy-search.sh claude-code__legal-and-compliance.md "legal" +check "content: compaction" content-search.sh docs__en__build-with-claude__compaction.md "compaction" +check "content: service tiers" content-search.sh docs__en__api__service-tiers.md "service" "tiers" +check "fuzzy: statusline" fuzzy-search.sh claude-code__statusline.md "statusline" +check "fuzzy: amazon bedrock" fuzzy-search.sh claude-code__amazon-bedrock.md "amazon bedrock" +check "content: openai sdk compat" content-search.sh docs__en__api__openai-sdk.md "openai" +check_url "url: tool use deep" "docs__en__agents-and-tools__tool-use__define-tools.md" "https://platform.claude.com/en/docs/agents-and-tools/tool-use/define-tools" + +echo "PASS: $pass/$total" +echo "FAIL: $fail/$total" diff --git a/tests/unit/test_manifest_validation.py b/tests/unit/test_manifest_validation.py index 48b46fd0c..9947055b5 100644 --- a/tests/unit/test_manifest_validation.py +++ b/tests/unit/test_manifest_validation.py @@ -245,7 +245,7 @@ def test_search_index_valid_json(self, project_root): assert 'index' in data def test_search_index_file_count(self, project_root): - """Verify search index has correct file count""" + """Verify search index covers all markdown files on disk.""" search_index = project_root / 'docs' / '.search_index.json' with open(search_index) as f: @@ -253,10 +253,8 @@ def test_search_index_file_count(self, project_root): indexed_files = data.get('indexed_files', 0) - # Should match docs_manifest.json — the source of truth for tracked files - docs_manifest_path = project_root / 'docs' / 'docs_manifest.json' - with open(docs_manifest_path) as f: - docs_manifest = json.load(f) - expected_count = len(docs_manifest.get('files', {})) - assert indexed_files == expected_count, \ - f"Search index shows {indexed_files} files, expected {expected_count} (from docs_manifest.json)" + # Should match actual .md files in docs/ (the index is built from disk, not manifest) + docs_dir = project_root / 'docs' + actual_md_files = len([f for f in docs_dir.glob('*.md') if f.name != 'docs_manifest.json']) + assert indexed_files == actual_md_files, \ + f"Search index has {indexed_files} files, but {actual_md_files} .md files exist on disk" diff --git a/tests/validation/test_sitemap_consistency.py b/tests/validation/test_sitemap_consistency.py index b4fe83ba1..21ae67476 100644 --- a/tests/validation/test_sitemap_consistency.py +++ b/tests/validation/test_sitemap_consistency.py @@ -14,16 +14,20 @@ class TestManifestCompleteness: @pytest.mark.integration def test_all_categories_present(self, paths_manifest): - """Test all expected categories are in manifest.""" - expected_categories = [ - 'core_documentation', - 'api_reference', - 'claude_code', - 'prompt_library' - ] + """Test structural categories are in manifest. - for category in expected_categories: - assert category in paths_manifest['categories'] + api_reference, core_documentation, and claude_code always exist because + they map to permanent URL patterns in Anthropic's sitemaps. Other categories + (prompt_library, resources, release_notes) depend on what the sitemaps return. + """ + categories = paths_manifest['categories'] + + # These 3 are structural — they always exist due to how categorize_path() works + for required in ['api_reference', 'core_documentation', 'claude_code']: + assert required in categories, f"Missing structural category: {required}" + + # Manifest should have at least these 3, possibly more + assert len(categories) >= 3 @pytest.mark.integration def test_metadata_complete(self, paths_manifest): @@ -158,44 +162,31 @@ def test_api_reference_largest_category(self, paths_manifest): @pytest.mark.integration def test_all_categories_nonempty(self, paths_manifest): - """Test main categories are not empty.""" - main_categories = [ - 'core_documentation', - 'api_reference', - 'claude_code', - 'prompt_library' - ] - - for category in main_categories: - paths = paths_manifest['categories'].get(category, []) - # Should have at least some paths + """Test every category in the manifest has at least one path.""" + for category, paths in paths_manifest['categories'].items(): assert len(paths) > 0, f"{category} is empty" @pytest.mark.integration def test_category_counts_reasonable(self, paths_manifest): - """Test category counts are within reasonable ranges.""" + """Test structural properties of category distribution. + + Instead of hardcoding count ranges (which break when sitemaps change), + validate invariants that hold regardless of Anthropic's doc structure. + """ categories = paths_manifest['categories'] + total = sum(len(paths) for paths in categories.values()) + + # Total paths must exceed the safety threshold used by the fetcher + assert total >= 200, f"Total paths {total} below safety threshold (200)" + + # api_reference is always the largest (multi-language SDK docs dominate) + api_count = len(categories.get('api_reference', [])) + assert api_count > total * 0.50, \ + f"api_reference ({api_count}) should be >50% of total ({total})" - # Based on current active documentation (573 total paths): - # api_reference: ~377 (65.8%) - includes multi-language SDK docs - # core_documentation: ~82 (14.3%) - # prompt_library: ~65 (11.3%) - # claude_code: ~46 (8%) - # release_notes: ~2 - # resources: ~1 - - # Allow reasonable variance for future updates - expected_ranges = { - 'core_documentation': (60, 200), - 'api_reference': (200, 600), # Large due to multi-language SDK docs - 'claude_code': (30, 100), - 'prompt_library': (40, 150) - } - - for category, (min_count, max_count) in expected_ranges.items(): - actual_count = len(categories.get(category, [])) - assert min_count <= actual_count <= max_count, \ - f"{category}: {actual_count} not in range [{min_count}, {max_count}]" + # claude_code should have a reasonable number of CLI pages + cc_count = len(categories.get('claude_code', [])) + assert cc_count >= 20, f"claude_code has only {cc_count} paths (expected >=20)" class TestManifestFormat: diff --git a/uninstall.sh b/uninstall.sh index 09267ae47..2ef126abd 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -1,138 +1,45 @@ #!/bin/bash set -euo pipefail -# Claude Code Documentation Mirror - Smart Uninstaller -# Dynamically finds and removes all installations +# Claude Code Docs — Uninstaller v1.0.0 -echo "Claude Code Documentation Mirror - Uninstaller" -echo "==============================================" +echo "Claude Code Docs — Uninstaller" +echo "===============================" echo "" -# Find all installations from configs -find_all_installations() { - local paths=() - - # From command file - if [[ -f ~/.claude/commands/docs.md ]]; then - while IFS= read -r line; do - if [[ "$line" =~ Execute:.*claude-code-docs ]]; then - local path=$(echo "$line" | grep -o '[^ "]*claude-code-docs[^ "]*' | head -1) - path="${path/#\~/$HOME}" - - # Get directory part - if [[ -d "$path" ]]; then - paths+=("$path") - elif [[ -d "$(dirname "$path")" ]] && [[ "$(basename "$(dirname "$path")")" == "claude-code-docs" ]]; then - paths+=("$(dirname "$path")") - fi - fi - done < ~/.claude/commands/docs.md - fi - - # From hooks - if [[ -f ~/.claude/settings.json ]]; then - local hooks=$(jq -r '.hooks.PreToolUse[]?.hooks[]?.command // empty' ~/.claude/settings.json 2>/dev/null) - while IFS= read -r cmd; do - if [[ "$cmd" =~ claude-code-docs ]]; then - local found=$(echo "$cmd" | grep -o '[^ "]*claude-code-docs[^ "]*' || true) - while IFS= read -r path; do - [[ -z "$path" ]] && continue - path="${path/#\~/$HOME}" - # Clean up path to get the claude-code-docs directory - if [[ "$path" =~ (.*/claude-code-docs)(/.*)?$ ]]; then - path="${BASH_REMATCH[1]}" - fi - [[ -d "$path" ]] && paths+=("$path") - done <<< "$found" - fi - done <<< "$hooks" - fi - - # Deduplicate - handle empty array case - if [[ ${#paths[@]} -gt 0 ]]; then - printf '%s\n' "${paths[@]}" | sort -u - fi -} +INSTALL_DIR="$HOME/.claude-code-docs" -# Main uninstall logic -installations=() -while IFS= read -r line; do - installations+=("$line") -done < <(find_all_installations) - -if [[ ${#installations[@]} -gt 0 ]]; then - echo "Found installations at:" - for path in "${installations[@]}"; do - echo " 📁 $path" - done - echo "" -fi - -echo "This will remove:" -echo " • The /docs command from ~/.claude/commands/docs.md" -echo " • Any legacy hooks from ~/.claude/settings.json (if present)" -if [[ ${#installations[@]} -gt 0 ]]; then - echo " • Installation directories (if safe to remove)" -fi +echo "To uninstall the plugin, run inside Claude Code:" +echo "" +echo " /plugin uninstall claude-docs@claude-code-docs" echo "" -read -p "Continue? (y/N): " -n 1 -r -echo -if [[ ! $REPLY =~ ^[Yy]$ ]]; then - echo "Cancelled." - exit 0 -fi - -# Remove command file -if [[ -f ~/.claude/commands/docs.md ]]; then - rm -f ~/.claude/commands/docs.md - echo "✓ Removed /docs command" -fi - -# Remove hooks -if [[ -f ~/.claude/settings.json ]]; then - cp ~/.claude/settings.json ~/.claude/settings.json.backup - - # Remove ALL hooks containing claude-code-docs - jq '.hooks.PreToolUse = [(.hooks.PreToolUse // [])[] | select(.hooks[0].command | contains("claude-code-docs") | not)]' ~/.claude/settings.json > ~/.claude/settings.json.tmp - - # Clean up empty structures - jq 'if .hooks.PreToolUse == [] then .hooks |= if . == {PreToolUse: []} then {} else del(.PreToolUse) end else . end | if .hooks == {} then del(.hooks) else . end' ~/.claude/settings.json.tmp > ~/.claude/settings.json.tmp2 - - mv ~/.claude/settings.json.tmp2 ~/.claude/settings.json - rm -f ~/.claude/settings.json.tmp - echo "✓ Cleaned up legacy hooks (backup: ~/.claude/settings.json.backup)" -fi - -# Remove directories -if [[ ${#installations[@]} -gt 0 ]]; then +if [ -d "$INSTALL_DIR" ]; then + echo "Local documentation found at: $INSTALL_DIR" echo "" - for path in "${installations[@]}"; do - if [[ ! -d "$path" ]]; then - continue - fi - - if [[ -d "$path/.git" ]]; then - # Save current directory - local current_dir=$(pwd) - cd "$path" - - if [[ -z "$(git status --porcelain 2>/dev/null)" ]]; then - cd "$current_dir" - rm -rf "$path" - echo "✓ Removed $path (clean git repo)" - else - cd "$current_dir" - echo "⚠️ Preserved $path (has uncommitted changes)" - fi + + if [ -t 0 ]; then + read -p "Remove local documentation? (y/N): " -n 1 -r + echo + if [[ $REPLY =~ ^[Yy]$ ]]; then + rm -rf "$INSTALL_DIR" + echo "Removed $INSTALL_DIR" else - echo "⚠️ Preserved $path (not a git repo)" + echo "Kept $INSTALL_DIR (documentation files still available locally)" fi - done + else + echo "Run interactively to remove, or: rm -rf $INSTALL_DIR" + fi +fi + +# Clean up any legacy artifacts +if [ -f "$HOME/.claude/commands/docs.md" ]; then + if grep -q "claude-docs-helper" "$HOME/.claude/commands/docs.md" 2>/dev/null; then + rm -f "$HOME/.claude/commands/docs.md" + echo "Removed legacy /docs command" + fi fi echo "" -echo "✅ Uninstall complete!" -echo "" -echo "To reinstall:" -echo "curl -fsSL https://raw.githubusercontent.com/costiash/claude-code-docs/main/install.sh | bash" \ No newline at end of file +echo "Uninstall complete." +echo "To reinstall: /plugin marketplace add costiash/claude-code-docs"