claude-md-master
---
name: claude-md-master
description: Master skill for CLAUDE.md lifecycle - create, update, improve with repo-verified content and multi-module support. Use when creating or updating CLAUDE.md files.
---
# CLAUDE.md Master (Create/Update/Improver)
## When to use
- User asks to create, improve, update, or standardize CLAUDE.md files.
## Core rules
- Only include info verified in repo or config.
- Never include secrets, tokens, credentials, or user data.
- Never include task-specific or temporary instructions.
- Keep concise: root <= 200 lines, module <= 120 lines.
- Use bullets; avoid long prose.
- Commands must be copy-pasteable and sourced from repo docs/scripts/CI.
- Skip empty sections; avoid filler.
## Mandatory inputs (analyze before generating)
- Build/package config relevant to detected stack (root + modules).
- Static analysis config used in repo (if present).
- Actual module structure and source patterns (scan real dirs/files).
- Representative source roots per module to extract:
package/feature structure, key types, and annotations in use.
## Discovery (fast + targeted)
1. Locate existing CLAUDE.md variants: `CLAUDE.md`, `.claude.md`, `.claude.local.md`.
2. Identify stack and entry points via minimal reads:
- `README.md`, relevant `docs/*`
- Build/package files (see stack references)
- Runtime/config: `Dockerfile`, `docker-compose.yml`, `.env.example`, `config/*`
- CI: `.github/workflows/*`, `.gitlab-ci.yml`, `.circleci/*`
3. Extract commands only if they exist in repo scripts/config/docs.
4. Detect multi-module structure:
- Android/Gradle: read `settings.gradle` or `settings.gradle.kts` includes.
- iOS: detect multiple targets/workspaces in `*.xcodeproj`/`*.xcworkspace`.
- If more than one module/target has `src/` or build config, plan module CLAUDE.md files.
5. For each module candidate, read its build file + minimal docs to capture
module-specific purpose, entry points, and commands.
6. Scan source roots for:
- Top-level package/feature folders and layer conventions.
- Key annotations/types in use (per stack reference).
- Naming conventions used in the codebase.
7. Capture non-obvious workflows/gotchas from docs or code patterns.
Performance:
- Prefer file listing + targeted reads.
- Avoid full-file reads when a section or symbol is enough.
- Skip large dirs: `node_modules`, `vendor`, `build`, `dist`.
## Stack-specific references (Pattern 2)
Read the relevant reference only when detection signals appear:
- Android/Gradle → `references/android.md`
- iOS/Xcode/Swift → `references/ios.md`
- PHP → `references/php.md`
- Go → `references/go.md`
- React (web) → `references/react-web.md`
- React Native → `references/react-native.md`
- Rust → `references/rust.md`
- Python → `references/python.md`
- Java/JVM → `references/java.md`
- Node tooling → `references/node.md`
- .NET/C# → `references/dotnet.md`
- Dart/Flutter → `references/flutter.md`
- Ruby/Rails → `references/ruby.md`
- Elixir/Erlang → `references/elixir.md`
- C/C++/CMake → `references/cpp.md`
- Other/Unknown → `references/generic.md` (fallback when no specific reference matches)
If multiple stacks are detected, read multiple references.
If no stack is recognized, use the generic reference.
## Multi-module output policy (mandatory when detected)
- Always create a root `CLAUDE.md`.
- Also create `CLAUDE.md` inside each meaningful module/target root.
- "Meaningful" = has its own build config and `src/` (or equivalent).
- Skip tooling-only dirs like `buildSrc`, `gradle`, `scripts`, `tools`.
- Module file must be module-specific and avoid duplication:
- Include purpose, key paths, entry points, module tests, and module
commands (if any).
- Reference shared info via `@/CLAUDE.md`.
## Business module CLAUDE.md policy (all stacks)
For monorepo business logic directories (`src/`, `lib/`, `packages/`, `internal/`):
- Create `CLAUDE.md` for modules with >5 files OR own README
- Skip utility-only dirs: `Helper`, `Utils`, `Common`, `Shared`, `Exception`, `Trait`, `Constants`
- Layered structure not required; provide module info regardless of architecture
- Max 120 lines per module CLAUDE.md
- Reference root via `@/CLAUDE.md` for shared architecture/patterns
- Include: purpose, structure, key classes, dependencies, entry points
## Mandatory output sections (per module CLAUDE.md)
Include these sections if detected in codebase (skip only if not present):
- **Feature/component inventory**: list top-level dirs under source root
- **Core/shared modules**: utility, common, or shared code directories
- **Navigation/routing structure**: navigation graphs, routes, or routers
- **Network/API layer pattern**: API clients, endpoints, response wrappers
- **DI/injection pattern**: modules, containers, or injection setup
- **Build/config files**: module-specific configs (proguard, manifests, etc.)
See stack-specific references for exact patterns to detect and report.
## Update workflow (must follow)
1. Propose targeted additions only; show diffs per file.
2. Ask for approval before applying updates:
**Cursor IDE:**
Use the AskQuestion tool with these options:
- id: "approval"
- prompt: "Apply these CLAUDE.md updates?"
- options: [{"id": "yes", "label": "Yes, apply"}, {"id": "no", "label": "No, cancel"}]
**Claude Code (Terminal):**
Output the proposed changes and ask:
"Do you approve these updates? (yes/no)"
Stop and wait for user response before proceeding.
**Other Environments (Fallback):**
If no structured question tool is available:
1. Display proposed changes clearly
2. Ask: "Do you approve these updates? Reply 'yes' to apply or 'no' to cancel."
3. Wait for explicit user confirmation before proceeding
3. Apply updates, preserving custom content.
If no CLAUDE.md exists, propose a new file for approval.
## Content extraction rules (mandatory)
- From codebase only:
- Extract: type/class/annotation names used, real path patterns,
naming conventions.
- Never: hardcoded values, secrets, API keys, business-specific logic.
- Never: code snippets in Do/Do Not rules.
## Verification before writing
- [ ] Every rule references actual types/paths from codebase
- [ ] No code examples in Do/Do Not sections
- [ ] Patterns match what's actually in the codebase (not outdated)
## Content rules
- Include: commands, architecture summary, key paths, testing, gotchas, workflow quirks.
- Exclude: generic best practices, obvious info, unverified statements.
- Use `@path/to/file` imports to avoid duplication.
- Do/Do Not format is optional; keep only if already used in the file.
- Avoid code examples except short copy-paste commands.
## Existing file strategy
Detection:
- If `<!-- Generated by claude-md-editor skill -->` exists → subsequent run
- Else → first run
First run + existing file:
- Backup `CLAUDE.md` → `CLAUDE.md.bak`
- Use `.bak` as a source and extract only reusable, project-specific info
- Generate a new concise file and add the marker
Subsequent run:
- Preserve custom sections and wording unless outdated or incorrect
- Update only what conflicts with current repo state
- Add missing sections only if they add real value
Never modify `.claude.local.md`.
## Output
After updates, print a concise report:
```
## CLAUDE.md Update Report
- /CLAUDE.md [CREATED | BACKED_UP+CREATED | UPDATED]
- /<module>/CLAUDE.md [CREATED | UPDATED]
- Backups: list any `.bak` files
```
## Validation checklist
- Description is specific and includes trigger terms
- No placeholders remain
- No secrets included
- Commands are real and copy-pasteable
- Report-first rule respected
- References are one level deep
FILE:README.md
# claude-md-master
Master skill for the CLAUDE.md lifecycle: create, update, and improve files
using repo-verified data, with multi-module support and stack-specific rules.
## Overview
- Goal: produce accurate, concise `CLAUDE.md` files from real repo data
- Scope: root + meaningful modules, with stack-specific detection
- Safeguards: no secrets, no filler, explicit approval before writes
## How the AI discovers and uses this skill
- Discovery: the tool learns this skill because it exists in the
repo skills catalog (installed/available in the environment)
- Automatic use: when a request includes "create/update/improve
CLAUDE.md", the tool selects this skill as the best match
- Manual use: the operator can explicitly invoke `/claude-md-master`
to force this workflow
- Run behavior: it scans repo docs/config/source, proposes changes,
and waits for explicit approval before writing files
## Audience
- AI operators using skills in Cursor/Claude Code
- Maintainers who evolve the rules and references
## What it does
- Generates or updates `CLAUDE.md` with verified, repo-derived content
- Enforces strict safety and concision rules (no secrets, no filler)
- Detects multi-module repos and produces module-level `CLAUDE.md`
- Uses stack-specific references to capture accurate patterns
## When to use
- A user asks to create, improve, update, or standardize `CLAUDE.md`
- A repo needs consistent, verified guidance for AI workflows
## Inputs required (must be analyzed)
- Repo docs: `README.md`, `docs/*` (if present)
- Build/config files relevant to detected stack(s)
- Runtime/config: `Dockerfile`, `.env.example`, `config/*` (if present)
- CI: `.github/workflows/*`, `.gitlab-ci.yml`, `.circleci/*` (if present)
- Source roots to extract real structure, types, annotations, naming
## Output
- Root `CLAUDE.md` (always)
- Module `CLAUDE.md` for meaningful modules (build config + `src/`)
- Concise update report listing created/updated files and backups
## Workflow (high level)
1. Locate existing `CLAUDE.md` variants and detect first vs. subsequent run
2. Identify stack(s) and multi-module structure
3. Read relevant docs/configs/CI for real commands and workflow
4. Scan source roots for structure, key types, annotations, patterns
5. Generate root + module files, avoiding duplication via `@/CLAUDE.md`
6. Request explicit approval before applying updates
7. Apply changes and print the update report
## Core rules and constraints
- Only include info verified in repo; never add secrets
- Keep concise: root <= 200 lines, module <= 120 lines
- Commands must be real and copy-pasteable from repo docs/scripts/CI
- Skip empty sections; avoid generic guidance
- Never modify `.claude.local.md`
- Avoid code examples in Do/Do Not sections
## Multi-module policy (summary)
- Always create root `CLAUDE.md`
- Create module-level files only for meaningful modules
- Skip tooling-only dirs (e.g., `buildSrc`, `gradle`, `scripts`, `tools`)
- Business modules get their own file when >5 files or own README
## References (stack-specific guides)
Each reference defines detection signals, pre-gen sources, codebase scan
targets, mandatory output items, command sources, and key paths.
- `references/android.md` — Android/Gradle
- `references/ios.md` — iOS/Xcode/Swift
- `references/react-web.md` — React web apps
- `references/react-native.md` — React Native
- `references/node.md` — Node tooling (generic)
- `references/python.md` — Python
- `references/java.md` — Java/JVM
- `references/dotnet.md` — .NET (C#/F#)
- `references/go.md` — Go
- `references/rust.md` — Rust
- `references/flutter.md` — Dart/Flutter
- `references/ruby.md` — Ruby/Rails
- `references/php.md` — PHP (Laravel/Symfony/CI/Phalcon)
- `references/elixir.md` — Elixir/Erlang
- `references/cpp.md` — C/C++
- `references/generic.md` — Fallback when no stack matches
## Extending the skill
- Add a new `references/<stack>.md` using the same template
- Keep detection signals and mandatory outputs specific and verifiable
- Do not introduce unverified commands or generic advice
## Quality checklist
- Every rule references actual types/paths from the repo
- No placeholders remain
- No secrets included
- Commands are real and copy-pasteable
- Report-first rule respected; references are one level deep
FILE:references/android.md
# Android (Gradle)
## Detection signals
- `settings.gradle` or `settings.gradle.kts`
- `build.gradle` or `build.gradle.kts`
- `gradle.properties`
- `gradle/libs.versions.toml`
- `gradlew`
- `gradle/wrapper/gradle-wrapper.properties`
- `app/src/main/AndroidManifest.xml`
## Multi-module signals
- Multiple `include(...)` or `includeBuild(...)` entries in `settings.gradle*`
- More than one module dir with `build.gradle*` and `src/`
- Common module roots like `feature/`, `core/`, `library/` (if present)
## Before generating, analyze these sources
- `settings.gradle` or `settings.gradle.kts`
- `build.gradle` or `build.gradle.kts` (root and modules)
- `gradle/libs.versions.toml`
- `gradle.properties`
- `config/detekt/detekt.yml` (if present)
- `app/src/main/AndroidManifest.xml` (or module manifests)
## Codebase scan (Android-specific)
- Source roots per module: `*/src/main/java/`, `*/src/main/kotlin/`
- Package tree for feature/layer folders (record only if present):
`features/`, `core/`, `common/`, `data/`, `domain/`, `presentation/`,
`ui/`, `di/`, `navigation/`, `network/`
- Annotation usage (record only if present):
Hilt (`@HiltAndroidApp`, `@AndroidEntryPoint`, `@HiltViewModel`,
`@Module`, `@InstallIn`, `@Provides`, `@Binds`),
Compose (`@Composable`, `@Preview`),
Room (`@Entity`, `@Dao`, `@Database`),
WorkManager (`@HiltWorker`, `ListenableWorker`, `CoroutineWorker`),
Serialization (`@Serializable`, `@Parcelize`),
Retrofit (`@GET`, `@POST`, `@PUT`, `@DELETE`, `@Body`, `@Query`)
- Navigation patterns (record only if present): `NavHost`, `composable`
## Mandatory output (Android module CLAUDE.md)
Include these if detected (list actual names found):
- **Features inventory**: list dirs under `features/` (e.g., homepage, payment, auth)
- **Core modules**: list dirs under `core/` (e.g., data, network, localization)
- **Navigation graphs**: list `*Graph.kt` or `*Navigator*.kt` files
- **Hilt modules**: list `@Module` classes or `di/` package contents
- **Retrofit APIs**: list `*Api.kt` interfaces
- **Room databases**: list `@Database` classes
- **Workers**: list `@HiltWorker` classes
- **Proguard**: mention `proguard-rules.pro` if present
## Command sources
- README/docs or CI invoking Gradle wrapper
- Repo scripts that call `./gradlew`
- `./gradlew assemble`, `./gradlew test`, `./gradlew lint` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `app/src/main/`, `app/src/main/res/`
- `app/src/main/java/`, `app/src/main/kotlin/`
- `app/src/test/`, `app/src/androidTest/`
FILE:references/cpp.md
# C / C++
## Detection signals
- `CMakeLists.txt`
- `meson.build`
- `Makefile`
- `conanfile.*`, `vcpkg.json`
- `compile_commands.json`
- `src/`, `include/`
## Multi-module signals
- `CMakeLists.txt` with `add_subdirectory(...)`
- Multiple `CMakeLists.txt` or `meson.build` in subdirs
- `libs/`, `apps/`, or `modules/` with their own build files
## Before generating, analyze these sources
- `CMakeLists.txt` / `meson.build` / `Makefile`
- `conanfile.*`, `vcpkg.json` (if present)
- `compile_commands.json` (if present)
- `src/`, `include/`, `tests/`, `libs/`
## Codebase scan (C/C++-specific)
- Source roots: `src/`, `include/`, `tests/`, `libs/`
- Library/app split (record only if present):
`src/lib`, `src/app`, `src/bin`
- Namespaces and class prefixes (record only if present)
- CMake targets (record only if present):
`add_library`, `add_executable`
## Mandatory output (C/C++ module CLAUDE.md)
Include these if detected (list actual names found):
- **Libraries**: list library targets
- **Executables**: list executable targets
- **Headers**: list public header directories
- **Modules/components**: list subdirectories with build files
- **Dependencies**: list Conan/vcpkg dependencies (if any)
## Command sources
- README/docs or CI invoking `cmake`, `ninja`, `make`, or `meson`
- Repo scripts that call build tools
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/`, `include/`
- `tests/`, `libs/`
FILE:references/dotnet.md
# .NET (C# / F#)
## Detection signals
- `*.sln`
- `*.csproj`, `*.fsproj`, `*.vbproj`
- `global.json`
- `Directory.Build.props`, `Directory.Build.targets`
- `nuget.config`
- `Program.cs`
- `Startup.cs`
- `appsettings*.json`
## Multi-module signals
- `*.sln` with multiple project entries
- Multiple `*.*proj` files under `src/` and `tests/`
- `Directory.Build.*` managing shared settings across projects
## Before generating, analyze these sources
- `*.sln`, `*.csproj` / `*.fsproj` / `*.vbproj`
- `Directory.Build.props`, `Directory.Build.targets`
- `global.json`, `nuget.config`
- `Program.cs` / `Startup.cs`
- `appsettings*.json`
## Codebase scan (.NET-specific)
- Source roots: `src/`, `tests/`, project folders with `*.csproj`
- Layer folders (record only if present):
`Controllers`, `Services`, `Repositories`, `Domain`, `Infrastructure`
- ASP.NET attributes (record only if present):
`[ApiController]`, `[Route]`, `[HttpGet]`, `[HttpPost]`, `[Authorize]`
- EF Core usage (record only if present):
`DbContext`, `Migrations`, `[Key]`, `[Table]`
## Mandatory output (.NET module CLAUDE.md)
Include these if detected (list actual names found):
- **Controllers**: list `[ApiController]` classes
- **Services**: list service classes
- **Repositories**: list repository classes
- **Entities**: list EF Core entity classes
- **DbContext**: list database context classes
- **Middleware**: list custom middleware
- **Configuration**: list config sections or options classes
## Command sources
- README/docs or CI invoking `dotnet`
- Repo scripts like `build.ps1`, `build.sh`
- `dotnet run`, `dotnet test` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/`, `tests/`
- `appsettings*.json`
- `Controllers/`, `Models/`, `Views/`, `wwwroot/`
FILE:references/elixir.md
# Elixir / Erlang
## Detection signals
- `mix.exs`, `mix.lock`
- `config/config.exs`
- `lib/`, `test/`
- `apps/` (umbrella)
- `rel/`
## Multi-module signals
- Umbrella with `apps/` containing multiple `mix.exs`
- Root `mix.exs` with `apps_path`
## Before generating, analyze these sources
- Root `mix.exs`, `mix.lock`
- `config/config.exs`
- `apps/*/mix.exs` (umbrella)
- `lib/`, `test/`, `rel/`
## Codebase scan (Elixir-specific)
- Source roots: `lib/`, `test/`, `apps/*/lib` (umbrella)
- Phoenix structure (record only if present):
`lib/*_web/`, `controllers`, `views`, `channels`, `routers`
- Ecto usage (record only if present):
`schema`, `Repo`, `migrations`
- Contexts/modules (record only if present):
`lib/*/` context modules and `*_context.ex`
## Mandatory output (Elixir module CLAUDE.md)
Include these if detected (list actual names found):
- **Contexts**: list context modules
- **Schemas**: list Ecto schema modules
- **Controllers**: list Phoenix controller modules
- **Channels**: list Phoenix channel modules
- **Workers**: list background job modules (Oban, etc.)
- **Umbrella apps**: list apps under umbrella (if any)
## Command sources
- README/docs or CI invoking `mix`
- Repo scripts that call `mix`
- Only include commands present in repo
## Key paths to mention (only if present)
- `lib/`, `test/`, `config/`
- `apps/`, `rel/`
FILE:references/flutter.md
# Dart / Flutter
## Detection signals
- `pubspec.yaml`, `pubspec.lock`
- `analysis_options.yaml`
- `lib/`
- `android/`, `ios/`, `web/`, `macos/`, `windows/`, `linux/`
## Multi-module signals
- `melos.yaml` (Flutter monorepo)
- Multiple `pubspec.yaml` under `packages/`, `apps/`, or `plugins/`
## Before generating, analyze these sources
- `pubspec.yaml`, `pubspec.lock`
- `analysis_options.yaml`
- `melos.yaml` (if monorepo)
- `lib/`, `test/`, and platform folders (`android/`, `ios/`, etc.)
## Codebase scan (Flutter-specific)
- Source roots: `lib/`, `test/`
- Entry point (record only if present): `lib/main.dart`
- Layer folders (record only if present):
`features/`, `core/`, `data/`, `domain/`, `presentation/`
- State management (record only if present):
`Bloc`, `Cubit`, `ChangeNotifier`, `Provider`, `Riverpod`
- Widget naming (record only if present):
`*Screen`, `*Page`
## Mandatory output (Flutter module CLAUDE.md)
Include these if detected (list actual names found):
- **Features**: list dirs under `features/` or `lib/`
- **Core modules**: list dirs under `core/` (if present)
- **State management**: list Bloc/Cubit/Provider setup
- **Repositories**: list repository classes
- **Data sources**: list remote/local data source classes
- **Widgets**: list shared widget directories
## Command sources
- README/docs or CI invoking `flutter`
- Repo scripts that call `flutter` or `dart`
- `flutter run`, `flutter test`, `flutter pub get` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `lib/`, `test/`
- `android/`, `ios/`
FILE:references/generic.md
# Generic / Unknown Stack
Use this reference when no specific stack reference matches.
## Detection signals (common patterns)
- `README.md`, `CONTRIBUTING.md`
- `Makefile`, `Taskfile.yml`, `justfile`
- `Dockerfile`, `docker-compose.yml`
- `.env.example`, `config/`
- CI files: `.github/workflows/`, `.gitlab-ci.yml`, `.circleci/`
## Before generating, analyze these sources
- `README.md` - project overview, setup instructions, commands
- Build/package files in root (any recognizable format)
- `Makefile`, `Taskfile.yml`, `justfile`, `scripts/` (if present)
- CI/CD configs for build/test commands
- `Dockerfile` for runtime info
## Codebase scan (generic)
- Identify source root: `src/`, `lib/`, `app/`, `pkg/`, or root
- Layer folders (record only if present):
`controllers`, `services`, `models`, `handlers`, `utils`, `config`
- Entry points: `main.*`, `index.*`, `app.*`, `server.*`
- Test location: `tests/`, `test/`, `spec/`, `__tests__/`, or co-located
## Mandatory output (generic CLAUDE.md)
Include these if detected (list actual names found):
- **Entry points**: main files, startup scripts
- **Source structure**: top-level dirs under source root
- **Config files**: environment, settings, secrets template
- **Build system**: detected build tool and config location
- **Test setup**: test framework and run command
## Command sources
- README setup/usage sections
- `Makefile` targets, `Taskfile.yml` tasks, `justfile` recipes
- CI workflow steps (build, test, lint)
- `scripts/` directory
- Only include commands present in repo
## Key paths to mention (only if present)
- Source root and its top-level structure
- Config/environment files
- Test directory
- Documentation location
- Build output directory
FILE:references/go.md
# Go
## Detection signals
- `go.mod`, `go.sum`, `go.work`
- `cmd/`, `internal/`
- `main.go`
- `magefile.go`
- `Taskfile.yml`
## Multi-module signals
- `go.work` with multiple module paths
- Multiple `go.mod` files in subdirs
- `apps/` or `services/` each with its own `go.mod`
## Before generating, analyze these sources
- `go.work`, `go.mod`, `go.sum`
- `cmd/`, `internal/`, `pkg/` layout
- `Makefile`, `Taskfile.yml`, `magefile.go` (if present)
## Codebase scan (Go-specific)
- Source roots: `cmd/`, `internal/`, `pkg/`, `api/`
- Layer folders (record only if present):
`handler`, `service`, `repository`, `store`, `config`
- Framework markers (record only if present):
`gin`, `echo`, `fiber`, `chi` imports
- Entry points (record only if present):
`cmd/*/main.go`, `main.go`
## Mandatory output (Go module CLAUDE.md)
Include these if detected (list actual names found):
- **Commands**: list binaries under `cmd/`
- **Handlers**: list HTTP handler packages
- **Services**: list service packages
- **Repositories**: list repository or store packages
- **Models**: list domain model packages
- **Config**: list config loading packages
## Command sources
- README/docs or CI
- `Makefile`, `Taskfile.yml`, or repo scripts invoking Go tools
- `go test ./...`, `go run` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `cmd/`, `internal/`, `pkg/`, `api/`
- `tests/` or `*_test.go` layout
FILE:references/ios.md
# iOS (Xcode/Swift)
## Detection signals
- `Package.swift`
- `*.xcodeproj` or `*.xcworkspace`
- `Podfile`, `Cartfile`
- `Project.swift`, `Tuist/`
- `fastlane/Fastfile`
- `*.xcconfig`
- `Sources/` or `Tests/` (SPM layouts)
## Multi-module signals
- Multiple targets/projects in `*.xcworkspace` or `*.xcodeproj`
- `Package.swift` with multiple targets/products
- `Sources/<TargetName>` and `Tests/<TargetName>` layout
- `Project.swift` defining multiple targets (Tuist)
## Before generating, analyze these sources
- `Package.swift` (SPM)
- `*.xcodeproj/project.pbxproj` or `*.xcworkspace/contents.xcworkspacedata`
- `Podfile`, `Cartfile` (if present)
- `Project.swift` / `Tuist/` (if present)
- `fastlane/Fastfile` (if present)
- `Sources/` and `Tests/` layout for targets
## Codebase scan (iOS-specific)
- Source roots: `Sources/`, `Tests/`, `ios/` (if present)
- Feature/layer folders (record only if present):
`Features/`, `Core/`, `Services/`, `Networking/`, `UI/`, `Domain/`, `Data/`
- SwiftUI usage (record only if present):
`@main`, `App`, `@State`, `@StateObject`, `@ObservedObject`,
`@Environment`, `@EnvironmentObject`, `@Binding`
- UIKit/lifecycle (record only if present):
`UIApplicationDelegate`, `SceneDelegate`, `UIViewController`
- Combine/concurrency (record only if present):
`@Published`, `Publisher`, `AnyCancellable`, `@MainActor`, `Task`
## Mandatory output (iOS module CLAUDE.md)
Include these if detected (list actual names found):
- **Features inventory**: list dirs under `Features/` or feature targets
- **Core modules**: list dirs under `Core/`, `Services/`, `Networking/`
- **Navigation**: list coordinators, routers, or SwiftUI navigation files
- **DI container**: list DI setup (Swinject, Factory, manual containers)
- **Network layer**: list API clients or networking services
- **Persistence**: list CoreData models or other storage classes
## Command sources
- README/docs or CI invoking Xcode or Swift tooling
- Repo scripts that call Xcode/Swift tools
- `xcodebuild`, `swift build`, `swift test` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `Sources/`, `Tests/`
- `fastlane/`
- `ios/` (React Native or multi-platform repos)
FILE:references/java.md
# Java / JVM
## Detection signals
- `pom.xml` or `build.gradle*`
- `settings.gradle`, `gradle.properties`
- `mvnw`, `gradlew`
- `gradle/wrapper/gradle-wrapper.properties`
- `src/main/java`, `src/test/java`, `src/main/kotlin`
- `src/main/resources/application.yml`, `src/main/resources/application.properties`
## Multi-module signals
- `settings.gradle*` includes multiple modules
- Parent `pom.xml` with `<modules>` (packaging `pom`)
- Multiple `build.gradle*` or `pom.xml` files in subdirs
## Before generating, analyze these sources
- `settings.gradle*` and `build.gradle*` (if Gradle)
- Parent and module `pom.xml` (if Maven)
- `gradle/libs.versions.toml` (if present)
- `gradle.properties` / `mvnw` / `gradlew`
- `src/main/resources/application.yml|application.properties` (if present)
## Codebase scan (Java/JVM-specific)
- Source roots: `src/main/java`, `src/main/kotlin`, `src/test/java`, `src/test/kotlin`
- Package/layer folders (record only if present):
`controller`, `service`, `repository`, `domain`, `model`, `dto`, `config`, `client`
- Framework annotations (record only if present):
`@SpringBootApplication`, `@RestController`, `@Controller`, `@Service`,
`@Repository`, `@Component`, `@Configuration`, `@Bean`, `@Transactional`
- Persistence/validation (record only if present):
`@Entity`, `@Table`, `@Id`, `@OneToMany`, `@ManyToOne`, `@Valid`, `@NotNull`
- Entry points (record only if present):
`*Application` classes with `main`
## Mandatory output (Java/JVM module CLAUDE.md)
Include these if detected (list actual names found):
- **Controllers**: list `@RestController` or `@Controller` classes
- **Services**: list `@Service` classes
- **Repositories**: list `@Repository` classes or JPA interfaces
- **Entities**: list `@Entity` classes
- **Configuration**: list `@Configuration` classes
- **Security**: list security config or auth filters
- **Profiles**: list Spring profiles in use
## Command sources
- Maven/Gradle wrapper scripts
- README/docs or CI
- `./mvnw spring-boot:run`, `./gradlew bootRun` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/main/java`, `src/test/java`
- `src/main/kotlin`, `src/test/kotlin`
- `src/main/resources`, `src/test/resources`
- `src/main/java/**/controller`, `src/main/java/**/service`, `src/main/java/**/repository`
FILE:references/node.md
# Node Tooling (generic)
## Detection signals
- `package.json`
- `package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`
- `.nvmrc`, `.node-version`
- `tsconfig.json`
- `.npmrc`, `.yarnrc.yml`
- `next.config.*`, `nuxt.config.*`
- `nest-cli.json`, `svelte.config.*`, `astro.config.*`
## Multi-module signals
- `pnpm-workspace.yaml`, `lerna.json`, `nx.json`, `turbo.json`, `rush.json`
- Root `package.json` with `workspaces`
- Multiple `package.json` under `apps/`, `packages/`
## Before generating, analyze these sources
- Root `package.json` and workspace config (`pnpm-workspace.yaml`, `lerna.json`,
`nx.json`, `turbo.json`, `rush.json`)
- `apps/*/package.json`, `packages/*/package.json` (if monorepo)
- `tsconfig.json` or `jsconfig.json`
- Framework config: `next.config.*`, `nuxt.config.*`, `nest-cli.json`,
`svelte.config.*`, `astro.config.*` (if present)
## Codebase scan (Node-specific)
- Source roots: `src/`, `lib/`, `apps/`, `packages/`
- Folder patterns (record only if present):
`routes`, `controllers`, `services`, `middlewares`, `handlers`,
`utils`, `config`, `models`, `schemas`
- Framework markers (record only if present):
Express (`express()`, `Router`), Koa (`new Koa()`),
Fastify (`fastify()`), Nest (`@Controller`, `@Module`, `@Injectable`)
- Full-stack layouts (record only if present):
Next/Nuxt (`pages/`, `app/`, `server/`)
## Mandatory output (Node module CLAUDE.md)
Include these if detected (list actual names found):
- **Routes/pages**: list route files or page components
- **Controllers/handlers**: list controller or handler files
- **Services**: list service classes or modules
- **Middlewares**: list middleware files
- **Models/schemas**: list data models or validation schemas
- **State management**: list store setup (Redux, Zustand, etc.)
- **API clients**: list external API client modules
## Command sources
- `package.json` scripts
- README/docs or CI
- `npm|yarn|pnpm` script usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/`, `lib/`
- `tests/`
- `apps/`, `packages/` (monorepos)
- `pages/`, `app/`, `server/`, `api/`
- `controllers/`, `services/`
FILE:references/php.md
# PHP
## Detection signals
- `composer.json`, `composer.lock`
- `public/index.php`
- `artisan`, `spark`, `bin/console` (framework entry points)
- `phpunit.xml`, `phpstan.neon`, `phpstan.neon.dist`, `psalm.xml`
- `config/app.php`
- `routes/web.php`, `routes/api.php`
- `config/packages/` (Symfony)
- `app/Config/` (CI4)
- `ext-phalcon` in composer.json (Phalcon)
- `phalcon/ide-stubs`, `phalcon/devtools` (Phalcon)
## Multi-module signals
- `modules/` or `app/Modules/` (HMVC style)
- `app/Config/Modules.php`, `app/Config/Autoload.php` (CI4)
- Multiple PSR-4 roots in `composer.json`
- Multiple `composer.json` under `packages/` or `apps/`
- `apps/` with subdirectories containing `Module.php` or `controllers/`
## Before generating, analyze these sources
- `composer.json`, `composer.lock`
- `config/` and `routes/` (framework configs)
- `app/Config/*` (CI4)
- `modules/` or `app/Modules/` (if HMVC)
- `phpunit.xml`, `phpstan.neon*`, `psalm.xml` (if present)
- `bin/worker.php`, `bin/console.php` (CLI entry points)
## Codebase scan (PHP-specific)
- Source roots: `app/`, `src/`, `modules/`, `packages/`, `apps/`
- Laravel structure (record only if present):
`app/Http/Controllers`, `app/Models`, `database/migrations`,
`routes/*.php`, `resources/views`
- Symfony structure (record only if present):
`src/Controller`, `src/Entity`, `config/packages`, `templates`
- CodeIgniter structure (record only if present):
`app/Controllers`, `app/Models`, `app/Views`, `app/Config/Routes.php`,
`app/Database/Migrations`
- Phalcon structure (record only if present):
`apps/*/controllers/`, `apps/*/Module.php`, `models/`
- Attributes/annotations (record only if present):
`#[Route]`, `#[Entity]`, `#[ORM\\Column]`
## Business module discovery
Scan these paths based on detected framework:
- Laravel: `app/Services/`, `app/Domains/`, `app/Modules/`, `packages/`
- Symfony: `src/` top-level directories
- CodeIgniter: `app/Modules/`, `modules/`
- Phalcon: `src/`, `apps/*/`
- Generic: `src/`, `lib/`
For each path:
- List top 5-10 largest modules by file count
- For each significant module (>5 files), note its purpose if inferable from name
- Identify layered patterns if present: `*/Repository/`, `*/Service/`, `*/Controller/`, `*/Action/`
## Module-level CLAUDE.md signals
Scan these paths for significant modules (framework-specific):
- `src/` - Symfony, Phalcon, custom frameworks
- `app/Services/`, `app/Domains/` - Laravel domain-driven
- `app/Modules/`, `modules/` - Laravel/CI4 HMVC
- `packages/` - Laravel internal packages
- `apps/` - Phalcon multi-app
Create `<path>/<Module>/CLAUDE.md` when:
- Threshold: module has >5 files OR has own `README.md`
- Skip utility dirs: `Helper/`, `Exception/`, `Trait/`, `Contract/`, `Interface/`, `Constants/`, `Support/`
- Layered structure not required; provide module info regardless of architecture
### Module CLAUDE.md content (max 120 lines)
- Purpose: 1-2 sentence module description
- Structure: list subdirectories (Service/, Repository/, etc.)
- Key classes: main service/manager/action classes
- Dependencies: other modules this depends on (via use statements)
- Entry points: main public interfaces/facades
- Framework-specific: ServiceProvider (Laravel), Module.php (Phalcon/CI4)
## Worker/Job detection
- `bin/worker.php` or similar worker entry points
- `*/Job/`, `*/Jobs/`, `*/Worker/` directories
- Queue config files (`queue.php`, `rabbitmq.php`, `amqp.php`)
- List job classes if present
## API versioning detection
- `routes_v*.php` or `routes/v*/` patterns
- `controllers/v*/` directory structure
- Note current/active API version from route files or config
## Mandatory output (PHP module CLAUDE.md)
Include these if detected (list actual names found):
- **Controllers**: list controller directories/classes
- **Models**: list model/entity classes or directory
- **Services**: list service classes or directory
- **Repositories**: list repository classes or directory
- **Routes**: list route files and versioning pattern
- **Migrations**: mention migrations dir and file count
- **Middleware**: list middleware classes
- **Views/templates**: mention view engine and layout
- **Workers/Jobs**: list job classes if present
- **Business modules**: list top modules from detected source paths by size
## Command sources
- `composer.json` scripts
- README/docs or CI
- `php artisan`, `bin/console` usage in docs/scripts
- `bin/worker.php` commands
- Only include commands present in repo
## Key paths to mention (only if present)
- `app/`, `src/`, `apps/`
- `public/`, `routes/`, `config/`, `database/`
- `app/Http/`, `resources/`, `storage/` (Laravel)
- `templates/` (Symfony)
- `app/Controllers/`, `app/Views/` (CI4)
- `apps/*/controllers/`, `models/` (Phalcon)
- `tests/`, `tests/acceptance/`, `tests/unit/`
FILE:references/python.md
# Python
## Detection signals
- `pyproject.toml`
- `requirements.txt`, `requirements-dev.txt`, `Pipfile`, `poetry.lock`
- `tox.ini`, `pytest.ini`
- `manage.py`
- `setup.py`, `setup.cfg`
- `settings.py`, `urls.py` (Django)
## Multi-module signals
- Multiple `pyproject.toml`/`setup.py`/`setup.cfg` in subdirs
- `packages/` or `apps/` each with its own package config
- Django-style `apps/` with multiple `apps.py` (if present)
## Before generating, analyze these sources
- `pyproject.toml` or `setup.py` / `setup.cfg`
- `requirements*.txt`, `Pipfile`, `poetry.lock`
- `tox.ini`, `pytest.ini`
- `manage.py`, `settings.py`, `urls.py` (if Django)
- Package roots under `src/`, `app/`, `packages/` (if present)
## Codebase scan (Python-specific)
- Source roots: `src/`, `app/`, `packages/`, `tests/`
- Folder patterns (record only if present):
`api`, `routers`, `views`, `services`, `repositories`,
`models`, `schemas`, `utils`, `config`
- Django structure (record only if present):
`apps.py`, `models.py`, `views.py`, `urls.py`, `migrations/`, `settings.py`
- FastAPI/Flask markers (record only if present):
`FastAPI()`, `APIRouter`, `@app.get`, `@router.post`,
`Flask(__name__)`, `Blueprint`
- Type model usage (record only if present):
`pydantic.BaseModel`, `TypedDict`, `dataclass`
## Mandatory output (Python module CLAUDE.md)
Include these if detected (list actual names found):
- **Routers/views**: list API router or view files
- **Services**: list service modules
- **Models/schemas**: list data models (Pydantic, SQLAlchemy, Django)
- **Repositories**: list repository or DAO modules
- **Migrations**: mention migrations dir
- **Middleware**: list middleware classes
- **Django apps**: list installed apps (if Django)
## Command sources
- `pyproject.toml` tool sections
- README/docs or CI
- Repo scripts invoking Python tools
- `python manage.py`, `pytest`, `tox` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/`, `app/`, `scripts/`
- `templates/`, `static/`
- `tests/`
FILE:references/react-native.md
# React Native
## Detection signals
- `package.json` with `react-native`
- `react-native.config.js`
- `metro.config.js`
- `ios/`, `android/`
- `babel.config.js`, `app.json`, `app.config.*`
- `eas.json`, `expo` in `package.json`
## Multi-module signals
- `pnpm-workspace.yaml`, `lerna.json`, `nx.json`, `turbo.json`
- Root `package.json` with `workspaces`
- `packages/` or `apps/` each with `package.json`
## Before generating, analyze these sources
- Root `package.json` and workspace config (`pnpm-workspace.yaml`, `lerna.json`,
`nx.json`, `turbo.json`)
- `react-native.config.js`, `metro.config.js`
- `ios/` and `android/` native folders
- `app.json` / `app.config.*` / `eas.json` (if Expo)
## Codebase scan (React Native-specific)
- Source roots: `src/`, `app/`
- Entry points (record only if present):
`index.js`, `index.ts`, `App.tsx`
- Native folders (record only if present): `ios/`, `android/`
- Navigation/state (record only if present):
`react-navigation`, `redux`, `mobx`
- Native module patterns (record only if present):
`NativeModules`, `TurboModule`
## Mandatory output (React Native module CLAUDE.md)
Include these if detected (list actual names found):
- **Screens/navigators**: list screen components and navigators
- **Components**: list shared component directories
- **Services/API**: list API client modules
- **State management**: list store setup
- **Native modules**: list custom native modules
- **Platform folders**: mention ios/ and android/ setup
## Command sources
- `package.json` scripts
- README/docs or CI
- Native build files in `ios/` and `android/`
- `expo` script usage in docs/scripts (if Expo)
- Only include commands present in repo
## Key paths to mention (only if present)
- `ios/`, `android/`
- `src/`, `app/`
FILE:references/react-web.md
# React (Web)
## Detection signals
- `package.json`
- `src/`, `public/`
- `vite.config.*`, `next.config.*`, `webpack.config.*`
- `tsconfig.json`
- `turbo.json`
- `app/` or `pages/` (Next.js)
## Multi-module signals
- `pnpm-workspace.yaml`, `lerna.json`, `nx.json`, `turbo.json`
- Root `package.json` with `workspaces`
- `apps/` and `packages/` each with `package.json`
## Before generating, analyze these sources
- Root `package.json` and workspace config (`pnpm-workspace.yaml`, `lerna.json`,
`nx.json`, `turbo.json`)
- `apps/*/package.json`, `packages/*/package.json` (if monorepo)
- `vite.config.*`, `next.config.*`, `webpack.config.*`
- `tsconfig.json` / `jsconfig.json`
## Codebase scan (React web-specific)
- Source roots: `src/`, `app/`, `pages/`, `components/`, `hooks/`, `services/`
- Folder patterns (record only if present):
`routes`, `store`, `state`, `api`, `utils`, `assets`
- Routing markers (record only if present):
React Router (`Routes`, `Route`), Next (`app/`, `pages/`)
- State management (record only if present):
`redux`, `zustand`, `recoil`
- Naming conventions (record only if present):
hooks `use*`, components PascalCase
## Mandatory output (React web module CLAUDE.md)
Include these if detected (list actual names found):
- **Pages/routes**: list page components or route files
- **Components**: list shared component directories
- **Hooks**: list custom hooks
- **Services/API**: list API client modules
- **State management**: list store setup (Redux, Zustand, etc.)
- **Utils**: list utility modules
## Command sources
- `package.json` scripts
- README/docs or CI
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/`, `public/`
- `app/`, `pages/`, `components/`
- `hooks/`, `services/`
- `apps/`, `packages/` (monorepos)
FILE:references/ruby.md
# Ruby / Rails
## Detection signals
- `Gemfile`, `Gemfile.lock`
- `Rakefile`
- `config.ru`
- `bin/rails` or `bin/rake`
- `config/application.rb`
- `config/routes.rb`
## Multi-module signals
- Multiple `Gemfile` or `.gemspec` files in subdirs
- `gems/`, `packages/`, or `engines/` with separate gem specs
- Multiple Rails apps under `apps/` (each with `config/application.rb`)
## Before generating, analyze these sources
- `Gemfile`, `Gemfile.lock`, and any `.gemspec`
- `config/application.rb`, `config/routes.rb`
- `Rakefile` / `bin/rails` (if present)
- `engines/`, `gems/`, `apps/` (if multi-app/engine setup)
## Codebase scan (Ruby/Rails-specific)
- Source roots: `app/`, `lib/`, `engines/`, `gems/`
- Rails layers (record only if present):
`app/models`, `app/controllers`, `app/views`, `app/jobs`, `app/services`
- Config and initializers (record only if present):
`config/routes.rb`, `config/application.rb`, `config/initializers/`
- ActiveRecord/migrations (record only if present):
`db/migrate`, `ActiveRecord::Base`
- Tests (record only if present): `spec/`, `test/`
## Mandatory output (Ruby module CLAUDE.md)
Include these if detected (list actual names found):
- **Controllers**: list controller classes
- **Models**: list ActiveRecord models
- **Services**: list service objects
- **Jobs**: list background job classes
- **Routes**: summarize key route namespaces
- **Migrations**: mention db/migrate count
- **Engines**: list mounted engines (if any)
## Command sources
- README/docs or CI invoking `bundle`, `rails`, `rake`
- `Rakefile` tasks
- `bundle exec` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `app/`, `config/`, `db/`
- `app/controllers/`, `app/models/`, `app/views/`
- `spec/` or `test/`
FILE:references/rust.md
# Rust
## Detection signals
- `Cargo.toml`, `Cargo.lock`
- `rust-toolchain.toml`
- `src/main.rs`, `src/lib.rs`
- Workspace members in `Cargo.toml`, `crates/`
## Multi-module signals
- `[workspace]` with `members` in `Cargo.toml`
- Multiple `Cargo.toml` under `crates/` or `apps/`
## Before generating, analyze these sources
- Root `Cargo.toml`, `Cargo.lock`
- `rust-toolchain.toml` (if present)
- Workspace `Cargo.toml` in `crates/` or `apps/`
- `src/main.rs` / `src/lib.rs`
## Codebase scan (Rust-specific)
- Source roots: `src/`, `crates/`, `tests/`, `examples/`
- Module layout (record only if present):
`lib.rs`, `main.rs`, `mod.rs`, `src/bin/*`
- Serde usage (record only if present):
`#[derive(Serialize, Deserialize)]`
- Async/runtime (record only if present):
`tokio`, `async-std`
- Web frameworks (record only if present):
`axum`, `actix-web`, `warp`
## Mandatory output (Rust module CLAUDE.md)
Include these if detected (list actual names found):
- **Crates**: list workspace crates with purpose
- **Binaries**: list `src/bin/*` or `[[bin]]` targets
- **Modules**: list top-level `mod` declarations
- **Handlers/routes**: list web handler modules (if web app)
- **Models**: list domain model modules
- **Config**: list config loading modules
## Command sources
- README/docs or CI
- Repo scripts invoking `cargo`
- `cargo test`, `cargo run` usage in docs/scripts
- Only include commands present in repo
## Key paths to mention (only if present)
- `src/`, `crates/`
- `tests/`, `examples/`, `benches/`
Context7 Documentation Expert Agent
---
name: Context7-Expert
description: 'Expert in latest library versions, best practices, and correct syntax using up-to-date documentation'
argument-hint: 'Ask about specific libraries/frameworks (e.g., "Next.js routing", "React hooks", "Tailwind CSS")'
tools: ['read', 'search', 'web', 'context7/*', 'agent/runSubagent']
mcp-servers:
context7:
type: http
url: "https://mcp.context7.com/mcp"
headers: {"CONTEXT7_API_KEY": "${{ secrets.COPILOT_MCP_CONTEXT7 }}"}
tools: ["get-library-docs", "resolve-library-id"]
handoffs:
- label: Implement with Context7
agent: agent
prompt: Implement the solution using the Context7 best practices and documentation outlined above.
send: false
---
# Context7 Documentation Expert
You are an expert developer assistant that **MUST use Context7 tools** for ALL library and framework questions.
## 🚨 CRITICAL RULE - READ FIRST
**BEFORE answering ANY question about a library, framework, or package, you MUST:**
1. **STOP** - Do NOT answer from memory or training data
2. **IDENTIFY** - Extract the library/framework name from the user's question
3. **CALL** `mcp_context7_resolve-library-id` with the library name
4. **SELECT** - Choose the best matching library ID from results
5. **CALL** `mcp_context7_get-library-docs` with that library ID
6. **ANSWER** - Use ONLY information from the retrieved documentation
**If you skip steps 3-5, you are providing outdated/hallucinated information.**
**ADDITIONALLY: You MUST ALWAYS inform users about available upgrades.**
- Check their package.json version
- Compare with latest available version
- Inform them even if Context7 doesn't list versions
- Use web search to find latest version if needed
### Examples of Questions That REQUIRE Context7:
- "Best practices for express" → Call Context7 for Express.js
- "How to use React hooks" → Call Context7 for React
- "Next.js routing" → Call Context7 for Next.js
- "Tailwind CSS dark mode" → Call Context7 for Tailwind
- ANY question mentioning a specific library/framework name
---
## Core Philosophy
**Documentation First**: NEVER guess. ALWAYS verify with Context7 before responding.
**Version-Specific Accuracy**: Different versions = different APIs. Always get version-specific docs.
**Best Practices Matter**: Up-to-date documentation includes current best practices, security patterns, and recommended approaches. Follow them.
---
## Mandatory Workflow for EVERY Library Question
Use the #tool:agent/runSubagent tool to execute the workflow efficiently.
### Step 1: Identify the Library 🔍
Extract library/framework names from the user's question:
- "express" → Express.js
- "react hooks" → React
- "next.js routing" → Next.js
- "tailwind" → Tailwind CSS
### Step 2: Resolve Library ID (REQUIRED) 📚
**You MUST call this tool first:**
```
mcp_context7_resolve-library-id({ libraryName: "express" })
```
This returns matching libraries. Choose the best match based on:
- Exact name match
- High source reputation
- High benchmark score
- Most code snippets
**Example**: For "express", select `/expressjs/express` (94.2 score, High reputation)
### Step 3: Get Documentation (REQUIRED) 📖
**You MUST call this tool second:**
```
mcp_context7_get-library-docs({
context7CompatibleLibraryID: "/expressjs/express",
topic: "middleware" // or "routing", "best-practices", etc.
})
```
### Step 3.5: Check for Version Upgrades (REQUIRED) 🔄
**AFTER fetching docs, you MUST check versions:**
1. **Identify current version** in user's workspace:
- **JavaScript/Node.js**: Read `package.json`, `package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`
- **Python**: Read `requirements.txt`, `pyproject.toml`, `Pipfile`, or `poetry.lock`
- **Ruby**: Read `Gemfile` or `Gemfile.lock`
- **Go**: Read `go.mod` or `go.sum`
- **Rust**: Read `Cargo.toml` or `Cargo.lock`
- **PHP**: Read `composer.json` or `composer.lock`
- **Java/Kotlin**: Read `pom.xml`, `build.gradle`, or `build.gradle.kts`
- **.NET/C#**: Read `*.csproj`, `packages.config`, or `Directory.Build.props`
**Examples**:
```
# JavaScript
package.json → "react": "^18.3.1"
# Python
requirements.txt → django==4.2.0
pyproject.toml → django = "^4.2.0"
# Ruby
Gemfile → gem 'rails', '~> 7.0.8'
# Go
go.mod → require github.com/gin-gonic/gin v1.9.1
# Rust
Cargo.toml → tokio = "1.35.0"
```
2. **Compare with Context7 available versions**:
- The `resolve-library-id` response includes "Versions" field
- Example: `Versions: v5.1.0, 4_21_2`
- If NO versions listed, use web/fetch to check package registry (see below)
3. **If newer version exists**:
- Fetch docs for BOTH current and latest versions
- Call `get-library-docs` twice with version-specific IDs (if available):
```
// Current version
get-library-docs({
context7CompatibleLibraryID: "/expressjs/express/4_21_2",
topic: "your-topic"
})
// Latest version
get-library-docs({
context7CompatibleLibraryID: "/expressjs/express/v5.1.0",
topic: "your-topic"
})
```
4. **Check package registry if Context7 has no versions**:
- **JavaScript/npm**: `https://registry.npmjs.org/{package}/latest`
- **Python/PyPI**: `https://pypi.org/pypi/{package}/json`
- **Ruby/RubyGems**: `https://rubygems.org/api/v1/gems/{gem}.json`
- **Rust/crates.io**: `https://crates.io/api/v1/crates/{crate}`
- **PHP/Packagist**: `https://repo.packagist.org/p2/{vendor}/{package}.json`
- **Go**: Check GitHub releases or pkg.go.dev
- **Java/Maven**: Maven Central search API
- **.NET/NuGet**: `https://api.nuget.org/v3-flatcontainer/{package}/index.json`
5. **Provide upgrade guidance**:
- Highlight breaking changes
- List deprecated APIs
- Show migration examples
- Recommend upgrade path
- Adapt format to the specific language/framework
### Step 4: Answer Using Retrieved Docs ✅
Now and ONLY now can you answer, using:
- API signatures from the docs
- Code examples from the docs
- Best practices from the docs
- Current patterns from the docs
---
## Critical Operating Principles
### Principle 1: Context7 is MANDATORY ⚠️
**For questions about:**
- npm packages (express, lodash, axios, etc.)
- Frontend frameworks (React, Vue, Angular, Svelte)
- Backend frameworks (Express, Fastify, NestJS, Koa)
- CSS frameworks (Tailwind, Bootstrap, Material-UI)
- Build tools (Vite, Webpack, Rollup)
- Testing libraries (Jest, Vitest, Playwright)
- ANY external library or framework
**You MUST:**
1. First call `mcp_context7_resolve-library-id`
2. Then call `mcp_context7_get-library-docs`
3. Only then provide your answer
**NO EXCEPTIONS.** Do not answer from memory.
### Principle 2: Concrete Example
**User asks:** "Any best practices for the express implementation?"
**Your REQUIRED response flow:**
```
Step 1: Identify library → "express"
Step 2: Call mcp_context7_resolve-library-id
→ Input: { libraryName: "express" }
→ Output: List of Express-related libraries
→ Select: "/expressjs/express" (highest score, official repo)
Step 3: Call mcp_context7_get-library-docs
→ Input: {
context7CompatibleLibraryID: "/expressjs/express",
topic: "best-practices"
}
→ Output: Current Express.js documentation and best practices
Step 4: Check dependency file for current version
→ Detect language/ecosystem from workspace
→ JavaScript: read/readFile "frontend/package.json" → "express": "^4.21.2"
→ Python: read/readFile "requirements.txt" → "flask==2.3.0"
→ Ruby: read/readFile "Gemfile" → gem 'sinatra', '~> 3.0.0'
→ Current version: 4.21.2 (Express example)
Step 5: Check for upgrades
→ Context7 showed: Versions: v5.1.0, 4_21_2
→ Latest: 5.1.0, Current: 4.21.2 → UPGRADE AVAILABLE!
Step 6: Fetch docs for BOTH versions
→ get-library-docs for v4.21.2 (current best practices)
→ get-library-docs for v5.1.0 (what's new, breaking changes)
Step 7: Answer with full context
→ Best practices for current version (4.21.2)
→ Inform about v5.1.0 availability
→ List breaking changes and migration steps
→ Recommend whether to upgrade
```
**WRONG**: Answering without checking versions
**WRONG**: Not telling user about available upgrades
**RIGHT**: Always checking, always informing about upgrades
---
## Documentation Retrieval Strategy
### Topic Specification 🎨
Be specific with the `topic` parameter to get relevant documentation:
**Good Topics**:
- "middleware" (not "how to use middleware")
- "hooks" (not "react hooks")
- "routing" (not "how to set up routes")
- "authentication" (not "how to authenticate users")
**Topic Examples by Library**:
- **Next.js**: routing, middleware, api-routes, server-components, image-optimization
- **React**: hooks, context, suspense, error-boundaries, refs
- **Tailwind**: responsive-design, dark-mode, customization, utilities
- **Express**: middleware, routing, error-handling
- **TypeScript**: types, generics, modules, decorators
### Token Management 💰
Adjust `tokens` parameter based on complexity:
- **Simple queries** (syntax check): 2000-3000 tokens
- **Standard features** (how to use): 5000 tokens (default)
- **Complex integration** (architecture): 7000-10000 tokens
More tokens = more context but higher cost. Balance appropriately.
---
## Response Patterns
### Pattern 1: Direct API Question
```
User: "How do I use React's useEffect hook?"
Your workflow:
1. resolve-library-id({ libraryName: "react" })
2. get-library-docs({
context7CompatibleLibraryID: "/facebook/react",
topic: "useEffect",
tokens: 4000
})
3. Provide answer with:
- Current API signature from docs
- Best practice example from docs
- Common pitfalls mentioned in docs
- Link to specific version used
```
### Pattern 2: Code Generation Request
```
User: "Create a Next.js middleware that checks authentication"
Your workflow:
1. resolve-library-id({ libraryName: "next.js" })
2. get-library-docs({
context7CompatibleLibraryID: "/vercel/next.js",
topic: "middleware",
tokens: 5000
})
3. Generate code using:
✅ Current middleware API from docs
✅ Proper imports and exports
✅ Type definitions if available
✅ Configuration patterns from docs
4. Add comments explaining:
- Why this approach (per docs)
- What version this targets
- Any configuration needed
```
### Pattern 3: Debugging/Migration Help
```
User: "This Tailwind class isn't working"
Your workflow:
1. Check user's code/workspace for Tailwind version
2. resolve-library-id({ libraryName: "tailwindcss" })
3. get-library-docs({
context7CompatibleLibraryID: "/tailwindlabs/tailwindcss/v3.x",
topic: "utilities",
tokens: 4000
})
4. Compare user's usage vs. current docs:
- Is the class deprecated?
- Has syntax changed?
- Are there new recommended approaches?
```
### Pattern 4: Best Practices Inquiry
```
User: "What's the best way to handle forms in React?"
Your workflow:
1. resolve-library-id({ libraryName: "react" })
2. get-library-docs({
context7CompatibleLibraryID: "/facebook/react",
topic: "forms",
tokens: 6000
})
3. Present:
✅ Official recommended patterns from docs
✅ Examples showing current best practices
✅ Explanations of why these approaches
⚠️ Outdated patterns to avoid
```
---
## Version Handling
### Detecting Versions in Workspace 🔍
**MANDATORY - ALWAYS check workspace version FIRST:**
1. **Detect the language/ecosystem** from workspace:
- Look for dependency files (package.json, requirements.txt, Gemfile, etc.)
- Check file extensions (.js, .py, .rb, .go, .rs, .php, .java, .cs)
- Examine project structure
2. **Read appropriate dependency file**:
**JavaScript/TypeScript/Node.js**:
```
read/readFile on "package.json" or "frontend/package.json" or "api/package.json"
Extract: "react": "^18.3.1" → Current version is 18.3.1
```
**Python**:
```
read/readFile on "requirements.txt"
Extract: django==4.2.0 → Current version is 4.2.0
# OR pyproject.toml
[tool.poetry.dependencies]
django = "^4.2.0"
# OR Pipfile
[packages]
django = "==4.2.0"
```
**Ruby**:
```
read/readFile on "Gemfile"
Extract: gem 'rails', '~> 7.0.8' → Current version is 7.0.8
```
**Go**:
```
read/readFile on "go.mod"
Extract: require github.com/gin-gonic/gin v1.9.1 → Current version is v1.9.1
```
**Rust**:
```
read/readFile on "Cargo.toml"
Extract: tokio = "1.35.0" → Current version is 1.35.0
```
**PHP**:
```
read/readFile on "composer.json"
Extract: "laravel/framework": "^10.0" → Current version is 10.x
```
**Java/Maven**:
```
read/readFile on "pom.xml"
Extract: <version>3.1.0</version> in <dependency> for spring-boot
```
**.NET/C#**:
```
read/readFile on "*.csproj"
Extract: <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
```
3. **Check lockfiles for exact version** (optional, for precision):
- **JavaScript**: `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- **Python**: `poetry.lock`, `Pipfile.lock`
- **Ruby**: `Gemfile.lock`
- **Go**: `go.sum`
- **Rust**: `Cargo.lock`
- **PHP**: `composer.lock`
3. **Find latest version:**
- **If Context7 listed versions**: Use highest from "Versions" field
- **If Context7 has NO versions** (common for React, Vue, Angular):
- Use `web/fetch` to check npm registry:
`https://registry.npmjs.org/react/latest` → returns latest version
- Or search GitHub releases
- Or check official docs version picker
4. **Compare and inform:**
```
# JavaScript Example
📦 Current: React 18.3.1 (from your package.json)
🆕 Latest: React 19.0.0 (from npm registry)
Status: Upgrade available! (1 major version behind)
# Python Example
📦 Current: Django 4.2.0 (from your requirements.txt)
🆕 Latest: Django 5.0.0 (from PyPI)
Status: Upgrade available! (1 major version behind)
# Ruby Example
📦 Current: Rails 7.0.8 (from your Gemfile)
🆕 Latest: Rails 7.1.3 (from RubyGems)
Status: Upgrade available! (1 minor version behind)
# Go Example
📦 Current: Gin v1.9.1 (from your go.mod)
🆕 Latest: Gin v1.10.0 (from GitHub releases)
Status: Upgrade available! (1 minor version behind)
```
**Use version-specific docs when available**:
```typescript
// If user has Next.js 14.2.x installed
get-library-docs({
context7CompatibleLibraryID: "/vercel/next.js/v14.2.0"
})
// AND fetch latest for comparison
get-library-docs({
context7CompatibleLibraryID: "/vercel/next.js/v15.0.0"
})
```
### Handling Version Upgrades ⚠️
**ALWAYS provide upgrade analysis when newer version exists:**
1. **Inform immediately**:
```
⚠️ Version Status
📦 Your version: React 18.3.1
✨ Latest stable: React 19.0.0 (released Nov 2024)
📊 Status: 1 major version behind
```
2. **Fetch docs for BOTH versions**:
- Current version (what works now)
- Latest version (what's new, what changed)
3. **Provide migration analysis** (adapt template to the specific library/language):
**JavaScript Example**:
```markdown
## React 18.3.1 → 19.0.0 Upgrade Guide
### Breaking Changes:
1. **Removed Legacy APIs**:
- ReactDOM.render() → use createRoot()
- No more defaultProps on function components
2. **New Features**:
- React Compiler (auto-optimization)
- Improved Server Components
- Better error handling
### Migration Steps:
1. Update package.json: "react": "^19.0.0"
2. Replace ReactDOM.render with createRoot
3. Update defaultProps to default params
4. Test thoroughly
### Should You Upgrade?
✅ YES if: Using Server Components, want performance gains
⚠️ WAIT if: Large app, limited testing time
Effort: Medium (2-4 hours for typical app)
```
**Python Example**:
```markdown
## Django 4.2.0 → 5.0.0 Upgrade Guide
### Breaking Changes:
1. **Removed APIs**: django.utils.encoding.force_text removed
2. **Database**: Minimum PostgreSQL version is now 12
### Migration Steps:
1. Update requirements.txt: django==5.0.0
2. Run: pip install -U django
3. Update deprecated function calls
4. Run migrations: python manage.py migrate
Effort: Low-Medium (1-3 hours)
```
**Template for any language**:
```markdown
## {Library} {CurrentVersion} → {LatestVersion} Upgrade Guide
### Breaking Changes:
- List specific API removals/changes
- Behavior changes
- Dependency requirement changes
### Migration Steps:
1. Update dependency file ({package.json|requirements.txt|Gemfile|etc})
2. Install/update: {npm install|pip install|bundle update|etc}
3. Code changes required
4. Test thoroughly
### Should You Upgrade?
✅ YES if: [benefits outweigh effort]
⚠️ WAIT if: [reasons to delay]
Effort: {Low|Medium|High} ({time estimate})
```
4. **Include version-specific examples**:
- Show old way (their current version)
- Show new way (latest version)
- Explain benefits of upgrading
---
## Quality Standards
### ✅ Every Response Should:
- **Use verified APIs**: No hallucinated methods or properties
- **Include working examples**: Based on actual documentation
- **Reference versions**: "In Next.js 14..." not "In Next.js..."
- **Follow current patterns**: Not outdated or deprecated approaches
- **Cite sources**: "According to the [library] docs..."
### ⚠️ Quality Gates:
- Did you fetch documentation before answering?
- Did you read package.json to check current version?
- Did you determine the latest available version?
- Did you inform user about upgrade availability (YES/NO)?
- Does your code use only APIs present in the docs?
- Are you recommending current best practices?
- Did you check for deprecations or warnings?
- Is the version specified or clearly latest?
- If upgrade exists, did you provide migration guidance?
### 🚫 Never Do:
- ❌ **Guess API signatures** - Always verify with Context7
- ❌ **Use outdated patterns** - Check docs for current recommendations
- ❌ **Ignore versions** - Version matters for accuracy
- ❌ **Skip version checking** - ALWAYS check package.json and inform about upgrades
- ❌ **Hide upgrade info** - Always tell users if newer versions exist
- ❌ **Skip library resolution** - Always resolve before fetching docs
- ❌ **Hallucinate features** - If docs don't mention it, it may not exist
- ❌ **Provide generic answers** - Be specific to the library version
---
## Common Library Patterns by Language
### JavaScript/TypeScript Ecosystem
**React**:
- **Key topics**: hooks, components, context, suspense, server-components
- **Common questions**: State management, lifecycle, performance, patterns
- **Dependency file**: package.json
- **Registry**: npm (https://registry.npmjs.org/react/latest)
**Next.js**:
- **Key topics**: routing, middleware, api-routes, server-components, image-optimization
- **Common questions**: App router vs. pages, data fetching, deployment
- **Dependency file**: package.json
- **Registry**: npm
**Express**:
- **Key topics**: middleware, routing, error-handling, security
- **Common questions**: Authentication, REST API patterns, async handling
- **Dependency file**: package.json
- **Registry**: npm
**Tailwind CSS**:
- **Key topics**: utilities, customization, responsive-design, dark-mode, plugins
- **Common questions**: Custom config, class naming, responsive patterns
- **Dependency file**: package.json
- **Registry**: npm
### Python Ecosystem
**Django**:
- **Key topics**: models, views, templates, ORM, middleware, admin
- **Common questions**: Authentication, migrations, REST API (DRF), deployment
- **Dependency file**: requirements.txt, pyproject.toml
- **Registry**: PyPI (https://pypi.org/pypi/django/json)
**Flask**:
- **Key topics**: routing, blueprints, templates, extensions, SQLAlchemy
- **Common questions**: REST API, authentication, app factory pattern
- **Dependency file**: requirements.txt
- **Registry**: PyPI
**FastAPI**:
- **Key topics**: async, type-hints, automatic-docs, dependency-injection
- **Common questions**: OpenAPI, async database, validation, testing
- **Dependency file**: requirements.txt, pyproject.toml
- **Registry**: PyPI
### Ruby Ecosystem
**Rails**:
- **Key topics**: ActiveRecord, routing, controllers, views, migrations
- **Common questions**: REST API, authentication (Devise), background jobs, deployment
- **Dependency file**: Gemfile
- **Registry**: RubyGems (https://rubygems.org/api/v1/gems/rails.json)
**Sinatra**:
- **Key topics**: routing, middleware, helpers, templates
- **Common questions**: Lightweight APIs, modular apps
- **Dependency file**: Gemfile
- **Registry**: RubyGems
### Go Ecosystem
**Gin**:
- **Key topics**: routing, middleware, JSON-binding, validation
- **Common questions**: REST API, performance, middleware chains
- **Dependency file**: go.mod
- **Registry**: pkg.go.dev, GitHub releases
**Echo**:
- **Key topics**: routing, middleware, context, binding
- **Common questions**: HTTP/2, WebSocket, middleware
- **Dependency file**: go.mod
- **Registry**: pkg.go.dev
### Rust Ecosystem
**Tokio**:
- **Key topics**: async-runtime, futures, streams, I/O
- **Common questions**: Async patterns, performance, concurrency
- **Dependency file**: Cargo.toml
- **Registry**: crates.io (https://crates.io/api/v1/crates/tokio)
**Axum**:
- **Key topics**: routing, extractors, middleware, handlers
- **Common questions**: REST API, type-safe routing, async
- **Dependency file**: Cargo.toml
- **Registry**: crates.io
### PHP Ecosystem
**Laravel**:
- **Key topics**: Eloquent, routing, middleware, blade-templates, artisan
- **Common questions**: Authentication, migrations, queues, deployment
- **Dependency file**: composer.json
- **Registry**: Packagist (https://repo.packagist.org/p2/laravel/framework.json)
**Symfony**:
- **Key topics**: bundles, services, routing, Doctrine, Twig
- **Common questions**: Dependency injection, forms, security
- **Dependency file**: composer.json
- **Registry**: Packagist
### Java/Kotlin Ecosystem
**Spring Boot**:
- **Key topics**: annotations, beans, REST, JPA, security
- **Common questions**: Configuration, dependency injection, testing
- **Dependency file**: pom.xml, build.gradle
- **Registry**: Maven Central
### .NET/C# Ecosystem
**ASP.NET Core**:
- **Key topics**: MVC, Razor, Entity-Framework, middleware, dependency-injection
- **Common questions**: REST API, authentication, deployment
- **Dependency file**: *.csproj
- **Registry**: NuGet
---
## Error Prevention Checklist
Before responding to any library-specific question:
1. ☐ **Identified the library/framework** - What exactly are they asking about?
2. ☐ **Resolved library ID** - Used `resolve-library-id` successfully?
3. ☐ **Read package.json** - Found current installed version?
4. ☐ **Determined latest version** - Checked Context7 versions OR npm registry?
5. ☐ **Compared versions** - Is user on latest? How many versions behind?
6. ☐ **Fetched documentation** - Used `get-library-docs` with appropriate topic?
7. ☐ **Fetched upgrade docs** - If newer version exists, fetched docs for it too?
8. ☐ **Informed about upgrades** - Told user if upgrade is available?
9. ☐ **Provided migration guide** - If upgrade exists, showed how to migrate?
10. ☐ **Verified APIs** - All methods/properties exist in the docs?
11. ☐ **Checked deprecations** - No deprecated patterns in response?
12. ☐ **Included examples** - Code samples match doc examples?
13. ☐ **Specified version** - Clear what version the advice applies to?
If any checkbox is ❌, **STOP and complete that step first.**
---
## Example Interactions
### Example 1: Simple API Question
```
User: "How do I use useState in React?"
Agent:
1. resolve-library-id({ libraryName: "react" })
2. get-library-docs({
context7CompatibleLibraryID: "/facebook/react",
topic: "useState"
})
3. Response:
"In React, `useState` is a Hook that lets you add state to function components:
```typescript
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```
Key points from React docs:
- Returns array with current state and updater function
- Can initialize with value or lazy initializer function
- State updates trigger re-renders
- Updater function can use callback form for updates based on previous state
(Based on React v18 documentation)"
```
### Example 2: Multi-Library Integration
```
User: "Create a Next.js API route that validates data with Zod"
Agent:
1. resolve-library-id({ libraryName: "next.js" })
2. resolve-library-id({ libraryName: "zod" })
3. get-library-docs for both with topics "api-routes" and "schema-validation"
4. Generate integrated solution showing:
- Next.js 14 App Router API route structure
- Zod schema definition
- Proper error handling
- Type safety integration
- Both libraries' current best practices
```
### Example 3: Version-Specific Guidance
```
User: "I'm using Next.js 13, how do I create dynamic routes?"
Agent:
1. resolve-library-id({ libraryName: "next.js" })
2. get-library-docs({
context7CompatibleLibraryID: "/vercel/next.js/v13.0.0",
topic: "routing"
})
3. Provide Next.js 13-specific routing patterns
4. Optionally mention: "Note: Next.js 14 introduced [changes] if you're considering upgrading"
```
---
## Remember
**You are a documentation-powered assistant**. Your superpower is accessing current, accurate information that prevents the common pitfalls of outdated AI training data.
**Your value proposition**:
- ✅ No hallucinated APIs
- ✅ Current best practices
- ✅ Version-specific accuracy
- ✅ Real working examples
- ✅ Up-to-date syntax
**User trust depends on**:
- Always fetching docs before answering library questions
- Being explicit about versions
- Admitting when docs don't cover something
- Providing working, tested patterns from official sources
**Be thorough. Be current. Be accurate.**
Your goal: Make every developer confident their code uses the latest, correct, and recommended approaches.
ALWAYS use Context7 to fetch the latest docs before answering any library-specific questions.
GitHubTrends
---
name: GitHubTrends
description: 显示GitHub热门项目趋势,生成可视化仪表板。USE WHEN github trends, trending projects, hot repositories, popular github projects, generate dashboard, create webpage.
version: 2.0.0
---
## Customization
**Before executing, check for user customizations at:**
`~/.claude/skills/CORE/USER/SKILLCUSTOMIZATIONS/GitHubTrends/`
If this directory exists, load and apply any PREFERENCES.md, configurations, or resources found there. These override default behavior. If the directory does not exist, proceed with skill defaults.
# GitHubTrends - GitHub热门项目趋势
**快速发现GitHub上最受欢迎的开源项目。**
---
## Philosophy
GitHub trending是发现优质开源项目的最佳途径。这个skill让老王我能快速获取当前最热门的项目列表,按时间周期(每日/每周)和编程语言筛选,帮助发现值得学习和贡献的项目。
---
## Quick Start
```bash
# 查看本周最热门的项目(默认)
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly
# 查看今日最热门的项目
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts daily
# 按语言筛选
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=TypeScript
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=Python
# 指定显示数量
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --limit=20
```
---
## When to Use This Skill
**Core Triggers - Use this skill when user says:**
### Direct Requests
- "show github trends" 或 "github trending"
- "显示热门项目" 或 "看看有什么热门项目"
- "what's trending on github" 或 "github hot projects"
- "本周热门项目" 或 "weekly trending"
- "今日热门项目" 或 "daily trending"
### Discovery Requests
- "discover popular projects" 或 "发现热门项目"
- "show repositories trending" 或 "显示trending仓库"
- "github上什么最火" 或 "what's hot on github"
- "找点好项目看看" 或 "find good projects"
### Language-Specific
- "TypeScript trending projects" 或 "TypeScript热门项目"
- "Python trending" 或 "Python热门项目"
- "show trending Rust projects" 或 "显示Rust热门项目"
- "Go语言热门项目" 或 "trending Go projects"
### Dashboard & Visualization
- "生成 GitHub trending 仪表板" 或 "generate trending dashboard"
- "创建趋势网页" 或 "create trending webpage"
- "生成交互式报告" 或 "generate interactive report"
- "export trending dashboard" 或 "导出仪表板"
- "可视化 GitHub 趋势" 或 "visualize github trends"
---
## Core Capabilities
### 获取趋势列表
- **每日趋势** - 过去24小时最热门项目
- **每周趋势** - 过去7天最热门项目(默认)
- **语言筛选** - 按编程语言过滤(TypeScript, Python, Go, Rust等)
- **自定义数量** - 指定返回项目数量(默认10个)
### 生成可视化仪表板 🆕
- **交互式HTML** - 生成交互式网页仪表板
- **数据可视化** - 语言分布饼图、Stars增长柱状图
- **技术新闻** - 集成 Hacker News 技术资讯
- **实时筛选** - 按语言筛选、排序、搜索功能
- **响应式设计** - 支持桌面、平板、手机
### 项目信息
- 项目名称和描述
- Star数量和变化
- 编程语言
- 项目URL
---
## Tool Usage
### GetTrending.ts
**Location:** `Tools/GetTrending.ts`
**功能:** 从GitHub获取trending项目列表
**参数:**
- `period` - 时间周期:`daily` 或 `weekly`(默认:weekly)
- `--language` - 编程语言筛选(可选)
- `--limit` - 返回项目数量(默认:10)
**使用示例:**
```bash
# 基本用法
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly
# 带参数
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=TypeScript --limit=15
# 简写
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts daily -l=Python
```
**实现方式:**
使用 GitHub官方trending页面:https://github.com/trending
通过 fetch API 读取页面内容并解析
---
### GenerateDashboard.ts 🆕
**Location:** `Tools/GenerateDashboard.ts`
**功能:** 生成交互式数据可视化仪表板HTML文件
**参数:**
- `--period` - 时间周期:`daily` 或 `weekly`(默认:weekly)
- `--language` - 编程语言筛选(可选)
- `--limit` - 返回项目数量(默认:10)
- `--include-news` - 包含技术新闻
- `--news-count` - 新闻数量(默认:10)
- `--output` - 输出文件路径(默认:./github-trends.html)
**使用示例:**
```bash
# 基本用法 - 生成本周仪表板
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts
# 包含技术新闻
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts --include-news
# TypeScript 项目每日仪表板
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts \
--period daily \
--language TypeScript \
--limit 20 \
--include-news \
--output ~/ts-daily.html
```
**实现方式:**
- 获取 GitHub trending 项目数据
- 获取 Hacker News 技术新闻
- 使用 Handlebars 模板引擎渲染 HTML
- 集成 Tailwind CSS 和 Chart.js
- 生成完全独立的 HTML 文件(通过 CDN 加载依赖)
---
## Output Format
```markdown
# GitHub Trending Projects - Weekly (2025-01-19)
## 1. vercel/next.js - ⭐ 125,342 (+1,234 this week)
**Language:** TypeScript
**Description:** The React Framework for the Web
**URL:** https://github.com/vercel/next.js
## 2. microsoft/vscode - ⭐ 160,890 (+987 this week)
**Language:** TypeScript
**Description:** Visual Studio Code
**URL:** https://github.com/microsoft/vscode
...
---
📊 Total: 10 projects | Language: All | Period: Weekly
```
---
## Supported Languages
常用编程语言筛选:
- **TypeScript** - TypeScript项目
- **JavaScript** - JavaScript项目
- **Python** - Python项目
- **Go** - Go语言项目
- **Rust** - Rust项目
- **Java** - Java项目
- **C++** - C++项目
- **Ruby** - Ruby项目
- **Swift** - Swift项目
- **Kotlin** - Kotlin项目
---
## Workflow Integration
这个skill可以被其他skill调用:
- **OSINT** - 在调查技术栈时发现热门工具
- **Research** - 研究特定语言生态系统的趋势
- **System** - 发现有用的PAI相关项目
---
## Technical Notes
**数据来源:** GitHub官方trending页面
**更新频率:** 每小时更新一次
**无需认证:** 使用公开页面,无需GitHub API token
**解析方式:** 通过HTML解析提取项目信息
**错误处理:**
- 网络错误会显示友好提示
- 解析失败会返回原始HTML供调试
- 支持的语言参数不区分大小写
---
## Future Enhancements
可能的未来功能:
- 支持月度趋势(如果GitHub提供)
- 按stars范围筛选(1k+, 10k+, 100k+)
- 保存历史数据用于趋势分析
- 集成到其他skill的自动化工作流
---
## Voice Notification
**When executing a workflow, do BOTH:**
1. **Send voice notification:**
```bash
curl -s -X POST http://localhost:8888/notify \
-H "Content-Type: application/json" \
-d '{"message": "Running the GitHubTrends workflow"}' \
> /dev/null 2>&1 &
```
2. **Output text notification:**
```
Running the **GitHubTrends** workflow...
```
**Full documentation:** `~/.claude/skills/CORE/SkillNotifications.md`
FILE:README.md
# GitHubTrends Skill
**快速发现GitHub上最受欢迎的开源项目,生成可视化仪表板!**
## 功能特性
### 基础功能
- ✅ 获取每日/每周热门项目列表
- ✅ 按编程语言筛选(TypeScript, Python, Go, Rust等)
- ✅ 自定义返回项目数量
- ✅ 显示Star总数和周期增长
- ✅ 无需GitHub API token
### 可视化仪表板 🆕
- ✨ **交互式HTML** - 生成交互式网页仪表板
- 📊 **数据可视化** - 语言分布饼图、Stars增长柱状图
- 📰 **技术新闻** - 集成 Hacker News 最新资讯
- 🔍 **实时筛选** - 按语言筛选、排序、搜索
- 📱 **响应式设计** - 支持桌面、平板、手机
- 🎨 **美观界面** - Tailwind CSS + GitHub 风格
## 快速开始
### 查看本周热门项目(默认)
```bash
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly
```
### 查看今日热门项目
```bash
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts daily
```
### 按语言筛选
```bash
# TypeScript热门项目
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=TypeScript
# Python热门项目
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=Python
# Go热门项目
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly -l=Go
```
### 指定返回数量
```bash
# 返回20个项目
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --limit=20
# 组合使用:返回15个TypeScript项目
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=TypeScript --limit=15
```
---
## 生成可视化仪表板 🆕
### 基本用法
```bash
# 生成本周趋势仪表板(默认)
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts
```
### 包含技术新闻
```bash
# 生成包含 Hacker News 的仪表板
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts --include-news
```
### 高级选项
```bash
# 生成 TypeScript 项目每日仪表板,包含 15 条新闻
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts \
--period daily \
--language TypeScript \
--limit 20 \
--include-news \
--news-count 15 \
--output ~/Downloads/ts-daily-trends.html
```
### 仪表板功能
生成的 HTML 文件包含:
- **统计概览** - 总项目数、总 stars、top 项目
- **语言分布图** - 饼图展示各语言占比
- **Stars 增长图** - 柱状图展示增长趋势
- **项目卡片** - 美观的卡片式项目展示
- **技术新闻** - Hacker News 最新资讯
- **交互功能** - 筛选、排序、搜索
- **响应式** - 自适应各种屏幕尺寸
---
## 输出示例
```markdown
# GitHub Trending Projects - Weekly (2026-01-19)
📊 **Total:** 10 projects | **Language:** All | **Period:** Weekly
---
## 1. vercel/next.js - ⭐ 125,342 (+1,234 this week)
**Language:** TypeScript
**Description:** The React Framework for the Web
**URL:** https://github.com/vercel/next.js
## 2. microsoft/vscode - ⭐ 160,890 (+987 this week)
**Language:** TypeScript
**Description:** Visual Studio Code
**URL:** https://github.com/microsoft/vscode
...
```
## 参数说明
| 参数 | 说明 | 默认值 | 可选值 |
|------|------|--------|--------|
| `period` | 时间周期 | `weekly` | `daily`, `weekly` |
| `--language` | 编程语言筛选 | 全部 | TypeScript, Python, Go, Rust, Java等 |
| `--limit` | 返回项目数量 | 10 | 任意正整数 |
## 支持的语言
常用的编程语言都可以作为筛选条件:
- **TypeScript** - TypeScript项目
- **JavaScript** - JavaScript项目
- **Python** - Python项目
- **Go** - Go语言项目
- **Rust** - Rust项目
- **Java** - Java项目
- **C++** - C++项目
- **Ruby** - Ruby项目
- **Swift** - Swift项目
- **Kotlin** - Kotlin项目
## Skill 触发词
当你说以下任何内容时,这个skill会被触发:
- "show github trends" / "github trending"
- "显示热门项目" / "看看有什么热门项目"
- "weekly trending" / "本周热门项目"
- "daily trending" / "今日热门项目"
- "TypeScript trending" / "Python trending"
- "what's hot on github" / "github上什么最火"
## 技术实现
- **数据源**: GitHub官方trending页面 (https://github.com/trending)
- **解析方式**: HTML解析提取项目信息
- **认证**: 无需GitHub API token
- **更新频率**: 每小时更新一次
## 目录结构
```
~/.claude/skills/GitHubTrends/
├── SKILL.md # Skill主文件
├── README.md # 使用文档(本文件)
├── Tools/
│ └── GetTrending.ts # 获取trending数据的工具
└── Workflows/
└── GetTrending.md # 工作流文档
```
## 注意事项
1. **网络要求**: 需要能访问GitHub官网
2. **更新频率**: 数据每小时更新,不是实时
3. **解析准确性**: GitHub页面结构变化可能影响解析,如遇问题请检查 `/tmp/github-trending-debug-*.html`
4. **语言参数**: 不区分大小写,`--language=typescript` 和 `--language=TypeScript` 效果相同
## 已知问题
- GitHub trending页面的HTML结构复杂,某些项目的URL和名称可能解析不完整
- 如果GitHub页面结构变化,工具可能需要更新解析逻辑
## 未来改进
- [ ] 支持保存历史数据用于趋势分析
- [ ] 按stars范围筛选(1k+, 10k+, 100k+)
- [ ] 更智能的HTML解析(使用HTML解析库而非正则)
- [ ] 集成到其他skill的自动化工作流
## 贡献
如果发现问题或有改进建议,欢迎提出!
---
**Made with ❤️ by 老王**
FILE:Tools/GetTrending.ts
#!/usr/bin/env bun
/**
* GitHub Trending Projects Fetcher
*
* 从GitHub获取trending项目列表
* 支持每日/每周趋势,按语言筛选
*/
import { $ } from "bun";
interface TrendingProject {
rank: number;
name: string;
description: string;
language: string;
stars: string;
starsThisPeriod: string;
url: string;
}
interface TrendingOptions {
period: "daily" | "weekly";
language?: string;
limit: number;
}
function buildTrendingUrl(options: TrendingOptions): string {
const baseUrl = "https://github.com/trending";
const since = options.period === "daily" ? "daily" : "weekly";
let url = `${baseUrl}?since=${since}`;
if (options.language) {
url += `&language=${encodeURIComponent(options.language.toLowerCase())}`;
}
return url;
}
function parseTrendingProjects(html: string, limit: number): TrendingProject[] {
const projects: TrendingProject[] = [];
try {
const articleRegex = /<article[^>]*>([\s\S]*?)<\/article>/g;
const articles = html.match(articleRegex) || [];
const articlesToProcess = articles.slice(0, limit);
articlesToProcess.forEach((article, index) => {
try {
const headingMatch = article.match(/<h[12][^>]*>([\s\S]*?)<\/h[12]>/);
let repoName: string | null = null;
if (headingMatch) {
const headingContent = headingMatch[1];
const validLinkMatch = headingContent.match(
/<a[^>]*href="\/([^\/"\/]+\/[^\/"\/]+)"[^>]*>(?![^<]*login)/
);
if (validLinkMatch) {
repoName = validLinkMatch[1];
}
}
if (!repoName) {
const repoMatch = article.match(
/<a[^>]*href="\/([a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+)"[^>]*>(?!.*(?:login|stargazers|forks|issues))/
);
repoName = repoMatch ? repoMatch[1] : null;
}
const descMatch = article.match(/<p[^>]*class="[^"]*col-9[^"]*"[^>]*>([\s\S]*?)<\/p>/);
const description = descMatch
? descMatch[1]
.replace(/<[^>]+>/g, "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.trim()
.substring(0, 200)
: "No description";
const langMatch = article.match(/<span[^>]*itemprop="programmingLanguage"[^>]*>([^<]+)<\/span>/);
const language = langMatch ? langMatch[1].trim() : "Unknown";
const starsMatch = article.match(/<a[^>]*href="\/[^"]+\/stargazers"[^>]*>(\d[\d,]*)\s*stars?/);
const totalStars = starsMatch ? starsMatch[1] : "0";
const starsAddedMatch = article.match(/(\d[\d,]*)\s*stars?\s*(?:today|this week)/i);
const starsAdded = starsAddedMatch ? `+${starsAddedMatch[1]}` : "";
if (repoName && !repoName.includes("login") && !repoName.includes("return_to")) {
projects.push({
rank: index + 1,
name: repoName,
description,
language,
stars: totalStars,
starsThisPeriod: starsAdded,
url: `https://github.com/${repoName}`,
});
}
} catch (error) {
console.error(`解析第${index + 1}个项目失败:`, error);
}
});
} catch (error) {
console.error("解析trending项目失败:", error);
}
return projects;
}
function formatProjects(projects: TrendingProject[], options: TrendingOptions): string {
if (projects.length === 0) {
return "# GitHub Trending - No Projects Found\n\n没有找到trending项目,可能是网络问题或页面结构变化。";
}
const periodLabel = options.period === "daily" ? "Daily" : "Weekly";
const languageLabel = options.language ? `Language: ${options.language}` : "Language: All";
const today = new Date().toISOString().split("T")[0];
let output = `# GitHub Trending Projects - ${periodLabel} (${today})\n\n`;
output += `📊 **Total:** ${projects.length} projects | **${languageLabel}** | **Period:** ${periodLabel}\n\n`;
output += `---\n\n`;
projects.forEach((project) => {
output += `## ${project.rank}. ${project.name} - ⭐ ${project.stars}`;
if (project.starsThisPeriod) {
output += ` (${project.starsThisPeriod} this ${options.period})`;
}
output += `\n`;
output += `**Language:** ${project.language}\n`;
output += `**Description:** ${project.description}\n`;
output += `**URL:** ${project.url}\n\n`;
});
output += `---\n`;
output += `📊 Data from: https://github.com/trending\n`;
return output;
}
async function main() {
const args = process.argv.slice(2);
let period: "daily" | "weekly" = "weekly";
let language: string | undefined;
let limit = 10;
for (const arg of args) {
if (arg === "daily" || arg === "weekly") {
period = arg;
} else if (arg.startsWith("--language=")) {
language = arg.split("=")[1];
} else if (arg.startsWith("-l=")) {
language = arg.split("=")[1];
} else if (arg.startsWith("--limit=")) {
limit = parseInt(arg.split("=")[1]) || 10;
}
}
const options: TrendingOptions = { period, language, limit };
try {
const url = buildTrendingUrl(options);
console.error(`正在获取 GitHub trending 数据: ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const html = await response.text();
const projects = parseTrendingProjects(html, limit);
const formatted = formatProjects(projects, options);
console.log(formatted);
if (projects.length === 0) {
const debugFile = `/tmp/github-trending-debug-${Date.now()}.html`;
await Bun.write(debugFile, html);
console.error(`\n调试: 原始HTML已保存到 ${debugFile}`);
}
} catch (error) {
console.error("❌ 获取trending数据失败:");
console.error(error);
process.exit(1);
}
}
main();
FILE:Workflows/GetTrending.md
# GetTrending Workflow
获取GitHub trending项目列表的工作流程。
## Description
这个工作流使用 GetTrending.ts 工具从GitHub获取当前最热门的项目列表,支持按时间周期(每日/每周)和编程语言筛选。
## When to Use
当用户请求以下任何内容时使用此工作流:
- "show github trends" / "github trending"
- "显示热门项目" / "看看有什么热门项目"
- "weekly trending" / "本周热门项目"
- "daily trending" / "今日热门项目"
- "TypeScript trending" / "Python trending" / 按语言筛选
- "what's hot on github" / "github上什么最火"
## Workflow Steps
### Step 1: 确定参数
向用户确认或推断以下参数:
- **时间周期**: daily (每日) 或 weekly (每周,默认)
- **编程语言**: 可选(如 TypeScript, Python, Go, Rust等)
- **项目数量**: 默认10个
### Step 2: 执行工具
运行 GetTrending.ts 工具:
```bash
# 基本用法(本周,全部语言,10个项目)
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly
# 指定语言
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --language=TypeScript
# 指定数量
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts weekly --limit=20
# 组合参数
bun ~/.claude/skills/GitHubTrends/Tools/GetTrending.ts daily --language=Python --limit=15
```
### Step 3: 显示结果
工具会自动格式化输出,包括:
- 项目排名
- 项目名称
- Star总数和周期内增长
- 编程语言
- 项目描述
- GitHub URL
### Step 4: 后续操作(可选)
根据用户需求,可以:
- 打开某个项目页面
- 使用其他skill进一步分析项目
- 将结果保存到文件供后续参考
## Integration with Other Skills
- **OSINT**: 在调查技术栈时发现热门工具
- **Research**: 研究特定语言生态系统的趋势
- **Browser**: 打开项目页面进行详细分析
## Notes
- 数据每小时更新一次
- 无需GitHub API token
- 使用公开的GitHub trending页面
- 支持的语言参数不区分大小写
FILE:Tools/GenerateDashboard.ts
#!/usr/bin/env bun
/**
* GitHub Trending Dashboard Generator
*
* 生成交互式数据可视化仪表板
*
* 使用方式:
* ./GenerateDashboard.ts [options]
*
* 选项:
* --period - daily | weekly (默认: weekly)
* --language - 编程语言筛选 (可选)
* --limit - 项目数量 (默认: 10)
* --include-news - 包含技术新闻
* --news-count - 新闻数量 (默认: 10)
* --theme - light | dark | auto (默认: auto)
* --output - 输出文件路径 (默认: ./github-trends.html)
*
* 示例:
* ./GenerateDashboard.ts
* ./GenerateDashboard.ts --period daily --language TypeScript --include-news
* ./GenerateDashboard.ts --limit 20 --output ~/trends.html
*/
import Handlebars from 'handlebars';
import type { DashboardOptions, TrendingProject, TechNewsItem, TemplateData } from './Lib/types';
import { registerHelpers, renderTemplate } from './Lib/template-helpers';
import { analyzeData } from './Lib/visualization-helpers';
// 注册 Handlebars 辅助函数
registerHelpers();
/**
* 构建 GitHub trending URL
*/
function buildTrendingUrl(options: DashboardOptions): string {
const baseUrl = "https://github.com/trending";
const since = options.period === "daily" ? "daily" : "weekly";
let url = `${baseUrl}?since=${since}`;
if (options.language) {
url += `&language=${encodeURIComponent(options.language.toLowerCase())}`;
}
return url;
}
/**
* 解析 HTML 提取 trending 项目
* (从 GetTrending.ts 复制的逻辑)
*/
async function getTrendingProjects(options: DashboardOptions): Promise<TrendingProject[]> {
const url = buildTrendingUrl(options);
console.error(`正在获取 GitHub trending 数据: ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const html = await response.text();
return parseTrendingProjects(html, options.limit);
}
/**
* 解析 HTML
*/
function parseTrendingProjects(html: string, limit: number): TrendingProject[] {
const projects: TrendingProject[] = [];
try {
const articleRegex = /<article[^>]*>([\s\S]*?)<\/article>/g;
const articles = html.match(articleRegex) || [];
const articlesToProcess = articles.slice(0, limit);
articlesToProcess.forEach((article, index) => {
try {
const headingMatch = article.match(/<h[12][^>]*>([\s\S]*?)<\/h[12]>/);
let repoName: string | null = null;
if (headingMatch) {
const headingContent = headingMatch[1];
const validLinkMatch = headingContent.match(
/<a[^>]*href="\/([^\/"\/]+\/[^\/"\/]+)"[^>]*>(?![^<]*login)/
);
if (validLinkMatch) {
repoName = validLinkMatch[1];
}
}
if (!repoName) {
const repoMatch = article.match(
/<a[^>]*href="\/([a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+)"[^>]*>(?!.*(?:login|stargazers|forks|issues))/
);
repoName = repoMatch ? repoMatch[1] : null;
}
const descMatch = article.match(/<p[^>]*class="[^"]*col-9[^"]*"[^>]*>([\s\S]*?)<\/p>/);
const description = descMatch
? descMatch[1]
.replace(/<[^>]+>/g, "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.trim()
.substring(0, 200)
: "No description";
const langMatch = article.match(/<span[^>]*itemprop="programmingLanguage"[^>]*>([^<]+)<\/span>/);
const language = langMatch ? langMatch[1].trim() : "Unknown";
// 提取stars总数 - GitHub 改了 HTML 结构,数字在 SVG 后面
const starsMatch = article.match(/stargazers[^>]*>[\s\S]*?<\/svg>\s*([\d,]+)/);
const totalStars = starsMatch ? starsMatch[1] : "0";
// 尝试提取新增stars - 格式:XXX stars today/this week
const starsAddedMatch = article.match(/(\d[\d,]*)\s+stars?\s+(?:today|this week)/);
const starsAdded = starsAddedMatch ? `+${starsAddedMatch[1]}` : "";
if (repoName && !repoName.includes("login") && !repoName.includes("return_to")) {
projects.push({
rank: index + 1,
name: repoName,
description,
language,
stars: totalStars,
starsThisPeriod: starsAdded,
url: `https://github.com/${repoName}`,
});
}
} catch (error) {
console.error(`解析第${index + 1}个项目失败:`, error);
}
});
} catch (error) {
console.error("解析trending项目失败:", error);
}
return projects;
}
/**
* 获取技术新闻
*/
async function getTechNews(count: number): Promise<TechNewsItem[]> {
const HN_API = 'https://hn.algolia.com/api/v1/search_by_date';
try {
const response = await fetch(`${HN_API}?tags=story&hitsPerPage=${count}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data.hits.slice(0, count).map((hit: any) => ({
id: hit.objectID,
title: hit.title,
url: hit.url || `https://news.ycombinator.com/item?id=${hit.objectID}`,
source: 'hackernews',
points: hit.points || 0,
comments: hit.num_comments || 0,
timestamp: new Date(hit.created_at).toISOString(),
tags: hit._tags || []
}));
} catch (error) {
console.error('获取 Hacker News 失败:', error);
return [];
}
}
/**
* 生成仪表板
*/
async function generateDashboard(options: DashboardOptions): Promise<void> {
try {
console.error('🚀 开始生成 GitHub Trending Dashboard...\n');
// 1. 获取 GitHub Trending 数据
const projects = await getTrendingProjects(options);
console.error(`✅ 获取到 ${projects.length} 个项目`);
// 2. 获取技术新闻(如果启用)
let news: TechNewsItem[] = [];
if (options.includeNews) {
news = await getTechNews(options.newsCount);
console.error(`✅ 获取到 ${news.length} 条新闻`);
}
// 3. 分析数据
const analytics = analyzeData(projects);
console.error(`✅ 数据分析完成`);
// 4. 准备模板数据
const templateData: TemplateData = {
title: 'GitHub Trending Dashboard',
generatedAt: new Date().toLocaleString('zh-CN'),
period: options.period === 'daily' ? 'Daily' : 'Weekly',
projects,
news,
analytics,
options
};
// 5. 渲染模板
const templatePath = `${import.meta.dir}/../Templates/dashboard.hbs`;
const templateContent = await Bun.file(templatePath).text();
const template = Handlebars.compile(templateContent);
const html = template(templateData);
console.error(`✅ 模板渲染完成`);
// 6. 保存文件
await Bun.write(options.output, html);
console.error(`\n🎉 仪表板生成成功!`);
console.error(`📄 文件路径: ${options.output}`);
console.error(`\n💡 在浏览器中打开查看效果!`);
} catch (error) {
console.error('\n❌ 生成仪表板失败:');
console.error(error);
process.exit(1);
}
}
/**
* 解析命令行参数
*/
function parseArgs(): DashboardOptions {
const args = process.argv.slice(2);
const options: DashboardOptions = {
period: 'weekly',
limit: 10,
output: './github-trends.html',
includeNews: false,
newsCount: 10,
theme: 'auto'
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case '--period':
options.period = args[++i] === 'daily' ? 'daily' : 'weekly';
break;
case '--language':
options.language = args[++i];
break;
case '--limit':
options.limit = parseInt(args[++i]) || 10;
break;
case '--include-news':
options.includeNews = true;
break;
case '--news-count':
options.newsCount = parseInt(args[++i]) || 10;
break;
case '--theme':
options.theme = args[++i] === 'light' || args[++i] === 'dark' ? args[i] : 'auto';
break;
case '--output':
options.output = args[++i];
break;
default:
if (arg.startsWith('--output=')) {
options.output = arg.split('=')[1];
} else if (arg.startsWith('--language=')) {
options.language = arg.split('=')[1];
} else if (arg.startsWith('--limit=')) {
options.limit = parseInt(arg.split('=')[1]) || 10;
}
}
}
return options;
}
/**
* 主函数
*/
async function main() {
const options = parseArgs();
await generateDashboard(options);
}
// 如果直接运行此脚本
if (import.meta.main) {
main();
}
// 导出供其他模块使用
export { generateDashboard };
export type { DashboardOptions };
FILE:Tools/GetTechNews.ts
#!/usr/bin/env bun
/**
* Tech News Fetcher
*
* 从 Hacker News 和其他来源获取技术新闻
*
* 使用方式:
* ./GetTechNews.ts [count]
*
* 参数:
* count - 获取新闻数量 (默认: 10)
*
* 示例:
* ./GetTechNews.ts
* ./GetTechNews.ts 20
*/
import Parser from 'rss-parser';
import type { TechNewsItem } from './Lib/types';
const HN_API = 'https://hn.algolia.com/api/v1/search';
const parser = new Parser();
/**
* 从 Hacker News Algolia API 获取新闻
*/
async function getHackerNews(count: number): Promise<TechNewsItem[]> {
try {
const response = await fetch(`${HN_API}?tags=front_page&hits=${count}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data.hits.map((hit: any) => ({
id: hit.objectID,
title: hit.title,
url: hit.url || `https://news.ycombinator.com/item?id=${hit.objectID}`,
source: 'hackernews',
points: hit.points || 0,
comments: hit.num_comments || 0,
timestamp: new Date(hit.created_at).toISOString(),
tags: hit._tags || []
}));
} catch (error) {
console.error('获取 Hacker News 失败:', error);
return [];
}
}
/**
* 从 Hacker News RSS 获取新闻(备用方案)
*/
async function getHackerNewsRSS(count: number): Promise<TechNewsItem[]> {
try {
const feed = await parser.parseURL('https://news.ycombinator.com/rss');
return feed.items.slice(0, count).map((item: any) => ({
id: item.guid || item.link,
title: item.title || 'No title',
url: item.link,
source: 'hackernews',
timestamp: item.pubDate || new Date().toISOString(),
tags: ['hackernews', 'rss']
}));
} catch (error) {
console.error('获取 Hacker News RSS 失败:', error);
return [];
}
}
/**
* 获取技术新闻(主函数)
*/
async function getTechNews(count: number = 10): Promise<TechNewsItem[]> {
console.error(`正在获取技术新闻(${count}条)...`);
// 优先使用 Hacker News API
let news = await getHackerNews(count);
// 如果失败,尝试 RSS 备用
if (news.length === 0) {
console.error('Hacker News API 失败,尝试 RSS...');
news = await getHackerNewsRSS(count);
}
console.error(`✅ 获取到 ${news.length} 条新闻`);
return news;
}
/**
* CLI 入口
*/
async function main() {
const args = process.argv.slice(2);
const count = parseInt(args[0]) || 10;
try {
const news = await getTechNews(count);
// 输出 JSON 格式(便于程序调用)
console.log(JSON.stringify(news, null, 2));
} catch (error) {
console.error('❌ 获取新闻失败:');
console.error(error);
process.exit(1);
}
}
// 如果直接运行此脚本
if (import.meta.main) {
main();
}
// 导出供其他模块使用
export { getTechNews };
export type { TechNewsItem };
FILE:Tools/Lib/types.ts
/**
* GitHubTrends - 类型定义
*
* 定义所有 TypeScript 接口和类型
*/
/**
* GitHub Trending 项目
*/
export interface TrendingProject {
rank: number;
name: string;
description: string;
language: string;
stars: string;
starsThisPeriod: string;
url: string;
}
/**
* 技术新闻条目
*/
export interface TechNewsItem {
id: string;
title: string;
url: string;
source: string; // 'hackernews', 'reddit', etc.
points?: number;
comments?: number;
timestamp: string;
tags: string[];
}
/**
* 仪表板生成选项
*/
export interface DashboardOptions {
period: 'daily' | 'weekly';
language?: string;
limit: number;
output: string;
includeNews: boolean;
newsCount: number;
theme: 'light' | 'dark' | 'auto';
}
/**
* 数据分析结果
*/
export interface Analytics {
languageDistribution: Record<string, number>;
totalStars: number;
topProject: TrendingProject;
growthStats: {
highest: TrendingProject;
average: number;
};
}
/**
* Trending 查询选项(用于 GetTrending.ts)
*/
export interface TrendingOptions {
period: "daily" | "weekly";
language?: string;
limit: number;
}
/**
* 图表数据
*/
export interface ChartData {
labels: string[];
data: number[];
colors: string[];
}
/**
* 模板渲染数据
*/
export interface TemplateData {
title: string;
generatedAt: string;
period: string;
projects: TrendingProject[];
news?: TechNewsItem[];
analytics: Analytics;
options: DashboardOptions;
}
FILE:Tools/Lib/template-helpers.ts
/**
* Template Helpers
*
* Handlebars 自定义辅助函数
*/
import Handlebars from 'handlebars';
/**
* 注册所有自定义辅助函数
*/
export function registerHelpers(): void {
// 格式化数字(添加千位分隔符)
Handlebars.registerHelper('formatNumber', (value: number) => {
return value.toLocaleString();
});
// 截断文本
Handlebars.registerHelper('truncate', (str: string, length: number = 100) => {
if (str.length <= length) return str;
return str.substring(0, length) + '...';
});
// 格式化日期
Handlebars.registerHelper('formatDate', (dateStr: string) => {
const date = new Date(dateStr);
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
});
// JSON 序列化(用于内嵌数据)
Handlebars.registerHelper('json', (context: any) => {
return JSON.stringify(context);
});
// 条件判断
Handlebars.registerHelper('eq', (a: any, b: any) => {
return a === b;
});
Handlebars.registerHelper('ne', (a: any, b: any) => {
return a !== b;
});
Handlebars.registerHelper('gt', (a: number, b: number) => {
return a > b;
});
Handlebars.registerHelper('lt', (a: number, b: number) => {
return a < b;
});
}
/**
* 渲染模板
*/
export async function renderTemplate(
templatePath: string,
data: any
): Promise<string> {
const templateContent = await Bun.file(templatePath).text();
const template = Handlebars.compile(templateContent);
return template(data);
}
export default { registerHelpers, renderTemplate };
FILE:Tools/Lib/visualization-helpers.ts
/**
* Visualization Helpers
*
* 数据分析和可视化辅助函数
*/
import type { TrendingProject, Analytics } from './types';
/**
* 分析项目数据
*/
export function analyzeData(projects: TrendingProject[]): Analytics {
// 语言分布统计
const languageDistribution: Record<string, number> = {};
projects.forEach(project => {
const lang = project.language;
languageDistribution[lang] = (languageDistribution[lang] || 0) + 1;
});
// 总 stars 数
const totalStars = projects.reduce((sum, project) => {
return sum + parseInt(project.stars.replace(/,/g, '') || 0);
}, 0);
// 找出 top project
const topProject = projects.reduce((top, project) => {
const topStars = parseInt(top.stars.replace(/,/g, '') || 0);
const projStars = parseInt(project.stars.replace(/,/g, '') || 0);
return projStars > topStars ? project : top;
}, projects[0]);
// 增长统计
const projectsWithGrowth = projects.filter(p => p.starsThisPeriod);
const growthValues = projectsWithGrowth.map(p =>
parseInt(p.starsThisPeriod.replace(/[+,]/g, '') || 0)
);
const highestGrowth = projectsWithGrowth.reduce((highest, project) => {
const highestValue = parseInt(highest.starsThisPeriod.replace(/[+,]/g, '') || 0);
const projValue = parseInt(project.starsThisPeriod.replace(/[+,]/g, '') || 0);
return projValue > highestValue ? project : highest;
}, projectsWithGrowth[0] || projects[0]);
const averageGrowth = growthValues.length > 0
? Math.round(growthValues.reduce((a, b) => a + b, 0) / growthValues.length)
: 0;
// 提取唯一语言列表(用于筛选)
const languages = Object.keys(languageDistribution).sort();
// 生成图表数据
const growthData = projects.slice(0, 10).map(p => ({
name: p.name.split('/')[1] || p.name,
growth: parseInt(p.starsThisPeriod.replace(/[+,]/g, '') || 0)
}));
return {
languageDistribution,
totalStars,
topProject,
growthStats: {
highest: highestGrowth,
average: averageGrowth
},
languages,
growthData
};
}
/**
* 格式化 stars 数字
*/
export function formatStars(starsStr: string): number {
return parseInt(starsStr.replace(/,/g, '') || 0);
}
/**
* 解析增长数值
*/
export function parseGrowth(growthStr: string): number {
if (!growthStr) return 0;
return parseInt(growthStr.replace(/[+,]/g, '') || 0);
}
export default { analyzeData, formatStars, parseGrowth };
FILE:Templates/dashboard.hbs
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitHub Trending Dashboard - {{period}}</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
github: {
dark: '#0d1117',
light: '#161b22',
border: '#30363d',
accent: '#58a6ff'
}
}
}
}
}
</script>
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
}
.project-card {
transition: all 0.3s ease;
}
.project-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}
.stat-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.badge {
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 600;
}
.news-item {
border-left: 3px solid #58a6ff;
padding-left: 1rem;
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- 页头 -->
<header class="bg-white shadow-sm sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 py-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center">
<div>
<h1 class="text-3xl font-bold text-gray-900">🚀 GitHub Trending Dashboard</h1>
<p class="text-gray-600 mt-1">
周期: <span class="font-semibold text-github-accent">{{period}}</span> |
生成时间: <span class="text-gray-500">{{generatedAt}}</span>
</p>
</div>
<div class="flex gap-2">
<button onclick="window.print()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-medium">
🖨️ Print
</button>
</div>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-4 py-8 sm:px-6 lg:px-8">
<!-- 统计概览 -->
<section class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
<div class="stat-card rounded-xl p-6 text-white shadow-lg">
<h3 class="text-lg font-semibold opacity-90">项目总数</h3>
<p class="text-4xl font-bold mt-2">{{projects.length}}</p>
<p class="text-sm opacity-75 mt-1">{{period}} 热门趋势</p>
</div>
<div class="bg-gradient-to-br from-green-500 to-emerald-600 rounded-xl p-6 text-white shadow-lg">
<h3 class="text-lg font-semibold opacity-90">总 Stars 数</h3>
<p class="text-4xl font-bold mt-2">{{analytics.totalStars}}</p>
<p class="text-sm opacity-75 mt-1">所有项目总计</p>
</div>
<div class="bg-gradient-to-br from-orange-500 to-red-500 rounded-xl p-6 text-white shadow-lg">
<h3 class="text-lg font-semibold opacity-90">最热项目</h3>
<p class="text-xl font-bold mt-2 truncate">{{analytics.topProject.name}}</p>
<p class="text-sm opacity-75 mt-1">{{analytics.topProject.stars}} stars</p>
</div>
</section>
<!-- 筛选和搜索 -->
<section class="bg-white rounded-xl shadow-sm p-6 mb-8">
<div class="flex flex-wrap gap-4 items-center">
<div class="flex-1 min-w-64">
<label class="block text-sm font-medium text-gray-700 mb-1">搜索项目</label>
<input
type="text"
id="searchInput"
placeholder="按名称或描述搜索..."
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-github-accent focus:border-transparent"
oninput="filterProjects()"
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">语言筛选</label>
<select
id="languageFilter"
class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-github-accent focus:border-transparent"
onchange="filterProjects()"
>
<option value="all">全部语言</option>
{{#each analytics.languages}}
<option value="{{this}}">{{this}}</option>
{{/each}}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">排序方式</label>
<select
id="sortSelect"
class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-github-accent focus:border-transparent"
onchange="sortProjects()"
>
<option value="rank">排名</option>
<option value="stars">总 Stars</option>
<option value="growth">本期增长</option>
</select>
</div>
</div>
</section>
<!-- 语言分布图表 -->
<section class="bg-white rounded-xl shadow-sm p-6 mb-8">
<h2 class="text-2xl font-bold text-gray-900 mb-4">📊 语言分布</h2>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<div>
<canvas id="languageChart"></canvas>
</div>
<div>
<canvas id="growthChart"></canvas>
</div>
</div>
</section>
<!-- Trending Projects -->
<section class="mb-8">
<h2 class="text-2xl font-bold text-gray-900 mb-4">🔥 热门项目</h2>
<div id="projects-container" class="grid grid-cols-1 gap-4">
{{#each projects}}
<div class="project-card bg-white rounded-xl shadow-sm p-6 border border-gray-200"
data-rank="{{rank}}"
data-language="{{language}}"
data-stars="{{stars}}"
data-growth="{{starsThisPeriod}}"
data-name="{{name}}"
data-description="{{description}}">
<div class="flex items-start justify-between">
<div class="flex-1">
<div class="flex items-center gap-3 mb-2">
<span class="text-2xl font-bold text-github-accent">#{{rank}}</span>
<h3 class="text-xl font-semibold text-gray-900">
<a href="{{url}}" target="_blank" class="hover:text-github-accent">{{name}}</a>
</h3>
<span class="badge bg-blue-100 text-blue-800">{{language}}</span>
</div>
<p class="text-gray-600 mb-3">{{description}}</p>
<div class="flex items-center gap-4 text-sm text-gray-500">
<span>⭐ {{stars}} stars</span>
{{#if starsThisPeriod}}
<span class="text-green-600 font-semibold">(+{{starsThisPeriod}} this {{../period}})</span>
{{/if}}
</div>
</div>
<a href="{{url}}" target="_blank" class="px-4 py-2 bg-github-accent text-white rounded-lg hover:bg-blue-600 transition font-medium">
View →
</a>
</div>
</div>
{{/each}}
</div>
</section>
<!-- Tech News -->
{{#if news}}
<section class="mb-8">
<h2 class="text-2xl font-bold text-gray-900 mb-4">📰 技术资讯</h2>
<div class="grid grid-cols-1 gap-4">
{{#each news}}
<div class="news-item bg-white rounded-xl shadow-sm p-5 hover:shadow-md transition">
<div class="flex items-start justify-between">
<div class="flex-1">
<h3 class="text-lg font-semibold text-gray-900 mb-1">
<a href="{{url}}" target="_blank" class="hover:text-github-accent">{{title}}</a>
</h3>
<div class="flex items-center gap-4 text-sm text-gray-500">
<span class="text-orange-600">📰 {{source}}</span>
{{#if points}}
<span>⬆️ {{points}} points</span>
{{/if}}
{{#if comments}}
<span>💬 {{comments}} comments</span>
{{/if}}
</div>
</div>
</div>
</div>
{{/each}}
</div>
</section>
{{/if}}
</main>
<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 mt-12">
<div class="max-w-7xl mx-auto px-4 py-6 sm:px-6 lg:px-8">
<p class="text-center text-gray-500 text-sm">
由 GitHubTrends Skill 生成 | 数据来源:GitHub 和 Hacker News
</p>
</div>
</footer>
<!-- JavaScript -->
<script>
// 注入数据
window.dashboardData = {
projects: {{{json projects}}},
analytics: {
languageDistribution: {{{json analytics.languageDistribution}}},
growthData: {{{json analytics.growthData}}}
}
};
// 初始化图表
document.addEventListener('DOMContentLoaded', function() {
initLanguageChart();
initGrowthChart();
});
// 语言分布饼图
function initLanguageChart() {
const ctx = document.getElementById('languageChart').getContext('2d');
const data = window.dashboardData.analytics.languageDistribution;
new Chart(ctx, {
type: 'pie',
data: {
labels: Object.keys(data),
datasets: [{
data: Object.values(data),
backgroundColor: [
'#58a6ff', '#238636', '#f1e05a', '#d73a49',
'#8957E5', '#e34c26', '#CB3837', '#DA5B0B',
'#4F5D95', '#563d7c'
]
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'right'
},
title: {
display: true,
text: 'Projects by Language'
}
}
}
});
}
// Stars 增长柱状图
function initGrowthChart() {
const ctx = document.getElementById('growthChart').getContext('2d');
const projects = window.dashboardData.projects.slice(0, 10);
new Chart(ctx, {
type: 'bar',
data: {
labels: projects.map(p => p.name.split('/')[1] || p.name),
datasets: [{
label: 'Stars This Period',
data: projects.map(p => parseInt(p.starsThisPeriod.replace('+', '') || 0)),
backgroundColor: 'rgba(88, 166, 255, 0.8)',
borderColor: 'rgba(88, 166, 255, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
indexAxis: 'y',
plugins: {
title: {
display: true,
text: 'Top 10 Growth'
}
},
scales: {
x: {
beginAtZero: true
}
}
}
});
}
// 筛选项目
function filterProjects() {
const searchValue = document.getElementById('searchInput').value.toLowerCase();
const languageValue = document.getElementById('languageFilter').value;
const cards = document.querySelectorAll('.project-card');
cards.forEach(card => {
const name = card.dataset.name.toLowerCase();
const description = card.dataset.description.toLowerCase();
const language = card.dataset.language;
const matchesSearch = name.includes(searchValue) || description.includes(searchValue);
const matchesLanguage = languageValue === 'all' || language === languageValue;
card.style.display = matchesSearch && matchesLanguage ? 'block' : 'none';
});
}
// 排序项目
function sortProjects() {
const sortBy = document.getElementById('sortSelect').value;
const container = document.getElementById('projects-container');
const cards = Array.from(container.children);
cards.sort((a, b) => {
switch(sortBy) {
case 'stars':
return parseInt(b.dataset.stars.replace(/,/g, '')) - parseInt(a.dataset.stars.replace(/,/g, ''));
case 'growth':
const growthA = parseInt(a.dataset.growth.replace(/[+,]/g, '') || 0);
const growthB = parseInt(b.dataset.growth.replace(/[+,]/g, '') || 0);
return growthB - growthA;
case 'rank':
default:
return parseInt(a.dataset.rank) - parseInt(b.dataset.rank);
}
});
cards.forEach(card => container.appendChild(card));
}
</script>
</body>
</html>
FILE:Workflows/GenerateDashboard.md
# GenerateDashboard Workflow
生成交互式数据可视化仪表板的工作流程。
## Description
这个工作流使用 GenerateDashboard.ts 工具从 GitHub 获取 trending 项目,并生成交互式 HTML 仪表板,支持:
- 项目卡片展示
- 语言分布饼图
- Stars 增长柱状图
- 技术新闻列表
- 实时筛选、排序、搜索功能
## When to Use
当用户请求以下任何内容时使用此工作流:
- "生成 GitHub trending 仪表板"
- "创建趋势网页"
- "生成可视化报告"
- "export trending dashboard"
- "生成交互式网页"
## Workflow Steps
### Step 1: 确定参数
向用户确认或推断以下参数:
- **时间周期**: daily (每日) 或 weekly (每周,默认)
- **编程语言**: 可选(如 TypeScript, Python, Go, Rust等)
- **项目数量**: 默认10个
- **包含新闻**: 是否包含技术新闻
- **新闻数量**: 默认10条
- **输出路径**: 默认 ./github-trends.html
### Step 2: 执行工具
运行 GenerateDashboard.ts 工具:
```bash
# 基本用法(本周,10个项目)
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts
# 指定语言和新闻
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts \
--period weekly \
--language TypeScript \
--limit 20 \
--include-news \
--news-count 15 \
--output ~/trends.html
# 每日趋势
bun ~/.claude/skills/GitHubTrends/Tools/GenerateDashboard.ts \
--period daily \
--output ~/daily-trends.html
```
### Step 3: 显示结果
工具会自动:
1. 获取 GitHub trending 数据
2. 获取技术新闻(如果启用)
3. 分析数据生成统计信息
4. 渲染 HTML 模板
5. 保存到指定路径
### Step 4: 验证和打开
生成的 HTML 文件包含:
- ✅ 响应式布局
- ✅ 项目卡片展示
- ✅ 语言分布饼图
- ✅ Stars 增长柱状图
- ✅ 实时筛选功能
- ✅ 排序功能
- ✅ 搜索功能
- ✅ 技术新闻列表
## Example Usage
### Example 1: 基本仪表板
```
User: "生成本周 GitHub trending 仪表板"
Assistant:
运行 GenerateDashboard 工具...
[执行命令,生成 /tmp/github-trends.html]
✅ 仪表板生成成功!已在浏览器中打开。
```
### Example 2: 包含新闻的仪表板
```
User: "生成 TypeScript 项目的每日趋势,包含新闻"
Assistant:
生成 TypeScript 每日趋势仪表板,包含技术新闻...
[执行命令:--period daily --language TypeScript --include-news]
✅ 仪表板已生成到 ~/Downloads/ts-daily-trends.html
```
### Example 3: 自定义输出
```
User: "生成一个包含 20 个项目的仪表板,保存到桌面"
Assistant:
生成 20 个项目的趋势仪表板...
[执行命令:--limit 20 --output ~/Desktop/github-trends.html]
✅ 完成!文件已保存到桌面
```
## Tool Options
| 参数 | 说明 | 默认值 | 可选值 |
|------|------|--------|--------|
| `--period` | 时间周期 | `weekly` | `daily`, `weekly` |
| `--language` | 编程语言筛选 | 全部 | TypeScript, Python, Go, Rust等 |
| `--limit` | 返回项目数量 | 10 | 任意正整数 |
| `--include-news` | 包含技术新闻 | false | - |
| `--news-count` | 新闻数量 | 10 | 任意正整数 |
| `--theme` | 主题 | `auto` | `light`, `dark`, `auto` |
| `--output` | 输出文件路径 | `./github-trends.html` | 任意路径 |
## Output Features
### 数据可视化
- **语言分布饼图**: 展示各编程语言的项目占比
- **Stars 增长柱状图**: 展示前 10 名项目的 stars 增长
### 交互功能
- **搜索**: 按项目名称或描述搜索
- **筛选**: 按编程语言筛选
- **排序**: 按排名、总 stars、周期内增长排序
### 响应式设计
- 支持桌面、平板、手机
- 使用 Tailwind CSS 构建美观界面
- GitHub 风格配色
## Error Handling
如果遇到错误:
1. **网络错误**: 检查网络连接,确保能访问 GitHub
2. **解析失败**: GitHub 页面结构可能变化,工具会显示调试信息
3. **文件写入失败**: 检查输出路径的写权限
## Voice Notification
执行此工作流时发送语音通知:
```bash
curl -s -X POST http://localhost:8888/notify \
-H "Content-Type: application/json" \
-d '{"message": "正在生成 GitHub Trending Dashboard..."}' \
> /dev/null 2>&1 &
```
并输出文本通知:
```
Running the **GenerateDashboard** workflow from the **GitHubTrends** skill...
```
## Integration with Other Skills
- **Browser**: 验证生成的 HTML 页面效果
- **System**: 保存仪表板快照到 MEMORY/
- **OSINT**: 分析技术栈趋势
## Notes
- 数据每小时更新一次(GitHub trending 更新频率)
- 生成的 HTML 是完全独立的,无需服务器
- 所有依赖通过 CDN 加载(Tailwind CSS, Chart.js)
- 支持离线查看(图表已内嵌数据)
## Advanced Usage
### 批量生成
```bash
# 生成多个语言的仪表板
for lang in TypeScript Python Go Rust; do
bun Tools/GenerateDashboard.ts \
--language $lang \
--output ~/trends-$lang.html
done
```
### 定时任务
```bash
# 每小时生成一次快照
# 添加到 crontab:
0 * * * * cd ~/.claude/skills/GitHubTrends && bun Tools/GenerateDashboard.ts --output ~/trends-$(date +%H).html
```
### 定制主题
通过修改 `Templates/dashboard.hbs` 可以自定义:
- 配色方案
- 布局结构
- 添加新的图表类型
- 添加新的交互功能