Skip to content

Claude 概念完整指南

全面的参考指南,涵盖斜杠命令、子代理、记忆系统、MCP 协议和代理技能,包含表格、图表和实际示例。


目录

  1. 斜杠命令
  2. 子代理
  3. 记忆系统
  4. MCP 协议
  5. 代理技能
  6. 插件
  7. 钩子
  8. 检查点与回退
  9. 高级功能
  10. 对比与集成

斜杠命令

概述

斜杠命令是以 Markdown 文件形式存储的用户调用快捷方式,Claude Code 可以执行这些快捷方式。它们帮助团队标准化常用提示词和工作流。

架构

文件结构

命令组织表

位置范围可用性使用场景Git 追踪
.claude/commands/项目专用团队成员团队工作流,共享规范✅ 是
~/.claude/commands/个人单个用户跨项目的个人快捷方式❌ 否
子目录命名空间基于父级按类别组织✅ 是

功能与能力

功能示例是否支持
Shell 脚本执行bash scripts/deploy.sh✅ 是
文件引用@path/to/file.js✅ 是
Bash 集成$(git log --oneline)✅ 是
参数/pr --verbose✅ 是
MCP 命令/mcp__github__list_prs✅ 是

实际示例

示例 1:代码优化命令

文件: .claude/commands/optimize.md

markdown
---
name: Code Optimization
description: Analyze code for performance issues and suggest optimizations
tags: performance, analysis
---

# Code Optimization

Review the provided code for the following issues in order of priority:

1. **Performance bottlenecks** - identify O(n²) operations, inefficient loops
2. **Memory leaks** - find unreleased resources, circular references
3. **Algorithm improvements** - suggest better algorithms or data structures
4. **Caching opportunities** - identify repeated computations
5. **Concurrency issues** - find race conditions or threading problems

Format your response with:
- Issue severity (Critical/High/Medium/Low)
- Location in code
- Explanation
- Recommended fix with code example

用法:

bash
# 用户在 Claude Code 中输入
/optimize

# Claude 加载提示词并等待代码输入

示例 2:Pull Request 辅助命令

文件: .claude/commands/pr.md

markdown
---
name: Prepare Pull Request
description: Clean up code, stage changes, and prepare a pull request
tags: git, workflow
---

# Pull Request Preparation Checklist

Before creating a PR, execute these steps:

1. Run linting: `prettier --write .`
2. Run tests: `npm test`
3. Review git diff: `git diff HEAD`
4. Stage changes: `git add .`
5. Create commit message following conventional commits:
   - `fix:` for bug fixes
   - `feat:` for new features
   - `docs:` for documentation
   - `refactor:` for code restructuring
   - `test:` for test additions
   - `chore:` for maintenance

6. Generate PR summary including:
   - What changed
   - Why it changed
   - Testing performed
   - Potential impacts

用法:

bash
/pr

# Claude 执行检查清单并准备 PR

示例 3:层级文档生成器

文件: .claude/commands/docs/generate-api-docs.md

markdown
---
name: Generate API Documentation
description: Create comprehensive API documentation from source code
tags: documentation, api
---

# API Documentation Generator

Generate API documentation by:

1. Scanning all files in `/src/api/`
2. Extracting function signatures and JSDoc comments
3. Organizing by endpoint/module
4. Creating markdown with examples
5. Including request/response schemas
6. Adding error documentation

Output format:
- Markdown file in `/docs/api.md`
- Include curl examples for all endpoints
- Add TypeScript types

命令生命周期图

最佳实践

应该做 ✅不应该做 ❌
使用清晰、面向动作的命名为一次性任务创建命令
在描述中记录触发词在命令中构建复杂逻辑
保持命令专注于单一任务创建冗余命令
对项目命令进行版本控制硬编码敏感信息
在子目录中组织创建过长的命令列表
使用简单易读的提示词使用缩写或神秘的措辞

子代理

概述

子代理是具有隔离上下文窗口和自定义系统提示词的专业 AI 助手。它们在保持清晰关注点分离的同时实现委派任务执行。

架构图

子代理生命周期

子代理配置表

配置项类型用途示例
name字符串代理标识符code-reviewer
description字符串用途与触发词Comprehensive code quality analysis
tools列表/字符串允许的能力read, grep, diff, lint_runner
system_promptMarkdown行为指令自定义指南

工具访问层级

实际示例

示例 1:完整的子代理设置

文件: .claude/agents/code-reviewer.md

yaml
---
name: code-reviewer
description: Comprehensive code quality and maintainability analysis
tools: read, grep, diff, lint_runner
---

# Code Reviewer Agent

You are an expert code reviewer specializing in:
- Performance optimization
- Security vulnerabilities
- Code maintainability
- Testing coverage
- Design patterns

## Review Priorities (in order)

1. **Security Issues** - Authentication, authorization, data exposure
2. **Performance Problems** - O(n²) operations, memory leaks, inefficient queries
3. **Code Quality** - Readability, naming, documentation
4. **Test Coverage** - Missing tests, edge cases
5. **Design Patterns** - SOLID principles, architecture

## Review Output Format

For each issue:
- **Severity**: Critical / High / Medium / Low
- **Category**: Security / Performance / Quality / Testing / Design
- **Location**: File path and line number
- **Issue Description**: What's wrong and why
- **Suggested Fix**: Code example
- **Impact**: How this affects the system

## Example Review

### Issue: N+1 Query Problem
- **Severity**: High
- **Category**: Performance
- **Location**: src/user-service.ts:45
- **Issue**: Loop executes database query in each iteration
- **Fix**: Use JOIN or batch query

文件: .claude/agents/test-engineer.md

yaml
---
name: test-engineer
description: Test strategy, coverage analysis, and automated testing
tools: read, write, bash, grep
---

# Test Engineer Agent

You are expert at:
- Writing comprehensive test suites
- Ensuring high code coverage (>80%)
- Testing edge cases and error scenarios
- Performance benchmarking
- Integration testing

## Testing Strategy

1. **Unit Tests** - Individual functions/methods
2. **Integration Tests** - Component interactions
3. **End-to-End Tests** - Complete workflows
4. **Edge Cases** - Boundary conditions
5. **Error Scenarios** - Failure handling

## Test Output Requirements

- Use Jest for JavaScript/TypeScript
- Include setup/teardown for each test
- Mock external dependencies
- Document test purpose
- Include performance assertions when relevant

## Coverage Requirements

- Minimum 80% code coverage
- 100% for critical paths
- Report missing coverage areas

文件: .claude/agents/documentation-writer.md

yaml
---
name: documentation-writer
description: Technical documentation, API docs, and user guides
tools: read, write, grep
---

# Documentation Writer Agent

You create:
- API documentation with examples
- User guides and tutorials
- Architecture documentation
- Changelog entries
- Code comment improvements

## Documentation Standards

1. **Clarity** - Use simple, clear language
2. **Examples** - Include practical code examples
3. **Completeness** - Cover all parameters and returns
4. **Structure** - Use consistent formatting
5. **Accuracy** - Verify against actual code

## Documentation Sections

### For APIs
- Description
- Parameters (with types)
- Returns (with types)
- Throws (possible errors)
- Examples (curl, JavaScript, Python)
- Related endpoints

### For Features
- Overview
- Prerequisites
- Step-by-step instructions
- Expected outcomes
- Troubleshooting
- Related topics

示例 2:实际的子代理委派

markdown
# 场景:构建支付功能

## 用户请求
"构建一个与 Stripe 集成的安全支付处理功能"

## 主代理流程

