claude-code-best-practice
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Code Best Practice
Claude Code 最佳实践
Skill by ara.so — Claude Code Skills collection.
Master the transition from "vibe coding" to agentic engineering with comprehensive best practices, implementation patterns, and real-world examples for Claude Code.
由 ara.so 提供的技能 — Claude Code 技能合集。
掌握从“凭感觉编码”到智能体工程的转变,学习Claude Code的全面最佳实践、实现模式和真实案例。
Overview
概述
This project provides battle-tested patterns for building sophisticated AI coding workflows using Claude Code's agent system. It covers subagents, commands, skills, orchestration workflows, MCP servers, hooks, and advanced features like agent teams and scheduled tasks.
本项目提供了经过实战检验的模式,用于利用Claude Code的智能体系统构建复杂的AI编码工作流。内容涵盖子智能体、命令、技能、编排工作流、MCP服务器、钩子以及智能体团队、定时任务等高级功能。
Core Concepts
核心概念
Project Structure
项目结构
your-project/
├── .claude/
│ ├── agents/ # Subagent definitions
│ │ └── <name>.md
│ ├── commands/ # Custom slash commands
│ │ └── <name>.md
│ ├── skills/ # Skill packages
│ │ └── <name>/
│ │ └── SKILL.md
│ ├── hooks/ # Lifecycle hooks
│ │ └── <hook-name>.sh
│ ├── rules/ # Project-specific rules
│ │ └── <name>.md
│ └── settings.json # Configuration
├── .mcp.json # MCP server config
└── CLAUDE.md # Project memory/contextyour-project/
├── .claude/
│ ├── agents/ # 子智能体定义
│ │ └── <name>.md
│ ├── commands/ # 自定义斜杠命令
│ │ └── <name>.md
│ ├── skills/ # 技能包
│ │ └── <name>/
│ │ └── SKILL.md
│ ├── hooks/ # 生命周期钩子
│ │ └── <hook-name>.sh
│ ├── rules/ # 项目特定规则
│ │ └── <name>.md
│ └── settings.json # 配置文件
├── .mcp.json # MCP服务器配置
└── CLAUDE.md # 项目记忆/上下文Subagents
子智能体
Purpose: Specialized AI agents focused on specific domains.
Location:
.claude/agents/<name>.mdStructure:
markdown
---
name: backend-api
description: Expert in FastAPI, database design, and REST APIs
model: claude-3-7-sonnet-20250219
---
You are a backend API specialist...用途:专注于特定领域的专业AI智能体。
存放位置:
.claude/agents/<name>.md结构:
markdown
---
name: backend-api
description: Expert in FastAPI, database design, and REST APIs
model: claude-3-7-sonnet-20250219
---
You are a backend API specialist...Capabilities
Capabilities
- Design RESTful APIs
- Optimize database queries
- Handle authentication patterns
- Design RESTful APIs
- Optimize database queries
- Handle authentication patterns
Guidelines
Guidelines
- Always validate input
- Use async/await patterns
- Include proper error handling
**Invocation**:
```bash- Always validate input
- Use async/await patterns
- Include proper error handling
**调用方式**:
```bashDirect invocation
直接调用
@backend-api help me design a user authentication endpoint
@backend-api help me design a user authentication endpoint
From command
通过命令调用
/api-review # Can delegate to @backend-api
**Best Practices**:
- Keep agents focused (single responsibility)
- Define clear capabilities and constraints
- Use appropriate models (Sonnet for complex, Haiku for simple)
- Include domain-specific guidelines/api-review # 可委托给@backend-api
**最佳实践**:
- 保持智能体专注(单一职责)
- 定义清晰的能力和约束
- 使用合适的模型(Sonnet用于复杂任务,Haiku用于简单任务)
- 包含领域特定指南Commands
命令
Purpose: Reusable workflows triggered by .
/command-nameLocation:
.claude/commands/<name>.mdBasic Command:
markdown
---
name: api-review
description: Review API design for REST best practices
---
Review the current API implementation:
1. Check endpoint naming conventions
2. Verify HTTP method usage
3. Validate response status codes
4. Check error handling patterns
5. Assess documentation completeness
Focus on files in `src/api/` and `src/routes/`.Orchestration Command (delegates to agents):
markdown
---
name: full-stack-review
description: Comprehensive review using specialized agents
---
Orchestrate a complete codebase review:用途:通过触发的可复用工作流。
/command-name存放位置:
.claude/commands/<name>.md基础命令:
markdown
---
name: api-review
description: Review API design for REST best practices
---
Review the current API implementation:
1. Check endpoint naming conventions
2. Verify HTTP method usage
3. Validate response status codes
4. Check error handling patterns
5. Assess documentation completeness
Focus on files in `src/api/` and `src/routes/`.编排命令(委托给智能体):
markdown
---
name: full-stack-review
description: Comprehensive review using specialized agents
---
Orchestrate a complete codebase review:Step 1: Backend Review
Step 1: Backend Review
@backend-api review all API endpoints in for:
src/api/- Security vulnerabilities
- Performance issues
- Best practices compliance
@backend-api review all API endpoints in for:
src/api/- Security vulnerabilities
- Performance issues
- Best practices compliance
Step 2: Frontend Review
Step 2: Frontend Review
@frontend-expert analyze components in for:
src/components/- Accessibility issues
- Performance optimizations
- React best practices
@frontend-expert analyze components in for:
src/components/- Accessibility issues
- Performance optimizations
- React best practices
Step 3: Integration Check
Step 3: Integration Check
@integration-agent verify:
- API contract matches frontend usage
- Error handling is consistent
- Loading states are handled
@integration-agent verify:
- API contract matches frontend usage
- Error handling is consistent
- Loading states are handled
Final Report
Final Report
Synthesize findings into a prioritized action plan.
**With Parameters**:
```markdown
---
name: generate-crud
description: Generate CRUD endpoints for a model
---
Generate complete CRUD operations for: {model_name}
1. Create `src/models/{model_name}.py`
2. Create `src/routes/{model_name}.py`
3. Add database migrations
4. Generate OpenAPI documentation
5. Create integration tests
Use existing patterns from `src/models/user.py` as reference.Synthesize findings into a prioritized action plan.
**带参数的命令**:
```markdown
---
name: generate-crud
description: Generate CRUD endpoints for a model
---
Generate complete CRUD operations for: {model_name}
1. Create `src/models/{model_name}.py`
2. Create `src/routes/{model_name}.py`
3. Add database migrations
4. Generate OpenAPI documentation
5. Create integration tests
Use existing patterns from `src/models/user.py` as reference.Skills
技能
Purpose: Installable expertise packages with tools and context.
Location:
.claude/skills/<skill-name>/SKILL.mdExample FastAPI Skill:
markdown
---
name: fastapi-expert
description: Expert FastAPI development patterns and best practices
triggers:
- "create a FastAPI endpoint"
- "help with FastAPI routing"
- "optimize FastAPI performance"
---用途:包含工具和上下文的可安装专业知识包。
存放位置:
.claude/skills/<skill-name>/SKILL.mdFastAPI技能示例:
markdown
---
name: fastapi-expert
description: Expert FastAPI development patterns and best practices
triggers:
- "create a FastAPI endpoint"
- "help with FastAPI routing"
- "optimize FastAPI performance"
---FastAPI Expert Skill
FastAPI Expert Skill
Installation
Installation
bash
pip install fastapi uvicorn sqlalchemy pydanticbash
pip install fastapi uvicorn sqlalchemy pydanticBasic Endpoint Pattern
Basic Endpoint Pattern
python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Item(BaseModel):
id: int
name: str
description: str | None = None
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
item = await fetch_item(item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.post("/items", response_model=Item, status_code=201)
async def create_item(item: Item):
created = await save_item(item)
return createdpython
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Item(BaseModel):
id: int
name: str
description: str | None = None
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
item = await fetch_item(item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.post("/items", response_model=Item, status_code=201)
async def create_item(item: Item):
created = await save_item(item)
return createdDependency Injection
Dependency Injection
python
from fastapi import Depends
from sqlalchemy.orm import Session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users")
async def get_users(db: Session = Depends(get_db)):
return db.query(User).all()python
from fastapi import Depends
from sqlalchemy.orm import Session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users")
async def get_users(db: Session = Depends(get_db)):
return db.query(User).all()Background Tasks
Background Tasks
python
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
# Email sending logic
pass
@app.post("/send-notification")
async def notify(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email, email, "Welcome!")
return {"message": "Notification queued"}python
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
# Email sending logic
pass
@app.post("/send-notification")
async def notify(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email, email, "Welcome!")
return {"message": "Notification queued"}Best Practices
Best Practices
- Use Pydantic models for validation
- Leverage dependency injection
- Implement proper error handling
- Use async/await for I/O operations
- Document with OpenAPI metadata
undefined- Use Pydantic models for validation
- Leverage dependency injection
- Implement proper error handling
- Use async/await for I/O operations
- Document with OpenAPI metadata
undefinedWorkflows (Orchestration)
工作流(编排)
Purpose: Multi-step processes that coordinate multiple agents.
Example Weather Orchestrator:
markdown
---
name: weather-orchestrator
description: Fetch and analyze weather data using specialized agents
---用途:协调多个智能体的多步骤流程。
天气编排器示例:
markdown
---
name: weather-orchestrator
description: Fetch and analyze weather data using specialized agents
---Weather Analysis Workflow
Weather Analysis Workflow
Phase 1: Data Collection
Phase 1: Data Collection
@data-fetcher retrieve current weather data for {city} using:
- Temperature
- Humidity
- Wind speed
- Forecast
@data-fetcher retrieve current weather data for {city} using:
- Temperature
- Humidity
- Wind speed
- Forecast
Phase 2: Analysis
Phase 2: Analysis
@data-analyst analyze the weather data for:
- Trends over next 48 hours
- Unusual patterns
- Alerts or warnings
@data-analyst analyze the weather data for:
- Trends over next 48 hours
- Unusual patterns
- Alerts or warnings
Phase 3: Recommendations
Phase 3: Recommendations
@recommendation-engine generate actionable advice:
- Outdoor activity suitability
- Clothing recommendations
- Travel considerations
@recommendation-engine generate actionable advice:
- Outdoor activity suitability
- Clothing recommendations
- Travel considerations
Phase 4: Report
Phase 4: Report
Compile findings into a user-friendly summary with:
- Current conditions
- 48-hour forecast
- Personalized recommendations
**Invocation**:
```bash
/weather-orchestrator city="San Francisco"Compile findings into a user-friendly summary with:
- Current conditions
- 48-hour forecast
- Personalized recommendations
**调用方式**:
```bash
/weather-orchestrator city="San Francisco"MCP Servers
MCP服务器
Purpose: Extend Claude with external tools and data sources.
Configuration ():
.mcp.jsonjson
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "${BRAVE_API_KEY}"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
}
}
}
}Usage in Agents:
markdown
Use the GitHub MCP server to:
- List open pull requests
- Create issues
- Search repositories
- Analyze commit history用途:通过外部工具和数据源扩展Claude的能力。
配置文件():
.mcp.jsonjson
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "${BRAVE_API_KEY}"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
}
}
}
}在智能体中使用:
markdown
Use the GitHub MCP server to:
- List open pull requests
- Create issues
- Search repositories
- Analyze commit historyHooks
钩子
Purpose: Execute scripts at key lifecycle points.
Available Hooks:
- - Before processing user message
BeforeChat - - After generating response
AfterChat - - Before executing tool
BeforeToolCall - - After tool execution
AfterToolCall - - Before modifying files
BeforeFileEdit - - After file changes
AfterFileEdit - - When creating worktree
WorktreeCreate - - When removing worktree
WorktreeRemove
Example ():
.claude/hooks/BeforeFileEdit.shbash
#!/bin/bash用途:在关键生命周期节点执行脚本。
可用钩子:
- - 处理用户消息前
BeforeChat - - 生成响应后
AfterChat - - 执行工具前
BeforeToolCall - - 工具执行后
AfterToolCall - - 修改文件前
BeforeFileEdit - - 文件修改后
AfterFileEdit - - 创建工作树时
WorktreeCreate - - 删除工作树时
WorktreeRemove
示例():
.claude/hooks/BeforeFileEdit.shbash
#!/bin/bashBackup files before editing
Backup files before editing
FILE_PATH="$1"
BACKUP_DIR=".claude/backups"
mkdir -p "$BACKUP_DIR"
timestamp=$(date +%Y%m%d_%H%M%S)
cp "$FILE_PATH" "$BACKUP_DIR/$(basename "$FILE_PATH").$timestamp.bak"
echo "Backed up $FILE_PATH"
Make executable:
```bash
chmod +x .claude/hooks/BeforeFileEdit.shFILE_PATH="$1"
BACKUP_DIR=".claude/backups"
mkdir -p "$BACKUP_DIR"
timestamp=$(date +%Y%m%d_%H%M%S)
cp "$FILE_PATH" "$BACKUP_DIR/$(basename "$FILE_PATH").$timestamp.bak"
echo "Backed up $FILE_PATH"
设置可执行权限:
```bash
chmod +x .claude/hooks/BeforeFileEdit.shSettings
设置
Configuration ():
.claude/settings.jsonjson
{
"model": "claude-3-7-sonnet-20250219",
"maxTokens": 8000,
"temperature": 0.7,
"statusline": {
"left": ["model", "tokens"],
"right": ["time", "cost"]
},
"permissions": {
"read": ["**/*"],
"write": ["src/**", "tests/**"],
"execute": ["scripts/**/*.sh"]
},
"autoMode": {
"enabled": false,
"confirmThreshold": 10
},
"outputStyle": "markdown",
"fastMode": false,
"isolation": "none"
}Global Settings ():
~/.claude/settings.jsonjson
{
"defaultModel": "claude-3-7-sonnet-20250219",
"apiKey": "${ANTHROPIC_API_KEY}",
"theme": "dark",
"telemetry": false
}配置文件():
.claude/settings.jsonjson
{
"model": "claude-3-7-sonnet-20250219",
"maxTokens": 8000,
"temperature": 0.7,
"statusline": {
"left": ["model", "tokens"],
"right": ["time", "cost"]
},
"permissions": {
"read": ["**/*"],
"write": ["src/**", "tests/**"],
"execute": ["scripts/**/*.sh"]
},
"autoMode": {
"enabled": false,
"confirmThreshold": 10
},
"outputStyle": "markdown",
"fastMode": false,
"isolation": "none"
}全局设置():
~/.claude/settings.jsonjson
{
"defaultModel": "claude-3-7-sonnet-20250219",
"apiKey": "${ANTHROPIC_API_KEY}",
"theme": "dark",
"telemetry": false
}Memory (CLAUDE.md)
记忆(CLAUDE.md)
Purpose: Persistent project context and preferences.
Example:
markdown
undefined用途:持久化的项目上下文和偏好设置。
示例:
markdown
undefinedProject: E-commerce API
Project: E-commerce API
Tech Stack
Tech Stack
- FastAPI 0.104
- PostgreSQL 15
- Redis for caching
- Stripe for payments
- FastAPI 0.104
- PostgreSQL 15
- Redis for caching
- Stripe for payments
Architecture Decisions
Architecture Decisions
- Use repository pattern for data access
- Implement CQRS for orders
- JWT for authentication
- Event-driven for notifications
- Use repository pattern for data access
- Implement CQRS for orders
- JWT for authentication
- Event-driven for notifications
Code Style
Code Style
- Use async/await throughout
- Type hints required
- Max line length: 100
- Sort imports with isort
- Use async/await throughout
- Type hints required
- Max line length: 100
- Sort imports with isort
Testing Strategy
Testing Strategy
- Pytest for all tests
- Minimum 80% coverage
- Integration tests for API endpoints
- Mock external services
- Pytest for all tests
- Minimum 80% coverage
- Integration tests for API endpoints
- Mock external services
Common Commands
Common Commands
- - Start development server
make dev - - Run test suite
make test - - Apply database migrations
make migrate - - Run linters
make lint
- - Start development server
make dev - - Run test suite
make test - - Apply database migrations
make migrate - - Run linters
make lint
Never Do
Never Do
- Commit secrets to repository
- Skip migration files
- Use print() for logging
- Deploy without tests passing
undefined- Commit secrets to repository
- Skip migration files
- Use print() for logging
- Deploy without tests passing
undefinedAdvanced Features
高级功能
Agent Teams
智能体团队
Enable (environment variable):
bash
export CLAUDE_AGENT_TEAMS=true
claudeTeam Configuration:
markdown
undefined启用方式(环境变量):
bash
export CLAUDE_AGENT_TEAMS=true
claude团队配置:
markdown
undefinedIn .claude/agents/team-lead.md
In .claude/agents/team-lead.md
name: team-lead
description: Coordinates multiple specialized agents
team:
- backend-api
- frontend-expert
- database-admin
- security-auditor
I coordinate specialized agents to solve complex problems.
When given a task, I:
- Break it into domain-specific subtasks
- Delegate to appropriate specialists
- Synthesize their outputs
- Ensure consistency across domains
undefinedname: team-lead
description: Coordinates multiple specialized agents
team:
- backend-api
- frontend-expert
- database-admin
- security-auditor
I coordinate specialized agents to solve complex problems.
When given a task, I:
- Break it into domain-specific subtasks
- Delegate to appropriate specialists
- Synthesize their outputs
- Ensure consistency across domains
undefinedScheduled Tasks
定时任务
Create Scheduled Command ():
.claude/commands/daily-health-check.mdmarkdown
---
name: daily-health-check
description: Daily codebase health assessment
schedule: "0 9 * * *" # 9 AM daily
---
Perform daily health check:
1. Run test suite and report failures
2. Check for dependency vulnerabilities
3. Analyze code quality metrics
4. Review open pull requests
5. Check CI/CD pipeline status
Email summary to: ${TEAM_EMAIL}Manual Scheduling:
bash
/schedule daily-health-check "0 9 * * *"创建定时命令():
.claude/commands/daily-health-check.mdmarkdown
---
name: daily-health-check
description: Daily codebase health assessment
schedule: "0 9 * * *" # 9 AM daily
---
Perform daily health check:
1. Run test suite and report failures
2. Check for dependency vulnerabilities
3. Analyze code quality metrics
4. Review open pull requests
5. Check CI/CD pipeline status
Email summary to: ${TEAM_EMAIL}手动调度:
bash
/schedule daily-health-check "0 9 * * *"Worktrees (Git Isolation)
工作树(Git隔离)
Create Isolated Environment:
bash
claude --worktree feature/new-apiIn Command:
markdown
---
name: safe-refactor
description: Refactor in isolated worktree
isolation: worktree
---
Safely refactor {component} by:
1. Creating clean worktree
2. Running comprehensive tests
3. Applying changes incrementally
4. Validating each step创建隔离环境:
bash
claude --worktree feature/new-api在命令中使用:
markdown
---
name: safe-refactor
description: Refactor in isolated worktree
isolation: worktree
---
Safely refactor {component} by:
1. Creating clean worktree
2. Running comprehensive tests
3. Applying changes incrementally
4. Validating each stepUltrareview
Ultrareview
Start Deep Code Review:
bash
/ultrareview src/Track Progress:
bash
/ultrareview --statusIn settings.json:
json
{
"ultrareview": {
"depth": "thorough",
"focus": ["security", "performance", "maintainability"],
"excludePatterns": ["*.test.ts", "*.spec.ts"]
}
}启动深度代码审查:
bash
/ultrareview src/跟踪进度:
bash
/ultrareview --status在settings.json中配置:
json
{
"ultrareview": {
"depth": "thorough",
"focus": ["security", "performance", "maintainability"],
"excludePatterns": ["*.test.ts", "*.spec.ts"]
}
}Real-World Patterns
真实场景模式
Full-Stack Feature Development
全栈功能开发
Command ():
.claude/commands/new-feature.mdmarkdown
---
name: new-feature
description: Scaffold complete full-stack feature
---
Create feature: {feature_name}命令():
.claude/commands/new-feature.mdmarkdown
---
name: new-feature
description: Scaffold complete full-stack feature
---
Create feature: {feature_name}Backend (@backend-api)
Backend (@backend-api)
- Create data model in
src/models/{feature_name}.py - Create API routes in
src/routes/{feature_name}.py - Add database migration
- Write integration tests
- Create data model in
src/models/{feature_name}.py - Create API routes in
src/routes/{feature_name}.py - Add database migration
- Write integration tests
Frontend (@frontend-expert)
Frontend (@frontend-expert)
- Create React components in
src/components/{feature_name}/ - Add API client methods
- Implement form validation
- Add unit tests
- Create React components in
src/components/{feature_name}/ - Add API client methods
- Implement form validation
- Add unit tests
Integration (@integration-agent)
Integration (@integration-agent)
- Verify API contract
- Test error scenarios
- Validate loading states
- Check accessibility
- Verify API contract
- Test error scenarios
- Validate loading states
- Check accessibility
Documentation
Documentation
- Update OpenAPI spec
- Add component Storybook stories
- Update README.md
undefined- Update OpenAPI spec
- Add component Storybook stories
- Update README.md
undefinedSecurity Audit Workflow
安全审计工作流
Command ():
.claude/commands/security-audit.mdmarkdown
---
name: security-audit
description: Comprehensive security review
---命令():
.claude/commands/security-audit.mdmarkdown
---
name: security-audit
description: Comprehensive security review
---Phase 1: Dependency Check
Phase 1: Dependency Check
@security-auditor scan dependencies:
bash
npm audit
pip-audit@security-auditor scan dependencies:
bash
npm audit
pip-auditPhase 2: Code Analysis
Phase 2: Code Analysis
@security-auditor review for:
- SQL injection vulnerabilities
- XSS attack vectors
- Authentication bypass risks
- Exposed secrets
@security-auditor review for:
- SQL injection vulnerabilities
- XSS attack vectors
- Authentication bypass risks
- Exposed secrets
Phase 3: Configuration Review
Phase 3: Configuration Review
@security-auditor check:
- CORS policies
- CSP headers
- Environment variable usage
- API rate limiting
@security-auditor check:
- CORS policies
- CSP headers
- Environment variable usage
- API rate limiting
Phase 4: Report
Phase 4: Report
Generate security report with:
- Critical findings (immediate action)
- Medium priority issues
- Recommendations
- Remediation steps
undefinedGenerate security report with:
- Critical findings (immediate action)
- Medium priority issues
- Recommendations
- Remediation steps
undefinedDatabase Migration Pattern
数据库迁移模式
Agent ():
.claude/agents/database-admin.mdmarkdown
---
name: database-admin
description: Database schema and migration expert
model: claude-3-7-sonnet-20250219
---
Expert in database design and migrations.智能体():
.claude/agents/database-admin.mdmarkdown
---
name: database-admin
description: Database schema and migration expert
model: claude-3-7-sonnet-20250219
---
Expert in database design and migrations.Migration Template
Migration Template
python
"""
Migration: {description}
Created: {timestamp}
"""
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'table_name',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('created_at', sa.DateTime, nullable=False),
)
# Add indexes
op.create_index('ix_table_name_id', 'table_name', ['id'])
def downgrade():
op.drop_index('ix_table_name_id')
op.drop_table('table_name')python
"""
Migration: {description}
Created: {timestamp}
"""
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'table_name',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('created_at', sa.DateTime, nullable=False),
)
# Add indexes
op.create_index('ix_table_name_id', 'table_name', ['id'])
def downgrade():
op.drop_index('ix_table_name_id')
op.drop_table('table_name')Safety Checks
Safety Checks
- Always provide downgrade path
- Test migration on copy of production data
- Add indexes for foreign keys
- Use transactions where possible
undefined- Always provide downgrade path
- Test migration on copy of production data
- Add indexes for foreign keys
- Use transactions where possible
undefinedTroubleshooting
故障排除
Agent Not Found
智能体未找到
bash
undefinedbash
undefinedList available agents
列出可用智能体
ls .claude/agents/
ls .claude/agents/
Verify agent syntax
验证智能体语法
@agent-name --help
undefined@agent-name --help
undefinedCommand Fails
命令执行失败
bash
undefinedbash
undefinedCheck command definition
检查命令定义
cat .claude/commands/command-name.md
cat .claude/commands/command-name.md
View command output
查看命令输出
/command-name --verbose
undefined/command-name --verbose
undefinedMCP Server Issues
MCP服务器问题
bash
undefinedbash
undefinedTest MCP server
测试MCP服务器
npx @modelcontextprotocol/server-github --help
npx @modelcontextprotocol/server-github --help
Check environment variables
检查环境变量
echo $GITHUB_TOKEN
echo $GITHUB_TOKEN
Validate .mcp.json
验证.mcp.json
jq . .mcp.json
undefinedjq . .mcp.json
undefinedPermission Errors
权限错误
json
{
"permissions": {
"read": ["**/*"],
"write": ["src/**", "!src/config/**"],
"execute": ["scripts/**/*.sh"]
}
}json
{
"permissions": {
"read": ["**/*"],
"write": ["src/**", "!src/config/**"],
"execute": ["scripts/**/*.sh"]
}
}Hook Not Executing
钩子未执行
bash
undefinedbash
undefinedVerify executable permission
验证可执行权限
chmod +x .claude/hooks/BeforeFileEdit.sh
chmod +x .claude/hooks/BeforeFileEdit.sh
Test hook directly
直接测试钩子
.claude/hooks/BeforeFileEdit.sh "test.txt"
.claude/hooks/BeforeFileEdit.sh "test.txt"
Check hook output
检查钩子输出
cat ~/.claude/logs/hooks.log
undefinedcat ~/.claude/logs/hooks.log
undefinedBest Practices Summary
最佳实践总结
- Agents: Keep focused, use appropriate models, define clear boundaries
- Commands: Document parameters, handle errors, provide examples
- Skills: Include real code, cover common patterns, troubleshoot
- Workflows: Break into phases, coordinate agents, validate steps
- MCP: Secure credentials, test servers, handle failures
- Hooks: Keep fast, handle errors, log actions
- Settings: Version control, document choices, test changes
- Memory: Keep updated, be specific, include decisions
- 智能体:保持专注,使用合适的模型,定义清晰边界
- 命令:记录参数,处理错误,提供示例
- 技能:包含真实代码,覆盖常见模式,提供故障排除方法
- 工作流:拆分为多个阶段,协调智能体,验证每个步骤
- MCP:安全存储凭证,测试服务器,处理故障
- 钩子:保持执行快速,处理错误,记录操作
- 设置:版本控制,记录选择,测试变更
- 记忆:保持更新,内容具体,包含决策信息