Merge pull request #929 from xingzihai/feat/skill-development-guide

docs: add comprehensive Skill Development Guide
This commit is contained in:
Affaan Mustafa
2026-03-28 20:24:01 -04:00
committed by GitHub
15 changed files with 1665 additions and 12 deletions

View File

@@ -73,6 +73,13 @@ git add . && git commit -m "feat: add my-skill" && git push -u origin feat/my-co
Skills are knowledge modules that Claude Code loads based on context.
> **📚 Comprehensive Guide:** For detailed guidance on creating effective skills, see [Skill Development Guide](docs/SKILL-DEVELOPMENT-GUIDE.md). It covers:
> - Skill architecture and categories
> - Writing effective content with examples
> - Best practices and common patterns
> - Testing and validation
> - Complete examples gallery
### Directory Structure
```
@@ -86,7 +93,7 @@ skills/
```markdown
---
name: your-skill-name
description: Brief description shown in skill list
description: Brief description shown in skill list and used for auto-activation
origin: ECC
---
@@ -94,6 +101,10 @@ origin: ECC
Brief overview of what this skill covers.
## When to Activate
Describe scenarios where Claude should use this skill. This is critical for auto-activation.
## Core Concepts
Explain key patterns and guidelines.
@@ -107,33 +118,54 @@ function example() {
}
\`\`\`
## Anti-Patterns
Show what NOT to do with examples.
## Best Practices
- Actionable guidelines
- Do's and don'ts
- Common pitfalls to avoid
## When to Use
## Related Skills
Describe scenarios where this skill applies.
Link to complementary skills (e.g., `related-skill-1`, `related-skill-2`).
```
### Skill Categories
| Category | Purpose | Examples |
|----------|---------|----------|
| **Language Standards** | Idioms, conventions, best practices | `python-patterns`, `golang-patterns` |
| **Framework Patterns** | Framework-specific guidance | `django-patterns`, `nextjs-patterns` |
| **Workflow** | Step-by-step processes | `tdd-workflow`, `refactoring-workflow` |
| **Domain Knowledge** | Specialized domains | `security-review`, `api-design` |
| **Tool Integration** | Tool/library usage | `docker-patterns`, `supabase-patterns` |
| **Template** | Project-specific skill templates | `project-guidelines-example` |
### Skill Checklist
- [ ] Focused on one domain/technology
- [ ] Includes practical code examples
- [ ] Under 500 lines
- [ ] Focused on one domain/technology (not too broad)
- [ ] Includes "When to Activate" section for auto-activation
- [ ] Includes practical, copy-pasteable code examples
- [ ] Shows anti-patterns (what NOT to do)
- [ ] Under 500 lines (800 max)
- [ ] Uses clear section headers
- [ ] Tested with Claude Code
- [ ] Links to related skills
- [ ] No sensitive data (API keys, tokens, paths)
### Example Skills
| Skill | Purpose |
|-------|---------|
| `coding-standards/` | TypeScript/JavaScript patterns |
| `frontend-patterns/` | React and Next.js best practices |
| `backend-patterns/` | API and database patterns |
| `security-review/` | Security checklist |
| Skill | Category | Purpose |
|-------|----------|---------|
| `coding-standards/` | Language Standards | TypeScript/JavaScript patterns |
| `frontend-patterns/` | Framework Patterns | React and Next.js best practices |
| `backend-patterns/` | Framework Patterns | API and database patterns |
| `security-review/` | Domain Knowledge | Security checklist |
| `tdd-workflow/` | Workflow | Test-driven development process |
| `project-guidelines-example/` | Template | Project-specific skill template |
---

View File

@@ -0,0 +1,919 @@
# Skill Development Guide
A comprehensive guide to creating effective skills for Everything Claude Code (ECC).
## Table of Contents
- [What Are Skills?](#what-are-skills)
- [Skill Architecture](#skill-architecture)
- [Creating Your First Skill](#creating-your-first-skill)
- [Skill Categories](#skill-categories)
- [Writing Effective Skill Content](#writing-effective-skill-content)
- [Best Practices](#best-practices)
- [Common Patterns](#common-patterns)
- [Testing Your Skill](#testing-your-skill)
- [Submitting Your Skill](#submitting-your-skill)
- [Examples Gallery](#examples-gallery)
---
## What Are Skills?
Skills are **knowledge modules** that Claude Code loads based on context. They provide:
- **Domain expertise**: Framework patterns, language idioms, best practices
- **Workflow definitions**: Step-by-step processes for common tasks
- **Reference material**: Code snippets, checklists, decision trees
- **Context injection**: Activate when specific conditions are met
Unlike **agents** (specialized subassistants) or **commands** (user-triggered actions), skills are passive knowledge that Claude Code references when relevant.
### When Skills Activate
Skills activate when:
- The user's task matches the skill's domain
- Claude Code detects relevant context
- A command references a skill
- An agent needs domain knowledge
### Skill vs Agent vs Command
| Component | Purpose | Activation |
|-----------|---------|------------|
| **Skill** | Knowledge repository | Context-based (automatic) |
| **Agent** | Task executor | Explicit delegation |
| **Command** | User action | User-invoked (`/command`) |
| **Hook** | Automation | Event-triggered |
| **Rule** | Always-on guidelines | Always active |
---
## Skill Architecture
### File Structure
```
skills/
└── your-skill-name/
├── SKILL.md # Required: Main skill definition
├── examples/ # Optional: Code examples
│ ├── basic.ts
│ └── advanced.ts
└── references/ # Optional: External references
└── links.md
```
### SKILL.md Format
```markdown
---
name: skill-name
description: Brief description shown in skill list and used for auto-activation
origin: ECC
---
# Skill Title
Brief overview of what this skill covers.
## When to Activate
Describe scenarios where Claude should use this skill.
## Core Concepts
Main patterns and guidelines.
## Code Examples
\`\`\`typescript
// Practical, tested examples
\`\`\`
## Anti-Patterns
Show what NOT to do with concrete examples.
## Best Practices
- Actionable guidelines
- Do's and don'ts
## Related Skills
Link to complementary skills.
```
### YAML Frontmatter Fields
| Field | Required | Description |
|-------|----------|-------------|
| `name` | Yes | Lowercase, hyphenated identifier (e.g., `react-patterns`) |
| `description` | Yes | One-line description for skill list and auto-activation |
| `origin` | No | Source identifier (e.g., `ECC`, `community`, project name) |
| `tags` | No | Array of tags for categorization |
| `version` | No | Skill version for tracking updates |
---
## Creating Your First Skill
### Step 1: Choose a Focus
Good skills are **focused and actionable**:
| ✅ Good Focus | ❌ Too Broad |
|---------------|--------------|
| `react-hook-patterns` | `react` |
| `postgresql-indexing` | `databases` |
| `pytest-fixtures` | `python-testing` |
| `nextjs-app-router` | `nextjs` |
### Step 2: Create the Directory
```bash
mkdir -p skills/your-skill-name
```
### Step 3: Write SKILL.md
Here's a minimal template:
```markdown
---
name: your-skill-name
description: Brief description of when to use this skill
---
# Your Skill Title
Brief overview (1-2 sentences).
## When to Activate
- Scenario 1
- Scenario 2
- Scenario 3
## Core Concepts
### Concept 1
Explanation with examples.
### Concept 2
Another pattern with code.
## Code Examples
\`\`\`typescript
// Practical example
\`\`\`
## Best Practices
- Do this
- Avoid that
## Related Skills
- `related-skill-1`
- `related-skill-2`
```
### Step 4: Add Content
Write content that Claude can **immediately use**:
- ✅ Copy-pasteable code examples
- ✅ Clear decision trees
- ✅ Checklists for verification
- ❌ Vague explanations without examples
- ❌ Long prose without actionable guidance
---
## Skill Categories
### Language Standards
Focus on idiomatic code, naming conventions, and language-specific patterns.
**Examples:** `python-patterns`, `golang-patterns`, `typescript-standards`
```markdown
---
name: python-patterns
description: Python idioms, best practices, and patterns for clean, idiomatic code.
---
# Python Patterns
## When to Activate
- Writing Python code
- Refactoring Python modules
- Python code review
## Core Concepts
### Context Managers
\`\`\`python
# Always use context managers for resources
with open('file.txt') as f:
content = f.read()
\`\`\`
```
### Framework Patterns
Focus on framework-specific conventions, common patterns, and anti-patterns.
**Examples:** `django-patterns`, `nextjs-patterns`, `springboot-patterns`
```markdown
---
name: django-patterns
description: Django best practices for models, views, URLs, and templates.
---
# Django Patterns
## When to Activate
- Building Django applications
- Creating models and views
- Django URL configuration
```
### Workflow Skills
Define step-by-step processes for common development tasks.
**Examples:** `tdd-workflow`, `code-review-workflow`, `deployment-checklist`
```markdown
---
name: code-review-workflow
description: Systematic code review process for quality and security.
---
# Code Review Workflow
## Steps
1. **Understand Context** - Read PR description and linked issues
2. **Check Tests** - Verify test coverage and quality
3. **Review Logic** - Analyze implementation for correctness
4. **Check Security** - Look for vulnerabilities
5. **Verify Style** - Ensure code follows conventions
```
### Domain Knowledge
Specialized knowledge for specific domains (security, performance, etc.).
**Examples:** `security-review`, `performance-optimization`, `api-design`
```markdown
---
name: api-design
description: REST and GraphQL API design patterns, versioning, and best practices.
---
# API Design Patterns
## RESTful Conventions
| Method | Endpoint | Purpose |
|--------|----------|---------|
| GET | /resources | List all |
| GET | /resources/:id | Get one |
| POST | /resources | Create |
```
### Tool Integration
Guidance for using specific tools, libraries, or services.
**Examples:** `supabase-patterns`, `docker-patterns`, `mcp-server-patterns`
---
## Writing Effective Skill Content
### 1. Start with "When to Activate"
This section is **critical** for auto-activation. Be specific:
```markdown
## When to Activate
- Creating new React components
- Refactoring existing components
- Debugging React state issues
- Reviewing React code for best practices
```
### 2. Use "Show, Don't Tell"
Bad:
```markdown
## Error Handling
Always handle errors properly in async functions.
```
Good:
```markdown
## Error Handling
\`\`\`typescript
async function fetchData(url: string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(\`HTTP \${response.status}: \${response.statusText}\`)
}
return await response.json()
} catch (error) {
console.error('Fetch failed:', error)
throw new Error('Failed to fetch data')
}
}
\`\`\`
### Key Points
- Check \`response.ok\` before parsing
- Log errors for debugging
- Re-throw with user-friendly message
```
### 3. Include Anti-Patterns
Show what NOT to do:
```markdown
## Anti-Patterns
### ❌ Direct State Mutation
\`\`\`typescript
// NEVER do this
user.name = 'New Name'
items.push(newItem)
\`\`\`
### ✅ Immutable Updates
\`\`\`typescript
// ALWAYS do this
const updatedUser = { ...user, name: 'New Name' }
const updatedItems = [...items, newItem]
\`\`\`
```
### 4. Provide Checklists
Checklists are actionable and easy to follow:
```markdown
## Pre-Deployment Checklist
- [ ] All tests passing
- [ ] No console.log in production code
- [ ] Environment variables documented
- [ ] Secrets not hardcoded
- [ ] Error handling complete
- [ ] Input validation in place
```
### 5. Use Decision Trees
For complex decisions:
```markdown
## Choosing the Right Approach
\`\`\`
Need to fetch data?
├── Single request → use fetch directly
├── Multiple independent → Promise.all()
├── Multiple dependent → await sequentially
└── With caching → use SWR or React Query
\`\`\`
```
---
## Best Practices
### DO
| Practice | Example |
|----------|---------|
| **Be specific** | "Use \`useCallback\` for event handlers passed to child components" |
| **Show examples** | Include copy-pasteable code |
| **Explain WHY** | "Immutability prevents unexpected side effects in React state" |
| **Link related skills** | "See also: \`react-performance\`" |
| **Keep focused** | One skill = one domain/concept |
| **Use sections** | Clear headers for easy scanning |
### DON'T
| Practice | Why It's Bad |
|----------|--------------|
| **Be vague** | "Write good code" - not actionable |
| **Long prose** | Hard to parse, better as code |
| **Cover too much** | "Python, Django, and Flask patterns" - too broad |
| **Skip examples** | Theory without practice is less useful |
| **Ignore anti-patterns** | Learning what NOT to do is valuable |
### Content Guidelines
1. **Length**: 200-500 lines typical, 800 lines maximum
2. **Code blocks**: Include language identifier
3. **Headers**: Use `##` and `###` hierarchy
4. **Lists**: Use `-` for unordered, `1.` for ordered
5. **Tables**: For comparisons and references
---
## Common Patterns
### Pattern 1: Standards Skill
```markdown
---
name: language-standards
description: Coding standards and best practices for [language].
---
# [Language] Coding Standards
## When to Activate
- Writing [language] code
- Code review
- Setting up linting
## Naming Conventions
| Element | Convention | Example |
|---------|------------|---------|
| Variables | camelCase | userName |
| Constants | SCREAMING_SNAKE | MAX_RETRY |
| Functions | camelCase | fetchUser |
| Classes | PascalCase | UserService |
## Code Examples
[Include practical examples]
## Linting Setup
[Include configuration]
## Related Skills
- `language-testing`
- `language-security`
```
### Pattern 2: Workflow Skill
```markdown
---
name: task-workflow
description: Step-by-step workflow for [task].
---
# [Task] Workflow
## When to Activate
- [Trigger 1]
- [Trigger 2]
## Prerequisites
- [Requirement 1]
- [Requirement 2]
## Steps
### Step 1: [Name]
[Description]
\`\`\`bash
[Commands]
\`\`\`
### Step 2: [Name]
[Description]
## Verification
- [ ] [Check 1]
- [ ] [Check 2]
## Troubleshooting
| Problem | Solution |
|---------|----------|
| [Issue] | [Fix] |
```
### Pattern 3: Reference Skill
```markdown
---
name: api-reference
description: Quick reference for [API/Library].
---
# [API/Library] Reference
## When to Activate
- Using [API/Library]
- Looking up [API/Library] syntax
## Common Operations
### Operation 1
\`\`\`typescript
// Basic usage
\`\`\`
### Operation 2
\`\`\`typescript
// Advanced usage
\`\`\`
## Configuration
[Include config examples]
## Error Handling
[Include error patterns]
```
---
## Testing Your Skill
### Local Testing
1. **Copy to Claude Code skills directory**:
```bash
cp -r skills/your-skill-name ~/.claude/skills/
```
2. **Test with Claude Code**:
```
You: "I need to [task that should trigger your skill]"
Claude should reference your skill's patterns.
```
3. **Verify activation**:
- Ask Claude to explain a concept from your skill
- Check if it uses your examples and patterns
- Ensure it follows your guidelines
### Validation Checklist
- [ ] **YAML frontmatter valid** - No syntax errors
- [ ] **Name follows convention** - lowercase-with-hyphens
- [ ] **Description is clear** - Tells when to use
- [ ] **Examples work** - Code compiles and runs
- [ ] **Links valid** - Related skills exist
- [ ] **No sensitive data** - No API keys, tokens, paths
### Code Example Testing
Test all code examples:
```bash
# From the repo root
npx tsc --noEmit skills/your-skill-name/examples/*.ts
# Or from inside the skill directory
npx tsc --noEmit examples/*.ts
# From the repo root
python -m py_compile skills/your-skill-name/examples/*.py
# Or from inside the skill directory
python -m py_compile examples/*.py
# From the repo root
go build ./skills/your-skill-name/examples/...
# Or from inside the skill directory
go build ./examples/...
```
---
## Submitting Your Skill
### 1. Fork and Clone
```bash
gh repo fork affaan-m/everything-claude-code --clone
cd everything-claude-code
```
### 2. Create Branch
```bash
git checkout -b feat/skill-your-skill-name
```
### 3. Add Your Skill
```bash
mkdir -p skills/your-skill-name
# Create SKILL.md
```
### 4. Validate
```bash
# Check YAML frontmatter
head -10 skills/your-skill-name/SKILL.md
# Verify structure
ls -la skills/your-skill-name/
# Run tests if available
npm test
```
### 5. Commit and Push
```bash
git add skills/your-skill-name/
git commit -m "feat(skills): add your-skill-name skill"
git push -u origin feat/skill-your-skill-name
```
### 6. Create Pull Request
Use this PR template:
```markdown
## Summary
Brief description of the skill and why it's valuable.
## Skill Type
- [ ] Language standards
- [ ] Framework patterns
- [ ] Workflow
- [ ] Domain knowledge
- [ ] Tool integration
## Testing
How I tested this skill locally.
## Checklist
- [ ] YAML frontmatter valid
- [ ] Code examples tested
- [ ] Follows skill guidelines
- [ ] No sensitive data
- [ ] Clear activation triggers
```
---
## Examples Gallery
### Example 1: Language Standards
**File:** `skills/rust-patterns/SKILL.md`
```markdown
---
name: rust-patterns
description: Rust idioms, ownership patterns, and best practices for safe, idiomatic code.
origin: ECC
---
# Rust Patterns
## When to Activate
- Writing Rust code
- Handling ownership and borrowing
- Error handling with Result/Option
- Implementing traits
## Ownership Patterns
### Borrowing Rules
\`\`\`rust
// ✅ CORRECT: Borrow when you don't need ownership
fn process_data(data: &str) -> usize {
data.len()
}
// ✅ CORRECT: Take ownership when you need to modify or consume
fn consume_data(data: Vec<u8>) -> String {
String::from_utf8(data).unwrap()
}
\`\`\`
## Error Handling
### Result Pattern
\`\`\`rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Parse error: {0}")]
Parse(#[from] std::num::ParseIntError),
}
pub type AppResult<T> = Result<T, AppError>;
\`\`\`
## Related Skills
- `rust-testing`
- `rust-security`
```
### Example 2: Framework Patterns
**File:** `skills/fastapi-patterns/SKILL.md`
```markdown
---
name: fastapi-patterns
description: FastAPI patterns for routing, dependency injection, validation, and async operations.
origin: ECC
---
# FastAPI Patterns
## When to Activate
- Building FastAPI applications
- Creating API endpoints
- Implementing dependency injection
- Handling async database operations
## Project Structure
\`\`\`
app/
├── main.py # FastAPI app entry point
├── routers/ # Route handlers
│ ├── users.py
│ └── items.py
├── models/ # Pydantic models
│ ├── user.py
│ └── item.py
├── services/ # Business logic
│ └── user_service.py
└── dependencies.py # Shared dependencies
\`\`\`
## Dependency Injection
\`\`\`python
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
async def get_db() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session
@router.get("/users/{user_id}")
async def get_user(
user_id: int,
db: AsyncSession = Depends(get_db)
):
# Use db session
pass
\`\`\`
## Related Skills
- `python-patterns`
- `pydantic-validation`
```
### Example 3: Workflow Skill
**File:** `skills/refactoring-workflow/SKILL.md`
```markdown
---
name: refactoring-workflow
description: Systematic refactoring workflow for improving code quality without changing behavior.
origin: ECC
---
# Refactoring Workflow
## When to Activate
- Improving code structure
- Reducing technical debt
- Simplifying complex code
- Extracting reusable components
## Prerequisites
- All tests passing
- Git working directory clean
- Feature branch created
## Workflow Steps
### Step 1: Identify Refactoring Target
- Look for code smells (long methods, duplicate code, large classes)
- Check test coverage for target area
- Document current behavior
### Step 2: Ensure Tests Exist
\`\`\`bash
# Run tests to verify current behavior
npm test
# Check coverage for target files
npm run test:coverage
\`\`\`
### Step 3: Make Small Changes
- One refactoring at a time
- Run tests after each change
- Commit frequently
### Step 4: Verify Behavior Unchanged
\`\`\`bash
# Run full test suite
npm test
# Run E2E tests
npm run test:e2e
\`\`\`
## Common Refactorings
| Smell | Refactoring |
|-------|-------------|
| Long method | Extract method |
| Duplicate code | Extract to shared function |
| Large class | Extract class |
| Long parameter list | Introduce parameter object |
## Checklist
- [ ] Tests exist for target code
- [ ] Made small, focused changes
- [ ] Tests pass after each change
- [ ] Behavior unchanged
- [ ] Committed with clear message
```
---
## Additional Resources
- [CONTRIBUTING.md](../CONTRIBUTING.md) - General contribution guidelines
- [project-guidelines-example](../skills/project-guidelines-example/SKILL.md) - Project-specific skill template
- [coding-standards](../skills/coding-standards/SKILL.md) - Example of standards skill
- [tdd-workflow](../skills/tdd-workflow/SKILL.md) - Example of workflow skill
- [security-review](../skills/security-review/SKILL.md) - Example of domain knowledge skill
---
**Remember**: A good skill is focused, actionable, and immediately useful. Write skills you'd want to use yourself.

124
rules/common/code-review.md Normal file
View File

@@ -0,0 +1,124 @@
# Code Review Standards
## Purpose
Code review ensures quality, security, and maintainability before code is merged. This rule defines when and how to conduct code reviews.
## When to Review
**MANDATORY review triggers:**
- After writing or modifying code
- Before any commit to shared branches
- When security-sensitive code is changed (auth, payments, user data)
- When architectural changes are made
- Before merging pull requests
**Pre-Review Requirements:**
Before requesting review, ensure:
- All automated checks (CI/CD) are passing
- Merge conflicts are resolved
- Branch is up to date with target branch
## Review Checklist
Before marking code complete:
- [ ] Code is readable and well-named
- [ ] Functions are focused (<50 lines)
- [ ] Files are cohesive (<800 lines)
- [ ] No deep nesting (>4 levels)
- [ ] Errors are handled explicitly
- [ ] No hardcoded secrets or credentials
- [ ] No console.log or debug statements
- [ ] Tests exist for new functionality
- [ ] Test coverage meets 80% minimum
## Security Review Triggers
**STOP and use security-reviewer agent when:**
- Authentication or authorization code
- User input handling
- Database queries
- File system operations
- External API calls
- Cryptographic operations
- Payment or financial code
## Review Severity Levels
| Level | Meaning | Action |
|-------|---------|--------|
| CRITICAL | Security vulnerability or data loss risk | **BLOCK** - Must fix before merge |
| HIGH | Bug or significant quality issue | **WARN** - Should fix before merge |
| MEDIUM | Maintainability concern | **INFO** - Consider fixing |
| LOW | Style or minor suggestion | **NOTE** - Optional |
## Agent Usage
Use these agents for code review:
| Agent | Purpose |
|-------|---------|
| **code-reviewer** | General code quality, patterns, best practices |
| **security-reviewer** | Security vulnerabilities, OWASP Top 10 |
| **typescript-reviewer** | TypeScript/JavaScript specific issues |
| **python-reviewer** | Python specific issues |
| **go-reviewer** | Go specific issues |
| **rust-reviewer** | Rust specific issues |
## Review Workflow
```
1. Run git diff to understand changes
2. Check security checklist first
3. Review code quality checklist
4. Run relevant tests
5. Verify coverage >= 80%
6. Use appropriate agent for detailed review
```
## Common Issues to Catch
### Security
- Hardcoded credentials (API keys, passwords, tokens)
- SQL injection (string concatenation in queries)
- XSS vulnerabilities (unescaped user input)
- Path traversal (unsanitized file paths)
- CSRF protection missing
- Authentication bypasses
### Code Quality
- Large functions (>50 lines) - split into smaller
- Large files (>800 lines) - extract modules
- Deep nesting (>4 levels) - use early returns
- Missing error handling - handle explicitly
- Mutation patterns - prefer immutable operations
- Missing tests - add test coverage
### Performance
- N+1 queries - use JOINs or batching
- Missing pagination - add LIMIT to queries
- Unbounded queries - add constraints
- Missing caching - cache expensive operations
## Approval Criteria
- **Approve**: No CRITICAL or HIGH issues
- **Warning**: Only HIGH issues (merge with caution)
- **Block**: CRITICAL issues found
## Integration with Other Rules
This rule works with:
- [testing.md](testing.md) - Test coverage requirements
- [security.md](security.md) - Security checklist
- [git-workflow.md](git-workflow.md) - Commit standards
- [agents.md](agents.md) - Agent delegation

View File

@@ -36,3 +36,9 @@ The Feature Implementation Workflow describes the development pipeline: research
- Detailed commit messages
- Follow conventional commits format
- See [git-workflow.md](./git-workflow.md) for commit message format and PR process
5. **Pre-Review Checks**
- Verify all automated checks (CI/CD) are passing
- Resolve any merge conflicts
- Ensure branch is up to date with target branch
- Only request review after these checks pass

108
rules/zh/README.md Normal file
View File

@@ -0,0 +1,108 @@
# 规则
## 结构
规则按**通用**层和**语言特定**目录组织:
```
rules/
├── common/ # 语言无关的原则(始终安装)
│ ├── coding-style.md
│ ├── git-workflow.md
│ ├── testing.md
│ ├── performance.md
│ ├── patterns.md
│ ├── hooks.md
│ ├── agents.md
│ ├── security.md
│ ├── code-review.md
│ └── development-workflow.md
├── zh/ # 中文翻译版本
│ ├── coding-style.md
│ ├── git-workflow.md
│ ├── testing.md
│ ├── performance.md
│ ├── patterns.md
│ ├── hooks.md
│ ├── agents.md
│ ├── security.md
│ ├── code-review.md
│ └── development-workflow.md
├── typescript/ # TypeScript/JavaScript 特定
├── python/ # Python 特定
├── golang/ # Go 特定
├── swift/ # Swift 特定
└── php/ # PHP 特定
```
- **common/** 包含通用原则 — 无语言特定的代码示例。
- **zh/** 包含 common 目录的中文翻译版本。
- **语言目录** 扩展通用规则,包含框架特定的模式、工具和代码示例。每个文件引用其对应的通用版本。
## 安装
### 选项 1安装脚本推荐
```bash
# 安装通用 + 一个或多个语言特定的规则集
./install.sh typescript
./install.sh python
./install.sh golang
./install.sh swift
./install.sh php
# 同时安装多种语言
./install.sh typescript python
```
### 选项 2手动安装
> **重要提示:** 复制整个目录 — 不要使用 `/*` 展开。
> 通用和语言特定目录包含同名文件。
> 将它们展开到一个目录会导致语言特定文件覆盖通用规则,
> 并破坏语言特定文件使用的 `../common/` 相对引用。
```bash
# 创建目标目录
mkdir -p ~/.claude/rules
# 安装通用规则(所有项目必需)
cp -r rules/common ~/.claude/rules/common
# 安装中文翻译版本(可选)
cp -r rules/zh ~/.claude/rules/zh
# 根据项目技术栈安装语言特定规则
cp -r rules/typescript ~/.claude/rules/typescript
cp -r rules/python ~/.claude/rules/python
cp -r rules/golang ~/.claude/rules/golang
cp -r rules/swift ~/.claude/rules/swift
cp -r rules/php ~/.claude/rules/php
```
## 规则 vs 技能
- **规则** 定义广泛适用的标准、约定和检查清单(如"80% 测试覆盖率"、"禁止硬编码密钥")。
- **技能**`skills/` 目录)为特定任务提供深入、可操作的参考材料(如 `python-patterns``golang-testing`)。
语言特定的规则文件在适当的地方引用相关技能。规则告诉你*做什么*;技能告诉你*怎么做*。
## 规则优先级
当语言特定规则与通用规则冲突时,**语言特定规则优先**(特定覆盖通用)。这遵循标准的分层配置模式(类似于 CSS 特异性或 `.gitignore` 优先级)。
- `rules/common/` 定义适用于所有项目的通用默认值。
- `rules/golang/``rules/python/``rules/swift/``rules/php/``rules/typescript/` 等在语言习惯不同时覆盖这些默认值。
- `rules/zh/` 是通用规则的中文翻译,与英文版本内容一致。
### 示例
`common/coding-style.md` 推荐不可变性作为默认原则。语言特定的 `golang/coding-style.md` 可以覆盖这一点:
> 惯用的 Go 使用指针接收器进行结构体变更 — 参见 [common/coding-style.md](../common/coding-style.md) 了解通用原则,但这里首选符合 Go 习惯的变更方式。
### 带覆盖说明的通用规则
`rules/common/` 中可能被语言特定文件覆盖的规则会被标记:
> **语言说明**:此规则可能会被语言特定规则覆盖;对于某些语言,该模式可能并不符合惯用写法。

50
rules/zh/agents.md Normal file
View File

@@ -0,0 +1,50 @@
# 代理编排
## 可用代理
位于 `~/.claude/agents/`
| 代理 | 用途 | 何时使用 |
|-------|---------|------------|
| planner | 实现规划 | 复杂功能、重构 |
| architect | 系统设计 | 架构决策 |
| tdd-guide | 测试驱动开发 | 新功能、bug 修复 |
| code-reviewer | 代码审查 | 编写代码后 |
| security-reviewer | 安全分析 | 提交前 |
| build-error-resolver | 修复构建错误 | 构建失败时 |
| e2e-runner | E2E 测试 | 关键用户流程 |
| refactor-cleaner | 死代码清理 | 代码维护 |
| doc-updater | 文档 | 更新文档 |
| rust-reviewer | Rust 代码审查 | Rust 项目 |
## 立即使用代理
无需用户提示:
1. 复杂功能请求 - 使用 **planner** 代理
2. 刚编写/修改的代码 - 使用 **code-reviewer** 代理
3. Bug 修复或新功能 - 使用 **tdd-guide** 代理
4. 架构决策 - 使用 **architect** 代理
## 并行任务执行
对独立操作始终使用并行 Task 执行:
```markdown
# 好:并行执行
同时启动 3 个代理:
1. 代理 1认证模块安全分析
2. 代理 2缓存系统性能审查
3. 代理 3工具类型检查
# 坏:不必要的顺序
先代理 1然后代理 2然后代理 3
```
## 多视角分析
对于复杂问题,使用分角色子代理:
- 事实审查者
- 高级工程师
- 安全专家
- 一致性审查者
- 冗余检查者

124
rules/zh/code-review.md Normal file
View File

@@ -0,0 +1,124 @@
# 代码审查标准
## 目的
代码审查确保代码合并前的质量、安全性和可维护性。此规则定义何时以及如何进行代码审查。
## 何时审查
**强制审查触发条件:**
- 编写或修改代码后
- 提交到共享分支之前
- 更改安全敏感代码时(认证、支付、用户数据)
- 进行架构更改时
- 合并 pull request 之前
**审查前要求:**
在请求审查之前,确保:
- 所有自动化检查CI/CD已通过
- 合并冲突已解决
- 分支已与目标分支同步
## 审查检查清单
在标记代码完成之前:
- [ ] 代码可读且命名良好
- [ ] 函数聚焦(<50 行)
- [ ] 文件内聚(<800 行)
- [ ] 无深层嵌套(>4 层)
- [ ] 错误显式处理
- [ ] 无硬编码密钥或凭据
- [ ] 无 console.log 或调试语句
- [ ] 新功能有测试
- [ ] 测试覆盖率满足 80% 最低要求
## 安全审查触发条件
**停止并使用 security-reviewer 代理当:**
- 认证或授权代码
- 用户输入处理
- 数据库查询
- 文件系统操作
- 外部 API 调用
- 加密操作
- 支付或金融代码
## 审查严重级别
| 级别 | 含义 | 行动 |
|-------|---------|--------|
| CRITICAL关键 | 安全漏洞或数据丢失风险 | **阻止** - 合并前必须修复 |
| HIGH | Bug 或重大质量问题 | **警告** - 合并前应修复 |
| MEDIUM | 可维护性问题 | **信息** - 考虑修复 |
| LOW | 风格或次要建议 | **注意** - 可选 |
## 代理使用
使用这些代理进行代码审查:
| 代理 | 用途 |
|-------|--------|
| **code-reviewer** | 通用代码质量、模式、最佳实践 |
| **security-reviewer** | 安全漏洞、OWASP Top 10 |
| **typescript-reviewer** | TypeScript/JavaScript 特定问题 |
| **python-reviewer** | Python 特定问题 |
| **go-reviewer** | Go 特定问题 |
| **rust-reviewer** | Rust 特定问题 |
## 审查工作流
```
1. 运行 git diff 了解更改
2. 先检查安全检查清单
3. 审查代码质量检查清单
4. 运行相关测试
5. 验证覆盖率 >= 80%
6. 使用适当的代理进行详细审查
```
## 常见问题捕获
### 安全
- 硬编码凭据API 密钥、密码、令牌)
- SQL 注入(查询中的字符串拼接)
- XSS 漏洞(未转义的用户输入)
- 路径遍历(未净化的文件路径)
- CSRF 保护缺失
- 认证绕过
### 代码质量
- 大函数(>50 行)- 拆分为更小的
- 大文件(>800 行)- 提取模块
- 深层嵌套(>4 层)- 使用提前返回
- 缺少错误处理 - 显式处理
- 变更模式 - 优先使用不可变操作
- 缺少测试 - 添加测试覆盖
### 性能
- N+1 查询 - 使用 JOIN 或批处理
- 缺少分页 - 给查询添加 LIMIT
- 无界查询 - 添加约束
- 缺少缓存 - 缓存昂贵操作
## 批准标准
- **批准**:无关键或高优先级问题
- **警告**:仅有高优先级问题(谨慎合并)
- **阻止**:发现关键问题
## 与其他规则的集成
此规则与以下规则配合:
- [testing.md](testing.md) - 测试覆盖率要求
- [security.md](security.md) - 安全检查清单
- [git-workflow.md](git-workflow.md) - 提交标准
- [agents.md](agents.md) - 代理委托

48
rules/zh/coding-style.md Normal file
View File

@@ -0,0 +1,48 @@
# 编码风格
## 不可变性(关键)
始终创建新对象,永远不要修改现有对象:
```
// 伪代码
错误: modify(original, field, value) → 就地修改 original
正确: update(original, field, value) → 返回带有更改的新副本
```
原理:不可变数据防止隐藏的副作用,使调试更容易,并启用安全的并发。
## 文件组织
多个小文件 > 少量大文件:
- 高内聚,低耦合
- 典型 200-400 行,最多 800 行
- 从大模块中提取工具函数
- 按功能/领域组织,而非按类型
## 错误处理
始终全面处理错误:
- 在每一层显式处理错误
- 在面向 UI 的代码中提供用户友好的错误消息
- 在服务器端记录详细的错误上下文
- 永远不要静默吞掉错误
## 输入验证
始终在系统边界验证:
- 处理前验证所有用户输入
- 在可用的情况下使用基于模式的验证
- 快速失败并给出清晰的错误消息
- 永远不要信任外部数据API 响应、用户输入、文件内容)
## 代码质量检查清单
在标记工作完成前:
- [ ] 代码可读且命名良好
- [ ] 函数很小(<50 行)
- [ ] 文件聚焦(<800 行)
- [ ] 没有深层嵌套(>4 层)
- [ ] 正确的错误处理
- [ ] 没有硬编码值(使用常量或配置)
- [ ] 没有变更(使用不可变模式)

View File

@@ -0,0 +1,44 @@
# 开发工作流
> 此文件扩展 [common/git-workflow.md](./git-workflow.md),包含 git 操作之前的完整功能开发流程。
功能实现工作流描述了开发管道研究、规划、TDD、代码审查然后提交到 git。
## 功能实现工作流
0. **研究与重用** _(任何新实现前必需)_
- **GitHub 代码搜索优先:** 在编写任何新代码之前,运行 `gh search repos``gh search code` 查找现有实现、模板和模式。
- **库文档其次:** 使用 Context7 或主要供应商文档确认 API 行为、包使用和版本特定细节。
- **仅当前两者不足时使用 Exa** 在 GitHub 搜索和主要文档之后,使用 Exa 进行更广泛的网络研究或发现。
- **检查包注册表:** 在编写工具代码之前搜索 npm、PyPI、crates.io 和其他注册表。首选久经考验的库而非手工编写的解决方案。
- **搜索可适配的实现:** 寻找解决问题 80%+ 且可以分支、移植或包装的开源项目。
- 当满足需求时,优先采用或移植经验证的方法而非从头编写新代码。
1. **先规划**
- 使用 **planner** 代理创建实现计划
- 编码前生成规划文档PRD、架构、系统设计、技术文档、任务列表
- 识别依赖和风险
- 分解为阶段
2. **TDD 方法**
- 使用 **tdd-guide** 代理
- 先写测试RED
- 实现以通过测试GREEN
- 重构IMPROVE
- 验证 80%+ 覆盖率
3. **代码审查**
- 编写代码后立即使用 **code-reviewer** 代理
- 解决关键和高优先级问题
- 尽可能修复中优先级问题
4. **提交与推送**
- 详细的提交消息
- 遵循约定式提交格式
- 参见 [git-workflow.md](./git-workflow.md) 了解提交消息格式和 PR 流程
5. **审查前检查**
- 验证所有自动化检查CI/CD已通过
- 解决任何合并冲突
- 确保分支已与目标分支同步
- 仅在这些检查通过后请求审查

24
rules/zh/git-workflow.md Normal file
View File

@@ -0,0 +1,24 @@
# Git 工作流
## 提交消息格式
```
<类型>: <描述>
<可选正文>
```
类型feat, fix, refactor, docs, test, chore, perf, ci
注意:通过 ~/.claude/settings.json 全局禁用归属。
## Pull Request 工作流
创建 PR 时:
1. 分析完整提交历史(不仅是最新提交)
2. 使用 `git diff [base-branch]...HEAD` 查看所有更改
3. 起草全面的 PR 摘要
4. 包含带有 TODO 的测试计划
5. 如果是新分支,使用 `-u` 标志推送
> 对于 git 操作之前的完整开发流程规划、TDD、代码审查
> 参见 [development-workflow.md](./development-workflow.md)。

30
rules/zh/hooks.md Normal file
View File

@@ -0,0 +1,30 @@
# 钩子系统
## 钩子类型
- **PreToolUse**:工具执行前(验证、参数修改)
- **PostToolUse**:工具执行后(自动格式化、检查)
- **Stop**:会话结束时(最终验证)
## 自动接受权限
谨慎使用:
- 为可信、定义明确的计划启用
- 探索性工作时禁用
- 永远不要使用 dangerously-skip-permissions 标志
- 改为在 `~/.claude.json` 中配置 `allowedTools`
## TodoWrite 最佳实践
使用 TodoWrite 工具:
- 跟踪多步骤任务的进度
- 验证对指令的理解
- 启用实时引导
- 显示细粒度的实现步骤
待办列表揭示:
- 顺序错误的步骤
- 缺失的项目
- 多余的不必要项目
- 错误的粒度
- 误解的需求

31
rules/zh/patterns.md Normal file
View File

@@ -0,0 +1,31 @@
# 常用模式
## 骨架项目
实现新功能时:
1. 搜索久经考验的骨架项目
2. 使用并行代理评估选项:
- 安全性评估
- 可扩展性分析
- 相关性评分
- 实现规划
3. 克隆最佳匹配作为基础
4. 在经验证的结构内迭代
## 设计模式
### 仓储模式
将数据访问封装在一致的接口后面:
- 定义标准操作findAll、findById、create、update、delete
- 具体实现处理存储细节数据库、API、文件等
- 业务逻辑依赖抽象接口,而非存储机制
- 便于轻松切换数据源,并简化使用模拟的测试
### API 响应格式
对所有 API 响应使用一致的信封:
- 包含成功/状态指示器
- 包含数据负载(错误时可为空)
- 包含错误消息字段(成功时可为空)
- 包含分页响应的元数据total、page、limit

55
rules/zh/performance.md Normal file
View File

@@ -0,0 +1,55 @@
# 性能优化
## 模型选择策略
**Haiku 4.5**Sonnet 90% 的能力3 倍成本节省):
- 频繁调用的轻量级代理
- 结对编程和代码生成
- 多代理系统中的工作者代理
**Sonnet 4.6**(最佳编码模型):
- 主要开发工作
- 编排多代理工作流
- 复杂编码任务
**Opus 4.5**(最深度推理):
- 复杂架构决策
- 最大推理需求
- 研究和分析任务
## 上下文窗口管理
避免在上下文窗口的最后 20% 进行以下操作:
- 大规模重构
- 跨多个文件的功能实现
- 调试复杂交互
上下文敏感度较低的任务:
- 单文件编辑
- 独立工具创建
- 文档更新
- 简单 bug 修复
## 扩展思考 + 规划模式
扩展思考默认启用,为内部推理保留最多 31,999 个 token。
通过以下方式控制扩展思考:
- **切换**Option+TmacOS/ Alt+TWindows/Linux
- **配置**:在 `~/.claude/settings.json` 中设置 `alwaysThinkingEnabled`
- **预算上限**`export MAX_THINKING_TOKENS=10000`
- **详细模式**Ctrl+O 查看思考输出
对于需要深度推理的复杂任务:
1. 确保扩展思考已启用(默认开启)
2. 启用**规划模式**进行结构化方法
3. 使用多轮审查进行彻底分析
4. 使用分角色子代理获得多样化视角
## 构建排查
如果构建失败:
1. 使用 **build-error-resolver** 代理
2. 分析错误消息
3. 增量修复
4. 每次修复后验证

29
rules/zh/security.md Normal file
View File

@@ -0,0 +1,29 @@
# 安全指南
## 强制安全检查
在任何提交之前:
- [ ] 无硬编码密钥API 密钥、密码、令牌)
- [ ] 所有用户输入已验证
- [ ] SQL 注入防护(参数化查询)
- [ ] XSS 防护(净化 HTML
- [ ] CSRF 保护已启用
- [ ] 认证/授权已验证
- [ ] 所有端点启用速率限制
- [ ] 错误消息不泄露敏感数据
## 密钥管理
- 永远不要在源代码中硬编码密钥
- 始终使用环境变量或密钥管理器
- 启动时验证所需的密钥是否存在
- 轮换任何可能已暴露的密钥
## 安全响应协议
如果发现安全问题:
1. 立即停止
2. 使用 **security-reviewer** 代理
3. 在继续之前修复关键问题
4. 轮换任何已暴露的密钥
5. 审查整个代码库中的类似问题

29
rules/zh/testing.md Normal file
View File

@@ -0,0 +1,29 @@
# 测试要求
## 最低测试覆盖率80%
测试类型(全部必需):
1. **单元测试** - 单个函数、工具、组件
2. **集成测试** - API 端点、数据库操作
3. **E2E 测试** - 关键用户流程(框架根据语言选择)
## 测试驱动开发
强制工作流:
1. 先写测试RED
2. 运行测试 - 应该失败
3. 编写最小实现GREEN
4. 运行测试 - 应该通过
5. 重构IMPROVE
6. 验证覆盖率80%+
## 测试失败排查
1. 使用 **tdd-guide** 代理
2. 检查测试隔离
3. 验证模拟是否正确
4. 修复实现,而非测试(除非测试有误)
## 代理支持
- **tdd-guide** - 主动用于新功能,强制先写测试