1. **计划阶段**
   - 理解需求
   - 确定所需任务
   - 规划架构

2. **委派给代码审查员子代理**
   - 任务:"审查支付处理实现的安全性"
   - 上下文:认证、API 密钥、令牌处理
   - 审查内容:SQL 注入、密钥暴露、HTTPS 强制

3. **委派给测试工程师子代理**
   - 任务:"为支付流程创建全面测试"
   - 上下文:成功场景、失败、边缘情况
   - 创建测试:有效支付、拒绝卡、网络故障、Webhook

4. **委派给文档编写员子代理**
   - 任务:"记录支付 API 端点"
   - 上下文:请求/响应模式
   - 产出:带 curl 示例的 API 文档、错误代码

5. **综合**
   - 主代理收集所有输出
   - 整合发现
   - 向用户返回完整解决方案

示例 3:工具权限范围

限制性设置 — 仅限特定命令

yaml
---
name: secure-reviewer
description: Security-focused code review with minimal permissions
tools: read, grep
---

# Secure Code Reviewer

Reviews code for security vulnerabilities only.

This agent:
- ✅ Reads files to analyze
- ✅ Searches for patterns
- ❌ Cannot execute code
- ❌ Cannot modify files
- ❌ Cannot run tests

This ensures the reviewer doesn't accidentally break anything.

扩展设置 — 所有工具用于实现

yaml
---
name: implementation-agent
description: Full implementation capabilities for feature development
tools: read, write, bash, grep, edit, glob
---

# Implementation Agent

Builds features from specifications.

This agent:
- ✅ Reads specifications
- ✅ Writes new code files
- ✅ Runs build commands
- ✅ Searches codebase
- ✅ Edits existing files
- ✅ Finds files matching patterns

Full capabilities for independent feature development.

子代理上下文管理

何时使用子代理

场景使用子代理原因
步骤众多的复杂功能✅ 是分离关注点,防止上下文污染
快速代码审查❌ 否不必要的开销
并行任务执行✅ 是每个子代理有自己的上下文
需要专业能力✅ 是自定义系统提示词
长时间运行的分析✅ 是防止主上下文耗尽
单一任务❌ 否不必要地增加延迟

代理团队

代理团队协调多个代理共同处理相关任务。与一次委派给一个子代理不同,代理团队允许主代理编排一组代理,这些代理可以协作、共享中间结果,朝着共同目标努力。这对于大规模任务非常有用,例如全栈功能开发,其中前端代理、后端代理和测试代理并行工作。


记忆系统

概述

记忆系统使 Claude 能够跨会话和对话保留上下文。它以两种形式存在:claude.ai 中的自动综合,以及 Claude Code 中基于文件系统的 CLAUDE.md。

记忆架构

Claude Code 中的记忆层级(7 层)

Claude Code 从 7 个层级加载记忆,按优先级从高到低排列:

记忆位置表

层级位置范围优先级共享最适合
1. 托管策略企业管理员组织最高所有组织用户合规、安全策略
2. 项目./CLAUDE.md项目团队(Git)团队规范、架构
3. 项目规则.claude/rules/*.md项目团队(Git)模块化项目约定
4. 用户~/.claude/CLAUDE.md个人个人个人偏好
5. 用户规则~/.claude/rules/*.md个人个人个人规则模块
6. 本地.claude/local/CLAUDE.md本地不共享机器特定设置
7. 自动记忆自动会话最低个人学习到的偏好、模式

自动记忆

自动记忆自动捕获在会话期间观察到的用户偏好和模式。Claude 从你的交互中学习并记住:

  • 代码风格偏好
  • 你经常做出的修正
  • 框架和工具选择
  • 沟通风格偏好

自动记忆在后台工作,无需手动配置。

记忆更新生命周期

实际示例

示例 1:项目记忆结构

文件: ./CLAUDE.md

markdown
# Project Configuration

## Project Overview
- **Name**: E-commerce Platform
- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker
- **Team Size**: 5 developers
- **Deadline**: Q4 2025

## Architecture
@docs/architecture.md
@docs/api-standards.md
@docs/database-schema.md

## Development Standards

### Code Style
- Use Prettier for formatting
- Use ESLint with airbnb config
- Maximum line length: 100 characters
- Use 2-space indentation

### Naming Conventions
- **Files**: kebab-case (user-controller.js)
- **Classes**: PascalCase (UserService)
- **Functions/Variables**: camelCase (getUserById)
- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)
- **Database Tables**: snake_case (user_accounts)

### Git Workflow
- Branch names: `feature/description` or `fix/description`
- Commit messages: Follow conventional commits
- PR required before merge
- All CI/CD checks must pass
- Minimum 1 approval required

### Testing Requirements
- Minimum 80% code coverage
- All critical paths must have tests
- Use Jest for unit tests
- Use Cypress for E2E tests
- Test filenames: `*.test.ts` or `*.spec.ts`

### API Standards
- RESTful endpoints only
- JSON request/response
- Use HTTP status codes correctly
- Version API endpoints: `/api/v1/`
- Document all endpoints with examples

### Database
- Use migrations for schema changes
- Never hardcode credentials
- Use connection pooling
- Enable query logging in development
- Regular backups required

### Deployment
- Docker-based deployment
- Kubernetes orchestration
- Blue-green deployment strategy
- Automatic rollback on failure
- Database migrations run before deploy

## Common Commands

| Command | Purpose |
|---------|---------|
| `npm run dev` | Start development server |
| `npm test` | Run test suite |
| `npm run lint` | Check code style |
| `npm run build` | Build for production |
| `npm run migrate` | Run database migrations |

## Team Contacts
- Tech Lead: Sarah Chen (@sarah.chen)
- Product Manager: Mike Johnson (@mike.j)
- DevOps: Alex Kim (@alex.k)

## Known Issues & Workarounds
- PostgreSQL connection pooling limited to 20 during peak hours
- Workaround: Implement query queuing
- Safari 14 compatibility issues with async generators
- Workaround: Use Babel transpiler

## Related Projects
- Analytics Dashboard: `/projects/analytics`
- Mobile App: `/projects/mobile`
- Admin Panel: `/projects/admin`

示例 2:目录专用记忆

文件: ./src/api/CLAUDE.md

markdown
# API Module Standards

This file overrides root CLAUDE.md for everything in /src/api/

## API-Specific Standards

### Request Validation
- Use Zod for schema validation
- Always validate input
- Return 400 with validation errors
- Include field-level error details

### Authentication
- All endpoints require JWT token
- Token in Authorization header
- Token expires after 24 hours
- Implement refresh token mechanism

### Response Format

All responses must follow this structure:

```json
{
  "success": true,
  "data": { /* actual data */ },
  "timestamp": "2025-11-06T10:30:00Z",
  "version": "1.0"
}
```

### Error responses:
```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "User message",
    "details": { /* field errors */ }
  },
  "timestamp": "2025-11-06T10:30:00Z"
}
```

### Pagination
- Use cursor-based pagination (not offset)
- Include `hasMore` boolean
- Limit max page size to 100
- Default page size: 20

### Rate Limiting
- 1000 requests per hour for authenticated users
- 100 requests per hour for public endpoints
- Return 429 when exceeded
- Include retry-after header

### Caching
- Use Redis for session caching
- Cache duration: 5 minutes default
- Invalidate on write operations
- Tag cache keys with resource type

示例 3:个人记忆

文件: ~/.claude/CLAUDE.md

markdown
# My Development Preferences

## About Me
- **Experience Level**: 8 years full-stack development
- **Preferred Languages**: TypeScript, Python
- **Communication Style**: Direct, with examples
- **Learning Style**: Visual diagrams with code

## Code Preferences

### Error Handling
I prefer explicit error handling with try-catch blocks and meaningful error messages.
Avoid generic errors. Always log errors for debugging.

### Comments
Use comments for WHY, not WHAT. Code should be self-documenting.
Comments should explain business logic or non-obvious decisions.

### Testing
I prefer TDD (test-driven development).
Write tests first, then implementation.
Focus on behavior, not implementation details.

### Architecture
I prefer modular, loosely-coupled design.
Use dependency injection for testability.
Separate concerns (Controllers, Services, Repositories).

## Debugging Preferences
- Use console.log with prefix: `[DEBUG]`
- Include context: function name, relevant variables
- Use stack traces when available
- Always include timestamps in logs

## Communication
- Explain complex concepts with diagrams
- Show concrete examples before explaining theory
- Include before/after code snippets
- Summarize key points at the end

## Project Organization
I organize my projects as:
```
project/
  ├── src/
  │   ├── api/
  │   ├── services/
  │   ├── models/
  │   └── utils/
  ├── tests/
  ├── docs/
  └── docker/
```

## Tooling
- **IDE**: VS Code with vim keybindings
- **Terminal**: Zsh with Oh-My-Zsh
- **Format**: Prettier (100 char line length)
- **Linter**: ESLint with airbnb config
- **Test Framework**: Jest with React Testing Library

示例 4:会话中更新记忆

会话交互:

markdown
用户:记住我更倾向于为所有新组件使用 React hooks
      而不是 class 组件。

Claude:我将把这添加到你的记忆中。应该保存到哪个记忆文件?
        1. 项目记忆(./CLAUDE.md)
        2. 个人记忆(~/.claude/CLAUDE.md)

用户:项目记忆

Claude:✅ 记忆已保存!

添加到 ./CLAUDE.md:
---

### Component Development
- Use functional components with React Hooks
- Prefer hooks over class components
- Custom hooks for reusable logic
- Use useCallback for event handlers
- Use useMemo for expensive computations

Claude Web/Desktop 中的记忆

记忆综合时间线

记忆摘要示例:

markdown
## Claude 对用户的记忆

### 职业背景
- 拥有 8 年经验的高级全栈开发者
- 专注于 TypeScript/Node.js 后端和 React 前端
- 活跃的开源贡献者
- 对 AI 和机器学习感兴趣

### 项目背景
- 目前在构建电商平台
- 技术栈:Node.js、PostgreSQL、React 18、Docker
- 与 5 名开发者团队合作
- 使用 CI/CD 和蓝绿部署

### 沟通偏好
- 喜欢直接、简洁的解释
- 喜欢可视化图表和示例
- 欣赏代码片段
- 在注释中解释业务逻辑

### 当前目标
- 提升 API 性能
- 将测试覆盖率提高到 90%
- 实现缓存策略
- 记录架构

记忆功能对比

功能Claude Web/DesktopClaude Code(CLAUDE.md)
自动综合✅ 每 24 小时❌ 手动
跨项目✅ 共享❌ 项目专用
团队访问✅ 共享项目✅ Git 追踪
可搜索✅ 内置✅ 通过 /memory
可编辑✅ 聊天中✅ 直接编辑文件
导入/导出✅ 是✅ 复制/粘贴
持久化✅ 24 小时以上✅ 无限期

MCP 协议

概述

MCP(模型上下文协议)是 Claude 访问外部工具、API 和实时数据源的标准化方式。与记忆系统不同,MCP 协议提供对动态数据的实时访问。

MCP 架构

MCP 生态系统

MCP 设置流程

可用 MCP 服务器表

MCP 服务器用途常用工具认证实时
Filesystem文件操作read, write, deleteOS 权限✅ 是
GitHub仓库管理list_prs, create_issue, pushOAuth✅ 是
Slack团队通信send_message, list_channelsToken✅ 是
DatabaseSQL 查询query, insert, update凭据✅ 是
Google Docs文档访问read, write, shareOAuth✅ 是
Asana项目管理create_task, update_statusAPI Key✅ 是
Stripe支付数据list_charges, create_invoiceAPI Key✅ 是
Memory持久记忆store, retrieve, delete本地❌ 否

实际示例

示例 1:GitHub MCP 配置

文件: .mcp.json(项目范围)或 ~/.claude.json(用户范围)

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

可用的 GitHub MCP 工具:

markdown
# GitHub MCP Tools

## Pull Request Management
- `list_prs` - List all PRs in repository
- `get_pr` - Get PR details including diff
- `create_pr` - Create new PR
- `update_pr` - Update PR description/title
- `merge_pr` - Merge PR to main branch
- `review_pr` - Add review comments

Example request:
```
/mcp__github__get_pr 456

