Slash Commands, Hooks, and SubAgents
斜杠命令、钩子和子代理
Learn to automate repetitive development tasks with Claude Code's powerful automation features. Create reusable slash commands, implement workflow hooks, and coordinate specialized AI agents.
学习使用Claude Code的强大自动化功能自动化重复开发任务。创建可重用的斜杠命令、实现工作流钩子,并协调专门的AI Agent。
.claude/commands/ directory.
.claude/commands/目录中。
.claude/commands/run-tests.md for automated testing.
.claude/commands/run-tests.md用于自动化测试。
# Run Tests Command Run the complete test suite for the project. ## Usage /run-tests [options] ## Options - --cov: Run with coverage report - --verbose: Show detailed output - --file: Run specific test file ## Examples /run-tests /run-tests --cov /run-tests --file backend/tests/test_notes.py
/run-tests in Claude Code to execute.
/run-tests来执行。
/format, /lint, /deploy, /docs.
/format、/lint、/deploy、/docs。
.claude/hooks.json to define workflow hooks.
.claude/hooks.json来定义工作流钩子。
{
"SessionStart": {
"command": "compact",
"enabled": true,
"description": "Compact previous sessions on start"
},
"ToolUse": {
"command": "log-tools",
"enabled": true,
"description": "Log tool usage for analysis"
}
}
.claude/hooks/SessionStart/compact.sh for session management.
.claude/hooks/SessionStart/compact.sh用于会话管理。
#!/bin/bash # Pre-commit hook for code quality echo "🔍 Running pre-commit checks..." # Format code echo "📝 Formatting with black..." black backend/ # Lint code echo "🔎 Linting with ruff..." ruff check backend/ # Run tests echo "🧪 Running tests..." pytest backend/tests/ -q echo "✅ All checks passed!"
.claude/subagents/ for specialized agents.
.claude/subagents/用于专门Agent。
.claude/subagents/test-agent.md for testing specialist.
.claude/subagents/test-agent.md用于测试专家。
# TestAgent - Testing Specialist
You are a testing specialist focused on writing comprehensive tests.
## Role
Write thorough test suites including unit tests, integration tests, and edge cases.
## Responsibilities
- Write pytest tests for all endpoints
- Achieve >80% code coverage
- Test edge cases and error conditions
- Mock external dependencies
## Guidelines
1. Use pytest fixtures for setup
2. Group related tests in classes
3. Use descriptive test names
4. Test both success and failure paths
5. Mock database and external services
## Output Format
Create test files in `backend/tests/` following the pattern:
- `test_{module}.py` for module tests
- Test classes inherit from `unittest.TestCase`
- Use descriptive test methods: `test_{action}_{scenario}`
# Launch TestAgent Task tool: "test-agent" Prompt: "Write comprehensive tests for the notes CRUD endpoints" # Claude will launch TestAgent with: # - Specialized testing knowledge # - Access to pytest tools # - Focus on test coverage
# backend/app/schemas.py
class UserBase(BaseModel):
email: str
username: str
class UserCreate(UserBase):
password: str
class UserRead(UserBase):
id: int
created_at: datetime
# backend/app/routers/auth.py
@router.post("/register")
def register(user: UserCreate, db: Session = Depends(get_db)):
# Hash password with bcrypt
hashed = bcrypt.hashpw(user.password.encode(), bcrypt.gensalt())
# Create user
db_user = User(
email=user.email,
username=user.username,
password_hash=hashed.decode()
)
db.add(db_user)
db.commit()
return {"ok": True, "data": UserRead.model_validate(db_user)}
# backend/tests/test_auth.py
def test_register_success(client):
response = client.post("/auth/register", json={
"email": "test@example.com",
"username": "testuser",
"password": "securepass123"
})
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
assert data["data"]["email"] == "test@example.com"
def test_register_duplicate_email(client):
# Create user first
# Try to register again
# Assert 409 Conflict
| Concept / 概念 | Description / 描述 | Example / 示例 |
|---|---|---|
| Slash Commands | Reusable prompt templates | /run-tests, /format, /deploy |
| Hooks | Automatic triggers | pre-commit, SessionStart |
| SubAgents | Specialized AI workers | TestAgent, DocsAgent, BackendAgent |
| Coordination | Agent orchestration | Sequential handoffs, parallel work |
Keep commands focused on single tasks. Use clear names and detailed descriptions.
保持命令专注于单一任务。使用清晰的名称和详细的描述。
Use hooks for quality gates, not blocking workflows. Make them fast and non-invasive.
使用钩子进行质量检查,而非阻塞工作流。使它们快速且非侵入性。
Define clear responsibilities for each agent. Use interfaces for communication.
为每个Agent定义清晰的职责。使用接口进行通信。
Monitor agent execution time. Cache results when possible. Use parallel execution.
监控Agent执行时间。尽可能缓存结果。使用并行执行。
Next week, you'll dive deeper into multi-agent workflows with:
下一周,你将深入研究多Agent工作流: