← Back to Course Summary / 返回课程总结
WEEK 4

Claude Code Automations
Claude Code自动化

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。

What You'll Build / 你将构建

🎯 Week 4 Project / 项目
Enhanced Developer's Command Center with automated workflows including slash commands for testing, pre-commit hooks for code quality, and SubAgents for specialized tasks.

增强的开发者控制中心,具有自动化工作流,包括用于测试的斜杠命令、用于代码质量的预提交钩子,以及用于专门任务的SubAgent。

Automation Types / 自动化类型

Slash Commands / 斜杠命令
Reusable prompt templates for common tasks like testing, linting, and documentation generation.

用于常见任务的可重用提示词模板,如测试、代码检查和文档生成。
✓ Benefits / 优势
  • Save time on repetitive tasks
  • Consistent execution
  • Easy to share with team
  • 参数支持 / Parameters
🪝
Hooks / 钩子
Automated actions triggered at specific points in the development workflow (pre-commit, post-response).

在开发工作流的特定点触发的自动化操作(预提交、响应后)。
✓ Benefits / 优势
  • Automatic quality checks
  • Enforce standards
  • Catch issues early
  • Zero manual effort
🤖
SubAgents / 子代理
Specialized AI agents with specific roles, tools, and capabilities for complex multi-step tasks.

具有特定角色、工具和功能的专门AI Agent,用于复杂的多步骤任务。
✓ Benefits / 优势
  • Specialized expertise
  • Parallel execution
  • Better context handling
  • Scalable workflows

Exercise 1: Creating Slash Commands / 练习1:创建斜杠命令

1
Create Command Directory / 创建命令目录
Claude Code stores slash commands in .claude/commands/ directory.

Claude Code将斜杠命令存储在.claude/commands/目录中。
mkdir -p .claude/commands
2
Create Test Command / 创建测试命令
Create .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
3
Use the Command / 使用命令
Type /run-tests in Claude Code to execute.

在Claude Code中输入/run-tests来执行。
💡 Pro Tip / 专业提示
Create commands for all repetitive tasks: /format, /lint, /deploy, /docs.

为所有重复性任务创建命令:/format/lint/deploy/docs

Exercise 2: Implementing Hooks / 练习2:实现钩子

1
Create Hooks Configuration / 创建钩子配置
Create .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"
  }
}
2
Create Pre-Commit Hook / 创建预提交钩子
Create .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!"
⚠️ Hook Types / 钩子类型
SessionStart: Runs when Claude Code starts
ToolUse: Runs before/after tool execution
ResponseComplete: Runs after each response

Available hooks: SessionStart, ToolUse, ResponseComplete, ContextUpdate

Exercise 3: Creating SubAgents / 练习3:创建SubAgent

1
Create SubAgent Directory / 创建SubAgent目录
Create .claude/subagents/ for specialized agents.

创建.claude/subagents/用于专门Agent。
mkdir -p .claude/subagents
2
Define TestAgent / 定义TestAgent
Create .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}`
3
Launch SubAgent / 启动SubAgent
Use Claude Code's Task tool to launch specialized agents.

使用Claude Code的Task工具启动专门Agent。
# 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

Exercise 4: Multi-Agent Workflow / 练习4:多Agent工作流

🔄 Workflow Scenario / 工作流场景
Implement a new feature: User Authentication
实现新功能:用户认证

This requires multiple agents: ParserAgent → BackendAgent → TestAgent → DocsAgent
1
ParserAgent - Define Schema / 定义模式
Create Pydantic models for User and authentication.

为用户和认证创建Pydantic模型。
# backend/app/schemas.py
class UserBase(BaseModel):
    email: str
    username: str

class UserCreate(UserBase):
    password: str

class UserRead(UserBase):
    id: int
    created_at: datetime
2
BackendAgent - Implement API / 实现API
Create authentication endpoints with password hashing.

创建具有密码哈希的认证端点。
# 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)}
3
TestAgent - Verify / 验证
Write comprehensive authentication tests.

编写全面的认证测试。
# 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
4
DocsAgent - Document / 文档化
Update API documentation with authentication details.

使用认证详情更新API文档。

Key Concepts / 关键概念

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

Best Practices / 最佳实践

📝 Command Design

Keep commands focused on single tasks. Use clear names and detailed descriptions.

保持命令专注于单一任务。使用清晰的名称和详细的描述。

🪝 Hook Strategy

Use hooks for quality gates, not blocking workflows. Make them fast and non-invasive.

使用钩子进行质量检查,而非阻塞工作流。使它们快速且非侵入性。

🤖 Agent Roles

Define clear responsibilities for each agent. Use interfaces for communication.

为每个Agent定义清晰的职责。使用接口进行通信。

⚡ Performance

Monitor agent execution time. Cache results when possible. Use parallel execution.

监控Agent执行时间。尽可能缓存结果。使用并行执行。

Achievements / 成就

  • ✅ Created 5+ slash commands for common tasks
  • ✅ Implemented pre-commit hooks for code quality
  • ✅ Built specialized SubAgents for testing and documentation
  • ✅ Coordinated multi-agent workflow for feature development
  • ✅ Achieved 2-3x productivity improvement with automations
  • ✅ 建立了5+个斜杠命令用于常见任务
  • ✅ 实现了预提交钩子用于代码质量
  • ✅ 构建了专门的SubAgent用于测试和文档
  • ✅ 协调了多Agent工作流用于功能开发
  • ✅ 通过自动化实现2-3倍生产力提升

Next Steps / 下一步

Week 5 Preview: Agentic Development

Next week, you'll dive deeper into multi-agent workflows with:

下一周,你将深入研究多Agent工作流:

  • 🤖 Advanced agent coordination patterns
  • 📋 Saved prompts and coding rules
  • ⚙️ Parallel agent execution
  • 📊 Efficiency metrics and optimization