# Returns:
Title: Add dark mode support
Author: @alice
Description: Implements dark theme using CSS variables
Status: OPEN
Reviewers: @bob, @charlie
```

## Issue Management
- `list_issues` - List all issues
- `get_issue` - Get issue details
- `create_issue` - Create new issue
- `close_issue` - Close issue
- `add_comment` - Add comment to issue

## Repository Information
- `get_repo_info` - Repository details
- `list_files` - File tree structure
- `get_file_content` - Read file contents
- `search_code` - Search across codebase

## Commit Operations
- `list_commits` - Commit history
- `get_commit` - Specific commit details
- `create_commit` - Create new commit

示例 2:数据库 MCP 设置

配置:

json
{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-database"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost/mydb"
      }
    }
  }
}

使用示例:

markdown
用户:查找所有订单超过 10 笔的用户

Claude:我将查询你的数据库以找到相关信息。

# 使用 MCP 数据库工具:
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id
HAVING COUNT(o.id) > 10
ORDER BY order_count DESC;

# 结果:
- Alice:15 笔订单
- Bob:12 笔订单
- Charlie:11 笔订单

示例 3:多 MCP 工作流

场景:日报生成

markdown
# 使用多个 MCP 的日报工作流

## 设置
1. GitHub MCP — 获取 PR 指标
2. Database MCP — 查询销售数据
3. Slack MCP — 发布报告
4. Filesystem MCP — 保存报告

## 工作流

### 步骤 1:获取 GitHub 数据
/mcp__github__list_prs completed:true last:7days

输出:
- 总 PR 数:42
- 平均合并时间:2.3 小时
- 审查周转时间:1.1 小时

### 步骤 2:查询数据库
SELECT COUNT(*) as sales, SUM(amount) as revenue
FROM orders
WHERE created_at > NOW() - INTERVAL '1 day'

输出:
- 销售:247
- 收入:$12,450

### 步骤 3:生成报告
将数据合并为 HTML 报告

### 步骤 4:保存到文件系统
将 report.html 写入 /reports/

### 步骤 5:发布到 Slack
将摘要发送到 #daily-reports 频道

最终输出:
✅ 报告已生成并发布
📊 本周合并了 47 个 PR
💰 日销售额 $12,450

示例 4:Filesystem MCP 操作

配置:

json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
    }
  }
}

可用操作:

操作命令用途
列出文件ls ~/projects显示目录内容
读取文件cat src/main.ts读取文件内容
写入文件create docs/api.md创建新文件
编辑文件edit src/app.ts修改文件
搜索grep "async function"在文件中搜索
删除rm old-file.js删除文件

MCP 与记忆系统:决策矩阵

请求/响应模式


代理技能

概述

代理技能是打包为文件夹的可复用、模型调用能力,包含指令、脚本和资源。Claude 自动检测并使用相关技能。

技能架构

技能加载流程

技能类型与位置表

类型位置范围共享同步最适合
预置内置全局所有用户自动文档创建
个人~/.claude/skills/个人手动个人自动化
项目.claude/skills/团队Git团队规范
插件通过插件安装不定视情况自动集成功能

预置技能

内置技能

Claude Code 现在包含 5 个开箱即用的内置技能:

技能命令用途
Simplify/simplify简化复杂代码或解释
Batch/batch对多个文件或条目执行批量操作
Debug/debug系统化调试问题并进行根因分析
Loop/loop按计时器安排周期性任务
Claude API/claude-api直接与 Anthropic API 交互

这些内置技能始终可用,无需安装或配置。

实际示例

示例 1:自定义代码审查技能

目录结构:

~/.claude/skills/code-review/
├── SKILL.md
├── templates/
│   ├── review-checklist.md
│   └── finding-template.md
└── scripts/
    ├── analyze-metrics.py
    └── compare-complexity.py

文件: ~/.claude/skills/code-review/SKILL.md

yaml
---
name: Code Review Specialist
description: Comprehensive code review with security, performance, and quality analysis
version: "1.0.0"
tags:
  - code-review
  - quality
  - security
when_to_use: When users ask to review code, analyze code quality, or evaluate pull requests
effort: high
shell: bash
---

# Code Review Skill

This skill provides comprehensive code review capabilities focusing on:

1. **Security Analysis**
   - Authentication/authorization issues
   - Data exposure risks
   - Injection vulnerabilities
   - Cryptographic weaknesses
   - Sensitive data logging

2. **Performance Review**
   - Algorithm efficiency (Big O analysis)
   - Memory optimization
   - Database query optimization
   - Caching opportunities
   - Concurrency issues

3. **Code Quality**
   - SOLID principles
   - Design patterns
   - Naming conventions
   - Documentation
   - Test coverage

4. **Maintainability**
   - Code readability
   - Function size (should be < 50 lines)
   - Cyclomatic complexity
   - Dependency management
   - Type safety

## Review Template

For each piece of code reviewed, provide:

### Summary
- Overall quality assessment (1-5)
- Key findings count
- Recommended priority areas

### Critical Issues (if any)
- **Issue**: Clear description
- **Location**: File and line number
- **Impact**: Why this matters
- **Severity**: Critical/High/Medium
- **Fix**: Code example

### Findings by Category

#### Security (if issues found)
List security vulnerabilities with examples

#### Performance (if issues found)
List performance problems with complexity analysis

#### Quality (if issues found)
List code quality issues with refactoring suggestions

#### Maintainability (if issues found)
List maintainability problems with improvements

Python Script: analyze-metrics.py

python
#!/usr/bin/env python3
import re
import sys

def analyze_code_metrics(code):
    """Analyze code for common metrics."""

    # Count functions
    functions = len(re.findall(r'^def\s+\w+', code, re.MULTILINE))

    # Count classes
    classes = len(re.findall(r'^class\s+\w+', code, re.MULTILINE))

    # Average line length
    lines = code.split('\n')
    avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0

    # Estimate complexity
    complexity = len(re.findall(r'\b(if|elif|else|for|while|and|or)\b', code))

    return {
        'functions': functions,
        'classes': classes,
        'avg_line_length': avg_length,
        'complexity_score': complexity
    }

if __name__ == '__main__':
    with open(sys.argv[1], 'r') as f:
        code = f.read()
    metrics = analyze_code_metrics(code)
    for key, value in metrics.items():
        print(f"{key}: {value:.2f}")

Python Script: compare-complexity.py

python
#!/usr/bin/env python3
"""
Compare cyclomatic complexity of code before and after changes.
Helps identify if refactoring actually simplifies code structure.
"""

import re
import sys
from typing import Dict, Tuple

class ComplexityAnalyzer:
    """Analyze code complexity metrics."""

    def __init__(self, code: str):
        self.code = code
        self.lines = code.split('\n')

    def calculate_cyclomatic_complexity(self) -> int:
        """
        Calculate cyclomatic complexity using McCabe's method.
        Count decision points: if, elif, else, for, while, except, and, or
        """
        complexity = 1  # Base complexity

        # Count decision points
        decision_patterns = [
            r'\bif\b',
            r'\belif\b',
            r'\bfor\b',
            r'\bwhile\b',
            r'\bexcept\b',
            r'\band\b(?!$)',
            r'\bor\b(?!$)'
        ]

        for pattern in decision_patterns:
            matches = re.findall(pattern, self.code)
            complexity += len(matches)

        return complexity

    def calculate_cognitive_complexity(self) -> int:
        """
        Calculate cognitive complexity - how hard is it to understand?
        Based on nesting depth and control flow.
        """
        cognitive = 0
        nesting_depth = 0

        for line in self.lines:
            # Track nesting depth
            if re.search(r'^\s*(if|for|while|def|class|try)\b', line):
                nesting_depth += 1
                cognitive += nesting_depth
            elif re.search(r'^\s*(elif|else|except|finally)\b', line):
                cognitive += nesting_depth

            # Reduce nesting when unindenting
            if line and not line[0].isspace():
                nesting_depth = 0

        return cognitive

    def calculate_maintainability_index(self) -> float:
        """
        Maintainability Index ranges from 0-100.
        > 85: Excellent
        > 65: Good
        > 50: Fair
        < 50: Poor
        """
        lines = len(self.lines)
        cyclomatic = self.calculate_cyclomatic_complexity()
        cognitive = self.calculate_cognitive_complexity()

        # Simplified MI calculation
        mi = 171 - 5.2 * (cyclomatic / lines) - 0.23 * (cognitive) - 16.2 * (lines / 1000)

        return max(0, min(100, mi))

    def get_complexity_report(self) -> Dict:
        """Generate comprehensive complexity report."""
        return {
            'cyclomatic_complexity': self.calculate_cyclomatic_complexity(),
            'cognitive_complexity': self.calculate_cognitive_complexity(),
            'maintainability_index': round(self.calculate_maintainability_index(), 2),
            'lines_of_code': len(self.lines),
            'avg_line_length': round(sum(len(l) for l in self.lines) / len(self.lines), 2) if self.lines else 0
        }


def compare_files(before_file: str, after_file: str) -> None:
    """Compare complexity metrics between two code versions."""

    with open(before_file, 'r') as f:
        before_code = f.read()

    with open(after_file, 'r') as f:
        after_code = f.read()

    before_analyzer = ComplexityAnalyzer(before_code)
    after_analyzer = ComplexityAnalyzer(after_code)

    before_metrics = before_analyzer.get_complexity_report()
    after_metrics = after_analyzer.get_complexity_report()

    print("=" * 60)
    print("CODE COMPLEXITY COMPARISON")
    print("=" * 60)

    print("\nBEFORE:")
    print(f"  Cyclomatic Complexity:    {before_metrics['cyclomatic_complexity']}")
    print(f"  Cognitive Complexity:     {before_metrics['cognitive_complexity']}")
    print(f"  Maintainability Index:    {before_metrics['maintainability_index']}")
    print(f"  Lines of Code:            {before_metrics['lines_of_code']}")
    print(f"  Avg Line Length:          {before_metrics['avg_line_length']}")

    print("\nAFTER:")
    print(f"  Cyclomatic Complexity:    {after_metrics['cyclomatic_complexity']}")
    print(f"  Cognitive Complexity:     {after_metrics['cognitive_complexity']}")
    print(f"  Maintainability Index:    {after_metrics['maintainability_index']}")
    print(f"  Lines of Code:            {after_metrics['lines_of_code']}")
    print(f"  Avg Line Length:          {after_metrics['avg_line_length']}")

    print("\nCHANGES:")
    cyclomatic_change = after_metrics['cyclomatic_complexity'] - before_metrics['cyclomatic_complexity']
    cognitive_change = after_metrics['cognitive_complexity'] - before_metrics['cognitive_complexity']
    mi_change = after_metrics['maintainability_index'] - before_metrics['maintainability_index']
    loc_change = after_metrics['lines_of_code'] - before_metrics['lines_of_code']

    print(f"  Cyclomatic Complexity:    {cyclomatic_change:+d}")
    print(f"  Cognitive Complexity:     {cognitive_change:+d}")
    print(f"  Maintainability Index:    {mi_change:+.2f}")
    print(f"  Lines of Code:            {loc_change:+d}")

    print("\nASSESSMENT:")
    if mi_change > 0:
        print("  ✅ Code is MORE maintainable")
    elif mi_change < 0:
        print("  ⚠️  Code is LESS maintainable")
    else:
        print("  ➡️  Maintainability unchanged")

    if cyclomatic_change < 0:
        print("  ✅ Complexity DECREASED")
    elif cyclomatic_change > 0:
        print("  ⚠️  Complexity INCREASED")
    else:
        print("  ➡️  Complexity unchanged")

    print("=" * 60)


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage: python compare-complexity.py <before_file> <after_file>")
        sys.exit(1)

    compare_files(sys.argv[1], sys.argv[2])

Template: review-checklist.md

markdown
# Code Review Checklist

## Security Checklist
- [ ] No hardcoded credentials or secrets
- [ ] Input validation on all user inputs
- [ ] SQL injection prevention (parameterized queries)
- [ ] CSRF protection on state-changing operations
- [ ] XSS prevention with proper escaping
- [ ] Authentication checks on protected endpoints
- [ ] Authorization checks on resources
- [ ] Secure password hashing (bcrypt, argon2)
- [ ] No sensitive data in logs
- [ ] HTTPS enforced

## Performance Checklist
- [ ] No N+1 queries
- [ ] Appropriate use of indexes
- [ ] Caching implemented where beneficial
- [ ] No blocking operations on main thread
- [ ] Async/await used correctly
- [ ] Large datasets paginated
- [ ] Database connections pooled
- [ ] Regular expressions optimized
- [ ] No unnecessary object creation
- [ ] Memory leaks prevented

## Quality Checklist
- [ ] Functions < 50 lines
- [ ] Clear variable naming
- [ ] No duplicate code
- [ ] Proper error handling
- [ ] Comments explain WHY, not WHAT
- [ ] No console.logs in production
- [ ] Type checking (TypeScript/JSDoc)
- [ ] SOLID principles followed
- [ ] Design patterns applied correctly
- [ ] Self-documenting code

## Testing Checklist
- [ ] Unit tests written
- [ ] Edge cases covered
- [ ] Error scenarios tested
- [ ] Integration tests present
- [ ] Coverage > 80%
- [ ] No flaky tests
- [ ] Mock external dependencies
- [ ] Clear test names

Template: finding-template.md

markdown
# Code Review Finding Template

Use this template when documenting each issue found during code review.

---

## Issue: [TITLE]

### Severity
- [ ] Critical (blocks deployment)
- [ ] High (should fix before merge)
- [ ] Medium (should fix soon)
- [ ] Low (nice to have)

### Category
- [ ] Security
- [ ] Performance
- [ ] Code Quality
- [ ] Maintainability
- [ ] Testing
- [ ] Design Pattern
- [ ] Documentation

### Location
**File:** `src/components/UserCard.tsx`

**Lines:** 45-52

**Function/Method:** `renderUserDetails()`

### Issue Description

**What:** Describe what the issue is.

**Why it matters:** Explain the impact and why this needs to be fixed.

**Current behavior:** Show the problematic code or behavior.

**Expected behavior:** Describe what should happen instead.

### Code Example

#### Current (Problematic)

```typescript
// Shows the N+1 query problem
const users = fetchUsers();
users.forEach(user => {
  const posts = fetchUserPosts(user.id); // Query per user!
  renderUserPosts(posts);
});
```

#### Suggested Fix

```typescript
// Optimized with JOIN query
const usersWithPosts = fetchUsersWithPosts();
usersWithPosts.forEach(({ user, posts }) => {
  renderUserPosts(posts);
});
```

### Impact Analysis

| Aspect | Impact | Severity |
|--------|--------|----------|
| Performance | 100+ queries for 20 users | High |
| User Experience | Slow page load | High |
| Scalability | Breaks at scale | Critical |
| Maintainability | Hard to debug | Medium |

### Related Issues

- Similar issue in `AdminUserList.tsx` line 120
- Related PR: #456
- Related issue: #789

### Additional Resources

- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem)
- [Database Join Documentation](https://docs.example.com/joins)
- [Performance Optimization Guide](./docs/performance.md)

### Reviewer Notes

- This is a common pattern in this codebase
- Consider adding this to the code style guide
- Might be worth creating a helper function

### Author Response (for feedback)

*To be filled by the code author:*

- [ ] Fix implemented in commit: `abc123`
- [ ] Fix status: Complete / In Progress / Needs Discussion
- [ ] Questions or concerns: (describe)

---

## Finding Statistics (for Reviewer)

When reviewing multiple findings, track:

- **Total Issues Found:** X
- **Critical:** X
- **High:** X
- **Medium:** X
- **Low:** X

**Recommendation:** ✅ Approve / ⚠️ Request Changes / 🔄 Needs Discussion

**Overall Code Quality:** 1-5 stars

使用示例

markdown
用户:审查这段 React 组件代码

Claude:我将使用我的代码审查技能进行全面代码审查。

[加载 SKILL.md]
[对照检查清单分析代码]
[运行 Python 指标脚本]
[应用模板]

## 代码审查结果

### 摘要
质量评分:3.5/5
关键发现:7 项
优先改进区域:性能优化、错误处理

### 关键问题:1 个

**问题**:N+1 查询问题
**位置**:UserComponent.tsx,第 45-52 行
**影响**:20 个用户列表触发 100+ 次数据库查询
**严重性**:高
**修复**
```javascript
// Before: N+1 queries
const users = fetchUsers();
users.forEach(user => fetchUserPosts(user.id)); // 20+ queries

// After: Single query with JOIN
const users = fetchUsersWithPosts(); // 1 query
```

### 性能发现
- 大列表缺少分页
- 建议:对列表项使用 React.memo()
- 数据库查询:可通过索引优化

### 质量发现
- 第 20 行的函数有 127 行(最大:50 行)
- 缺少错误边界
- Props 应有 TypeScript 类型

示例 2:品牌声音技能

目录结构:

.claude/skills/brand-voice/
├── SKILL.md
├── brand-guidelines.md
├── tone-examples.md
└── templates/
    ├── email-template.txt
    ├── social-post-template.txt
    └── blog-post-template.md

文件: .claude/skills/brand-voice/SKILL.md

yaml
---
name: Brand Voice Consistency
description: Ensure all communication matches brand voice and tone guidelines
tags:
  - brand
  - writing
  - consistency
when_to_use: When creating marketing copy, customer communications, or public-facing content
---

# Brand Voice Skill

## Overview
This skill ensures all communications maintain consistent brand voice, tone, and messaging.

## Brand Identity

### Mission
Help teams automate their development workflows with AI

### Values
- **Simplicity**: Make complex things simple
- **Reliability**: Rock-solid execution
- **Empowerment**: Enable human creativity

### Tone of Voice
- **Friendly but professional** - approachable without being casual
- **Clear and concise** - avoid jargon, explain technical concepts simply
- **Confident** - we know what we're doing
- **Empathetic** - understand user needs and pain points

## Writing Guidelines

### Do's ✅
- Use "you" when addressing readers
- Use active voice: "Claude generates reports" not "Reports are generated by Claude"
- Start with value proposition
- Use concrete examples
- Keep sentences under 20 words
- Use lists for clarity
- Include calls-to-action

### Don'ts ❌
- Don't use corporate jargon
- Don't patronize or oversimplify
- Don't use "we believe" or "we think"
- Don't use ALL CAPS except for emphasis
- Don't create walls of text
- Don't assume technical knowledge

## Vocabulary

### ✅ Preferred Terms
- Claude (not "the Claude AI")
- Code generation (not "auto-coding")
- Agent (not "bot")
- Streamline (not "revolutionize")
- Integrate (not "synergize")

### ❌ Avoid Terms
- "Cutting-edge" (overused)
- "Game-changer" (vague)
- "Leverage" (corporate-speak)
- "Utilize" (use "use")
- "Paradigm shift" (unclear)

示例

✅ 好示例

"Claude automates your code review process. Instead of manually checking each PR, Claude reviews security, performance, and quality—saving your team hours every week."

为什么有效:清晰的价值主张,具体收益,面向行动

❌ 坏示例

"Claude leverages cutting-edge AI to provide comprehensive software development solutions."

为什么无效:模糊、充斥企业术语、无具体价值

Template: Email

Subject: [Clear, benefit-driven subject]

Hi [Name],

[Opening: What's the value for them]

[Body: How it works / What they'll get]

[Specific example or benefit]

[Call to action: Clear next step]

Best regards,
[Name]

Template: Social Media

[Hook: Grab attention in first line]
[2-3 lines: Value or interesting fact]
[Call to action: Link, question, or engagement]
[Emoji: 1-2 max for visual interest]

File: tone-examples.md

Exciting announcement:
"Save 8 hours per week on code reviews. Claude reviews your PRs automatically."

Empathetic support:
"We know deployments can be stressful. Claude handles testing so you don't have to worry."

Confident product feature:
"Claude doesn't just suggest code. It understands your architecture and maintains consistency."

Educational blog post:
"Let's explore how agents improve code review workflows. Here's what we learned..."

示例 3:文档生成器技能

文件: .claude/skills/doc-generator/SKILL.md

yaml
---
name: API Documentation Generator
description: Generate comprehensive, accurate API documentation from source code
version: "1.0.0"
tags:
  - documentation
  - api
  - automation
when_to_use: When creating or updating API documentation
---

# API Documentation Generator Skill

## Generates

- OpenAPI/Swagger specifications
- API endpoint documentation
- SDK usage examples
- Integration guides
- Error code references
- Authentication guides

## Documentation Structure

### For Each Endpoint

```markdown
## GET /api/v1/users/:id

### Description
Brief explanation of what this endpoint does

### Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| id | string | Yes | User ID |

### Response

**200 Success**
```json
{
  "id": "usr_123",
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2025-01-15T10:30:00Z"
}
```

**404 Not Found**
```json
{
  "error": "USER_NOT_FOUND",
  "message": "User does not exist"
}
```

### Examples

**cURL**
```bash
curl -X GET "https://api.example.com/api/v1/users/usr_123" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

**JavaScript**
```javascript
const user = await fetch('/api/v1/users/usr_123', {
  headers: { 'Authorization': 'Bearer token' }
}).then(r => r.json());
```

**Python**
```python
response = requests.get(
    'https://api.example.com/api/v1/users/usr_123',
    headers={'Authorization': 'Bearer token'}
)
user = response.json()
```

## Python Script: generate-docs.py

```python
#!/usr/bin/env python3
import ast
import json
from typing import Dict, List

class APIDocExtractor(ast.NodeVisitor):
    """Extract API documentation from Python source code."""

    def __init__(self):
        self.endpoints = []

    def visit_FunctionDef(self, node):
        """Extract function documentation."""
        if node.name.startswith('get_') or node.name.startswith('post_'):
            doc = ast.get_docstring(node)
            endpoint = {
                'name': node.name,
                'docstring': doc,
                'params': [arg.arg for arg in node.args.args],
                'returns': self._extract_return_type(node)
            }
            self.endpoints.append(endpoint)
        self.generic_visit(node)

    def _extract_return_type(self, node):
        """Extract return type from function annotation."""
        if node.returns:
            return ast.unparse(node.returns)
        return "Any"

def generate_markdown_docs(endpoints: List[Dict]) -> str:
    """Generate markdown documentation from endpoints."""
    docs = "# API Documentation\n\n"

    for endpoint in endpoints:
        docs += f"## {endpoint['name']}\n\n"
        docs += f"{endpoint['docstring']}\n\n"
        docs += f"**Parameters**: {', '.join(endpoint['params'])}\n\n"
        docs += f"**Returns**: {endpoint['returns']}\n\n"
        docs += "---\n\n"

    return docs

if __name__ == '__main__':
    import sys
    with open(sys.argv[1], 'r') as f:
        tree = ast.parse(f.read())

    extractor = APIDocExtractor()
    extractor.visit(tree)

    markdown = generate_markdown_docs(extractor.endpoints)
    print(markdown)

技能发现与调用

技能与其他功能对比


Claude Code 插件

概述

Claude Code 插件是自定义功能的打包集合(斜杠命令、子代理、MCP 服务器和钩子),通过单个命令安装。它们是最高级别的扩展机制——将多个功能组合成连贯的可共享包。

架构

插件加载流程

插件类型与分发

类型范围共享权威方示例
官方全局所有用户AnthropicPR Review、Security Guidance
社区公开所有用户社区DevOps、Data Science
组织内部团队成员公司内部规范、工具
个人个人单个用户开发者自定义工作流

插件定义结构

yaml
---
name: plugin-name
version: "1.0.0"
description: "What this plugin does"
author: "Your Name"
license: MIT

# Plugin metadata
tags:
  - category
  - use-case

# Requirements
requires:
  - claude-code: ">=1.0.0"

# Components bundled
components:
  - type: commands
    path: commands/
  - type: agents
    path: agents/
  - type: mcp
    path: mcp/
  - type: hooks
    path: hooks/

# Configuration
config:
  auto_load: true
  enabled_by_default: true
---

插件结构

my-plugin/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   ├── task-1.md
│   ├── task-2.md
│   └── workflows/
├── agents/
│   ├── specialist-1.md
│   ├── specialist-2.md
│   └── configs/
├── skills/
│   ├── skill-1.md
│   └── skill-2.md
├── hooks/
│   └── hooks.json
├── .mcp.json
├── .lsp.json
├── settings.json
├── templates/
│   └── issue-template.md
├── scripts/
│   ├── helper-1.sh
│   └── helper-2.py
├── docs/
│   ├── README.md
│   └── USAGE.md
└── tests/
    └── plugin.test.js

实际示例

示例 1:PR Review 插件

文件: .claude-plugin/plugin.json

json
{
  "name": "pr-review",
  "version": "1.0.0",
  "description": "Complete PR review workflow with security, testing, and docs",
  "author": {
    "name": "Anthropic"
  },
  "license": "MIT"
}

文件: commands/review-pr.md

markdown
---
name: Review PR
description: Start comprehensive PR review with security and testing checks
---

# PR Review

This command initiates a complete pull request review including:

1. Security analysis
2. Test coverage verification
3. Documentation updates
4. Code quality checks
5. Performance impact assessment

文件: agents/security-reviewer.md

yaml
---
name: security-reviewer
description: Security-focused code review
tools: read, grep, diff
---

# Security Reviewer

Specializes in finding security vulnerabilities:
- Authentication/authorization issues
- Data exposure
- Injection attacks
- Secure configuration

安装:

bash
/plugin install pr-review

# 结果:
# ✅ 3 个斜杠命令已安装
# ✅ 3 个子代理已配置
# ✅ 2 个 MCP 服务器已连接
# ✅ 4 个钩子已注册
# ✅ 准备就绪!

示例 2:DevOps 插件

组件:

devops-automation/
├── commands/
│   ├── deploy.md
│   ├── rollback.md
│   ├── status.md
│   └── incident.md
├── agents/
│   ├── deployment-specialist.md
│   ├── incident-commander.md
│   └── alert-analyzer.md
├── mcp/
│   ├── github-config.json
│   ├── kubernetes-config.json
│   └── prometheus-config.json
├── hooks/
│   ├── pre-deploy.js
│   ├── post-deploy.js
│   └── on-error.js
└── scripts/
    ├── deploy.sh
    ├── rollback.sh
    └── health-check.sh

示例 3:Documentation 插件

打包组件:

documentation/
├── commands/
│   ├── generate-api-docs.md
│   ├── generate-readme.md
│   ├── sync-docs.md
│   └── validate-docs.md
├── agents/
│   ├── api-documenter.md
│   ├── code-commentator.md
│   └── example-generator.md
├── mcp/
│   ├── github-docs-config.json
│   └── slack-announce-config.json
└── templates/
    ├── api-endpoint.md
    ├── function-docs.md
    └── adr-template.md

插件市场

插件安装与生命周期

插件功能对比

功能斜杠命令技能子代理插件
安装手动复制手动复制手动配置一条命令
设置时间5 分钟10 分钟15 分钟2 分钟
打包单文件单文件单文件多文件
版本控制手动手动手动自动
团队共享复制文件复制文件复制文件安装 ID
更新手动手动手动自动可用
依赖项可能有
市场
分发仓库仓库仓库市场

插件使用场景

使用场景建议原因
团队入职✅ 使用插件即时设置,所有配置
框架设置✅ 使用插件打包框架特定命令
企业规范✅ 使用插件集中分发,版本控制
快速任务自动化❌ 使用命令过于复杂
单域专业能力❌ 使用技能太重,改用技能
专业分析❌ 使用子代理手动创建或使用技能
实时数据访问❌ 使用 MCP**独立使用,不要打包

何时创建插件

发布插件

发布步骤:

  1. 创建包含所有组件的插件结构
  2. 编写 .claude-plugin/plugin.json 清单
  3. 创建带文档的 README.md
  4. 通过 /plugin install ./my-plugin 本地测试
  5. 提交到插件市场
  6. 审核并批准
  7. 在市场上发布
  8. 用户可以通过一条命令安装

提交示例:

markdown
# PR Review Plugin

## Description
Complete PR review workflow with security, testing, and documentation checks.

## What's Included
- 3 slash commands for different review types
- 3 specialized subagents
- GitHub and CodeQL MCP integration
- Automated security scanning hooks

## Installation
```bash
/plugin install pr-review
```

## Features
✅ Security analysis
✅ Test coverage checking
✅ Documentation verification
✅ Code quality assessment
✅ Performance impact analysis

## Usage
```bash
/review-pr
/check-security
/check-tests
```

## Requirements
- Claude Code 1.0+
- GitHub access
- CodeQL (optional)

插件与手动配置对比

手动设置(2 小时以上):

  • 逐一安装斜杠命令
  • 单独创建子代理
  • 分别配置 MCP
  • 手动设置钩子
  • 记录所有内容
  • 与团队共享(希望他们配置正确)

使用插件(2 分钟):

bash
/plugin install pr-review
# ✅ 所有内容已安装并配置
# ✅ 立即可用
# ✅ 团队可以复现完全相同的设置

对比与集成

功能对比矩阵

功能调用方式持久化范围使用场景
斜杠命令手动(/cmd仅会话内单条命令快速快捷方式
子代理自动委派隔离上下文专项任务任务分发
记忆系统自动加载跨会话用户/团队上下文长期学习
MCP 协议自动查询外部实时实时数据访问动态信息
技能自动调用基于文件系统可复用专业能力自动化工作流

交互时间线

实际集成示例:客户支持自动化

架构

请求流程

markdown
## 客户支持请求流程

### 1. 收到邮件
"上传文件时出现 500 错误。这阻碍了我的工作!"

### 2. 记忆系统查找
- 加载带支持规范的 CLAUDE.md
- 检查客户历史:VIP 客户,本月第 3 次事件

### 3. MCP 查询
- GitHub MCP:列出未关闭问题(找到相关 bug 报告)
- Database MCP:检查系统状态(无已知故障)
- Slack MCP:检查工程团队是否知晓

### 4. 技能检测与加载
- 请求匹配「技术支持」技能
- 从技能中加载支持响应模板

### 5. 子代理委派
- 路由到技术支持子代理
- 提供上下文:客户历史、错误详情、已知问题
- 子代理可访问:read、bash、grep 工具

### 6. 子代理处理
技术支持子代理:
- 在代码库中搜索文件上传 500 错误
- 在提交 8f4a2c 中找到最近的更改
- 创建临时解决方案文档

### 7. 技能执行
响应生成器技能:
- 使用品牌声音指南
- 以移情的方式格式化响应
- 包含临时解决方案步骤
- 链接到相关文档

### 8. MCP 输出
- 在 #support Slack 频道发布更新
- 标记工程团队
- 在 Jira MCP 中更新工单

### 9. 响应
客户收到:
- 移情的确认
- 原因说明
- 即时临时解决方案
- 永久修复时间线
- 相关问题链接

完整功能编排

何时使用各功能

选择决策树


汇总表

方面斜杠命令子代理记忆系统MCP技能插件
设置难度简单中等简单中等中等简单
学习曲线
团队收益非常高
自动化程度非常高
上下文管理单会话隔离持久实时持久所有功能
维护负担
可扩展性优秀优秀优秀优秀
可共享性一般一般优秀
版本控制手动手动手动手动手动自动
安装手动复制手动配置N/A手动配置手动复制一条命令

快速入门指南

第 1 周:从简单开始

  • 为常见任务创建 2-3 个斜杠命令
  • 在设置中启用记忆系统
  • 在 CLAUDE.md 中记录团队规范

第 2 周:添加实时访问

  • 设置 1 个 MCP(GitHub 或数据库)
  • 使用 /mcp 进行配置
  • 在工作流中查询实时数据

第 3 周:分发工作

  • 为特定角色创建第一个子代理
  • 使用 /agents 命令
  • 用简单任务测试委派

第 4 周:自动化一切

  • 为重复自动化创建第一个技能
  • 使用技能市场或自行构建
  • 将所有功能组合为完整工作流

持续进行

  • 每月审查和更新记忆系统
  • 随着模式出现添加新技能
  • 优化 MCP 查询
  • 改进子代理提示词

钩子

概述

钩子是事件驱动的 shell 命令,在响应 Claude Code 事件时自动执行。它们实现自动化、验证和自定义工作流,无需手动干预。

钩子事件

Claude Code 支持跨四种钩子类型(command、http、prompt、agent)的 25 个钩子事件

钩子事件触发时机使用场景
SessionStart会话开始/恢复/清除/压缩环境设置,初始化
InstructionsLoaded加载 CLAUDE.md 或规则文件验证、转换、增强
UserPromptSubmit用户提交提示词输入验证,提示词过滤
PreToolUse任何工具运行前验证,审批门控,日志记录
PermissionRequest显示权限对话框自动批准/拒绝流程
PostToolUse工具成功后自动格式化,通知,清理
PostToolUseFailure工具执行失败错误处理,日志记录
Notification发送通知告警,外部集成
SubagentStart生成子代理上下文注入,初始化
SubagentStop子代理完成结果验证,日志记录
StopClaude 完成响应摘要生成,清理任务
StopFailureAPI 错误结束轮次错误恢复,日志记录
TeammateIdle代理团队成员空闲工作分配,协调
TaskCompleted任务标记为完成任务后处理
TaskCreated通过 TaskCreate 创建任务任务跟踪,日志记录
ConfigChange配置文件更改验证,传播
CwdChanged工作目录更改目录特定设置
FileChanged被监视文件更改文件监控,重建触发
PreCompact上下文压缩前状态保存
PostCompact压缩完成后压缩后操作
WorktreeCreate创建工作树环境设置,依赖安装
WorktreeRemove删除工作树清理,资源释放
ElicitationMCP 服务器请求用户输入输入验证
ElicitationResult用户响应 elicitation响应处理
SessionEnd会话终止清理,最终日志记录

常用钩子

钩子在 ~/.claude/settings.json(用户级)或 .claude/settings.json(项目级)中配置:

json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write $CLAUDE_FILE_PATH"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "eslint $CLAUDE_FILE_PATH"
          }
        ]
      }
    ]
  }
}

钩子环境变量

  • $CLAUDE_FILE_PATH — 被编辑/写入文件的路径
  • $CLAUDE_TOOL_NAME — 使用的工具名称
  • $CLAUDE_SESSION_ID — 当前会话标识符
  • $CLAUDE_PROJECT_DIR — 项目目录路径

最佳实践

应该:

  • 保持钩子快速(< 1 秒)
  • 使用钩子进行验证和自动化
  • 优雅地处理错误
  • 使用绝对路径

不应该:

  • 让钩子具有交互性
  • 用钩子处理长时运行的任务
  • 硬编码凭据

参见06-hooks/ 获取详细示例


检查点与回退

概述

检查点允许你保存对话状态并回退到之前的时间点,从而实现安全实验和探索多种方案。

核心概念

概念描述
检查点对话状态的快照,包括消息、文件和上下文
回退返回到之前的检查点,放弃后续更改
分支点从该检查点探索多种方案

访问检查点

每次用户提示都会自动创建检查点。要回退:

bash
# 按两次 Esc 打开检查点浏览器
Esc + Esc

# 或使用 /rewind 命令
/rewind

选择检查点后,你可以从以下五个选项中选择:

  1. 恢复代码和对话 — 将两者都恢复到该时间点
  2. 恢复对话 — 回退消息,保留当前代码
  3. 恢复代码 — 恢复文件,保留对话
  4. 从此处摘要 — 将对话压缩为摘要
  5. 取消 — 取消操作

使用场景

场景工作流
探索方案保存 → 尝试方案 A → 保存 → 回退 → 尝试方案 B → 对比
安全重构保存 → 重构 → 测试 → 如果失败:回退
A/B 测试保存 → 设计 A → 保存 → 回退 → 设计 B → 对比
错误恢复发现问题 → 回退到上一个良好状态

配置

json
{
  "autoCheckpoint": true
}

参见08-checkpoints/ 获取详细示例


高级功能

计划模式

在编码前创建详细的实现计划。

激活:

bash
/plan Implement user authentication system

收益:

  • 带时间估算的清晰路线图
  • 风险评估
  • 系统化任务分解
  • 审查和修改的机会

扩展思考

对复杂问题进行深度推理。

激活:

  • 在会话中通过 Alt+T(macOS 上为 Option+T)切换
  • 以编程方式设置 MAX_THINKING_TOKENS 环境变量
bash
# 通过环境变量启用扩展思考
export MAX_THINKING_TOKENS=50000
claude -p "Should we use microservices or monolith?"

收益:

  • 深入分析权衡
  • 更好的架构决策
  • 考虑边缘情况
  • 系统化评估

后台任务

无需阻塞对话即可运行长时间操作。

用法:

bash
用户:在后台运行测试

Claude:已启动任务 bg-1234

/task list           # 显示所有任务
/task status bg-1234 # 检查进度
/task show bg-1234   # 查看输出
/task cancel bg-1234 # 取消任务

权限模式

控制 Claude 可以执行的操作。

模式描述使用场景
default标准权限,对敏感操作提示确认常规开发
acceptEdits自动接受文件编辑无需确认受信任的编辑工作流
plan仅分析和计划,不修改文件代码审查,架构规划
auto自动批准安全操作,仅对风险操作提示平衡自主性与安全性
dontAsk无确认提示执行所有操作有经验的用户,自动化
bypassPermissions完全不受限访问,无安全检查CI/CD 流水线,受信任脚本

用法:

bash
claude --permission-mode plan          # 只读分析
claude --permission-mode acceptEdits   # 自动接受编辑
claude --permission-mode auto          # 自动批准安全操作
claude --permission-mode dontAsk       # 无确认提示

无头模式(打印模式)

使用 -p(打印)标志在无需交互输入的情况下运行 Claude Code,用于自动化和 CI/CD。

用法:

bash
# 运行特定任务
claude -p "Run all tests"

# 通过管道传入进行分析
cat error.log | claude -p "explain this error"

# CI/CD 集成(GitHub Actions)
- name: AI Code Review
  run: claude -p "Review PR changes and report issues"

# 用于脚本的 JSON 输出
claude -p --output-format json "list all functions in src/"

定时任务

使用 /loop 命令按重复计划运行任务。

用法:

bash
/loop every 30m "Run tests and report failures"
/loop every 2h "Check for dependency updates"
/loop every 1d "Generate daily summary of code changes"

定时任务在后台运行,完成时报告结果。它们适用于持续监控、定期检查和自动维护工作流。

Chrome 集成

Claude Code 可以与 Chrome 浏览器集成,用于网络自动化任务。这使得可以在开发工作流中直接导航网页、填写表单、截图和从网站提取数据。

会话管理

管理多个工作会话。

命令:

bash
/resume                # 恢复上一次对话
/rename "Feature"      # 命名当前会话
/fork                  # 派生到新会话
claude -c              # 继续最近的对话
claude -r "Feature"    # 按名称/ID 恢复会话

交互功能

键盘快捷键:

  • Ctrl + R — 搜索命令历史
  • Tab — 自动补全
  • ↑ / ↓ — 命令历史
  • Ctrl + L — 清屏

多行输入:

bash
用户:\
> 长而复杂的提示词
> 跨多行
> \end

配置

完整配置示例:

json
{
  "planning": {
    "autoEnter": true,
    "requireApproval": true
  },
  "extendedThinking": {
    "enabled": true,
    "showThinkingProcess": true
  },
  "backgroundTasks": {
    "enabled": true,
    "maxConcurrentTasks": 5
  },
  "permissions": {
    "mode": "default"
  }
}

参见09-advanced-features/ 获取全面指南


资源


最后更新:2026 年 3 月适用于 Claude Haiku 4.5、Sonnet 4.6 和 Opus 4.6现包含:钩子、检查点、计划模式、扩展思考、后台任务、权限模式(6 种)、无头模式、会话管理、自动记忆、代理团队、定时任务、Chrome 集成、Channels、语音输入和内置技能