编程 Superpowers 深度拆解:123K Star 的 AI 编程工作流框架,如何让 Claude Code 秒变资深工程师

2026-05-02 07:33:08 +0800 CST views 3

Superpowers 深度拆解:123K Star 的 AI 编程工作流框架,如何让 Claude Code 秒变资深工程师

当 AI 编程助手不再"随性写代码",而是像资深工程师一样先思考、再规划、后编码、必验证,会发生什么?Superpowers 用 123,000+ Star 给出了答案。

引言:AI 编程的"信任危机"

如果你用过 AI 编程助手,一定经历过这样的场景:

你告诉 AI:"帮我写一个用户认证模块",它立刻开始输出代码。十分钟后,你得到了一段"看起来能用"的代码——但当你仔细审查,发现缺少错误处理、没有测试、边界情况没考虑、数据库事务没做……最糟的是,你不确定这些问题究竟有多少,只能逐行检查。

这就是当前 AI 编程的核心痛点:速度很快,但质量不可控。AI 像一个没有经验的初级工程师——热情高涨、代码量大,但缺乏系统性思维和质量保障意识。

2025 年 10 月,一位名叫 Jesse Vincent 的开源开发者决定解决这个问题。他创建了 Superpowers,一个让 AI 编程助手"拥有纪律"的工作流框架。核心理念只有一句话:Process over Prompt(流程大于提示词)

不到一年时间,这个项目获得了 123,000+ Star,一度登顶 GitHub Trending。它凭什么?

一、Superpowers 是什么?从"工具"到"方法论"的跃迁

1.1 不是插件,是"软件工程操作系统"

很多人第一次看到 Superpowers,会把它当成 Claude Code 的"外挂"或"提示词模板"。这是误解。

Superpowers 的定位更准确地说是一个软件开发方法论 + 可组合技能库。它通过拦截 AI 编程代理的关键决策点,将单次对话转变为结构化的软件工程流程。

传统 AI 编程流程:

用户需求 → AI 直接写代码 → 用户审查 → 发现问题 → 迭代修改

Superpowers 流程:

用户需求 → 头脑风暴 → 方案设计 → 编写计划 → TDD 开发 → 代码审查 → 系统化调试 → 验证交付

这不是"让 AI 更聪明",而是"让 AI 更守规矩"。

1.2 核心设计哲学

Superpowers 的设计基于三个基本原则:

原则一:Test-Driven Development(测试驱动开发)

RED → 编写失败测试
GREEN → 编写最小代码通过测试
REFACTOR → 重构优化

这不是建议,是强制。Superpowers 的 test-driven-development 技能会在你试图写生产代码前,强制要求你先写测试——并亲眼看着它失败。

原则二:Systematic over Ad-hoc(系统化胜过临时方案)

当 AI 遇到问题时,它不应该"猜一个解决方案",而是遵循系统化的调试流程:

Phase 1: 复现问题
Phase 2: 定位根因
Phase 3: 设计修复方案
Phase 4: 验证修复
Phase 5: 添加防御性测试

原则三:Evidence over Claims(证据胜过断言)

AI 说"我修复了这个问题"?不够。Superpowers 要求提供证据:

  • 测试从失败变为通过
  • 所有相关测试仍然通过
  • 边界情况已被覆盖

1.3 一句话总结

Superpowers 不是让 AI "更强",而是让 AI "更稳"——通过强制执行软件工程最佳实践,将不可预测的 AI 输出转变为可信赖的工程交付。

二、架构深度解析:Skills 系统的设计艺术

2.1 什么是 Skills?

Skills 是 Superpowers 的核心概念。每个 Skill 是一个独立的工作流单元,负责处理特定类型的任务。

一个 Skill 的典型结构:

skills/
├── brainstorming/
│   ├── SKILL.md           # 技能描述和触发条件
│   ├── prompts/
│   │   ├── main.md        # 主提示词模板
│   │   └── followup.md    # 追问提示词
│   └── templates/
│       └── design-doc.md  # 设计文档模板
├── writing-plans/
│   ├── SKILL.md
│   └── ...
└── test-driven-development/
    └── ...

2.2 Skills 的触发机制

Skills 不是被动调用的,而是主动触发的。Superpowers 会在关键决策点检查当前上下文,自动激活相关技能。

触发条件定义示例:

# skills/brainstorming/SKILL.md

## Triggers

- User mentions "build", "create", "implement", or "add"
- User describes a new feature or component
- No existing design document found in project

## Behavior

When triggered:
1. DO NOT start writing code immediately
2. ASK clarifying questions to understand requirements
3. PRESENT design options with trade-offs
4. SAVE design document for future reference

这种设计让技能激活变得"隐式"——用户不需要记住调用哪个技能,AI 会自动判断并执行。

2.3 核心技能详解

Superpowers 目前提供 14 个核心技能,覆盖软件开发生命周期的各个阶段:

2.3.1 brainstorming(头脑风暴)

用途:在写代码前,先搞清楚"要做什么"

触发场景

  • 用户提出新功能需求
  • 项目中没有设计文档
  • 需求描述模糊或不完整

工作流程

1. 提取需求关键词
2. 生成澄清问题列表
3. 用户回答后,生成设计选项
4. 分段展示设计(每段不超过 100 行)
5. 用户确认后,保存设计文档

代码示例 - 澄清问题生成逻辑

def generate_clarifying_questions(requirement: str) -> list[str]:
    """
    从模糊需求中生成澄清问题
    
    Example:
        Input: "帮我做一个用户登录功能"
        Output: [
            "登录方式支持哪些?(账号密码/手机验证码/第三方登录)",
            "是否需要记住登录状态?有效期多久?",
            "登录失败时如何处理?锁定账户?验证码?",
            "是否需要登录日志?记录哪些信息?"
        ]
    """
    questions = []
    
    # 检查认证方式
    if "登录" in requirement and not any(kw in requirement for kw in ["OAuth", "验证码", "密码"]):
        questions.append("登录方式支持哪些?(账号密码/手机验证码/第三方登录)")
    
    # 检查会话管理
    if "登录" in requirement and "会话" not in requirement:
        questions.append("是否需要记住登录状态?有效期多久?")
    
    # 检查错误处理
    if "登录" in requirement and "失败" not in requirement:
        questions.append("登录失败时如何处理?锁定账户?验证码?")
    
    return questions

2.3.2 writing-plans(编写计划)

用途:将设计方案分解为可执行的小任务

核心原则

  • 每个任务 2-5 分钟可完成
  • 任务包含:文件路径、完整代码、验证步骤
  • 任务之间相对独立,可并行执行

计划模板示例

# Implementation Plan: User Authentication Module

## Task 1: Create User Model (Est: 3 min)
- File: `src/models/user.py`
- Code:
  ```python
  from dataclasses import dataclass
  from datetime import datetime
  
  @dataclass
  class User:
      id: str
      username: str
      password_hash: str
      created_at: datetime
      last_login: datetime | None = None
  • Verification: python -c "from src.models.user import User; print(User)"
  • Status: [ ] Pending

Task 2: Implement Password Hashing (Est: 2 min)

  • File: src/utils/security.py
  • Code:
    import bcrypt
    
    def hash_password(password: str) -> str:
        return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
    
    def verify_password(password: str, hash: str) -> bool:
        return bcrypt.checkpw(password.encode(), hash.encode())
    
  • Verification: Run tests/test_security.py
  • Status: [ ] Pending

Task 3: Create Login Endpoint (Est: 5 min)

  • File: src/api/auth.py
  • Dependencies: Task 1, Task 2
  • Code:
    from fastapi import APIRouter, HTTPException
    from src.models.user import User
    from src.utils.security import verify_password
    
    router = APIRouter()
    
    @router.post("/login")
    async def login(username: str, password: str):
        user = await User.get_by_username(username)
        if not user or not verify_password(password, user.password_hash):
            raise HTTPException(401, "Invalid credentials")
        return {"token": create_jwt(user)}
    
  • Verification: Run integration test tests/test_auth.py::test_login_success
  • Status: [ ] Pending

#### 2.3.3 subagent-driven-development(子代理驱动开发)

这是 Superpowers 最强大的技能之一。

**用途**:为每个任务派发独立的子代理,执行后进行两阶段审查

**工作流程**:

主代理
├── 派发任务 1 → 子代理 A → 实现代码
│ ↓
│ 规范审查代理 → 检查是否符合设计
│ ↓
│ 代码质量代理 → 检查代码质量
│ ↓
├── 派发任务 2 → 子代理 B → ...

└── 最终整合审查


**两阶段审查详解**:

```python
class SpecReviewer:
    """规范合规性审查"""
    
    def review(self, code: str, spec: DesignSpec) -> ReviewResult:
        issues = []
        
        # 检查是否实现了所有必需功能
        for requirement in spec.must_have:
            if not self._check_requirement(code, requirement):
                issues.append(Issue(
                    severity="critical",
                    message=f"Missing required feature: {requirement}",
                    location=self._find_missing_location(code, requirement)
                ))
        
        # 检查是否有未授权的功能(超出范围)
        for feature in self._extract_features(code):
            if feature not in spec.all_features:
                issues.append(Issue(
                    severity="warning",
                    message=f"Unspecified feature detected: {feature}"
                ))
        
        return ReviewResult(passed=len([i for i in issues if i.severity == "critical"]) == 0,
                           issues=issues)


class CodeQualityReviewer:
    """代码质量审查"""
    
    def review(self, code: str) -> ReviewResult:
        issues = []
        
        # 静态分析
        issues.extend(self._run_linter(code))
        
        # 复杂度检查
        if self._calculate_cyclomatic_complexity(code) > 10:
            issues.append(Issue(
                severity="warning",
                message="Function complexity too high, consider refactoring"
            ))
        
        # 命名规范
        issues.extend(self._check_naming_conventions(code))
        
        # 重复代码检测
        duplicates = self._detect_duplicates(code)
        if duplicates:
            issues.append(Issue(
                severity="info",
                message=f"Potential code duplication detected: {len(duplicates)} blocks"
            ))
        
        return ReviewResult(passed=len([i for i in issues if i.severity == "critical"]) == 0,
                           issues=issues)

为什么用子代理而不是直接执行?

关键优势:

  1. 上下文隔离:每个子代理从干净状态开始,不受之前任务"记忆污染"
  2. 并行执行:多个独立任务可以同时进行
  3. 质量保障:每次执行后强制审查,问题在早期发现

2.3.4 test-driven-development(测试驱动开发)

铁律:没有失败测试,就没有生产代码。

RED-GREEN-REFACTOR 循环

class TDDWorkflow:
    """TDD 工作流执行器"""
    
    def execute(self, task: Task):
        # Phase 1: RED - 编写失败测试
        test_code = self._write_test(task)
        self._save_test(test_code)
        
        # 验证测试确实失败
        test_result = self._run_tests()
        if test_result.passed:
            raise TDDViolation("Test passed immediately! This means it doesn't test anything.")
        
        print(f"✅ RED phase complete - test fails as expected")
        
        # Phase 2: GREEN - 编写最小代码
        impl_code = self._write_minimal_implementation(task)
        self._save_implementation(impl_code)
        
        # 验证测试通过
        test_result = self._run_tests()
        if not test_result.passed:
            raise TDDViolation(f"Implementation failed to pass test: {test_result.failures}")
        
        print(f"✅ GREEN phase complete - test passes")
        
        # Phase 3: REFACTOR - 优化代码
        refactored_code = self._refactor(impl_code)
        
        # 验证重构后测试仍然通过
        self._save_implementation(refactored_code)
        test_result = self._run_tests()
        if not test_result.passed:
            raise TDDViolation("Refactoring broke tests! Rolling back...")
        
        print(f"✅ REFACTOR phase complete - code improved, tests still pass")
        
        return refactored_code
    
    def _write_test(self, task: Task) -> str:
        """
        生成测试代码
        
        好的测试应该:
        1. 有清晰的描述性名称
        2. 测试一个行为
        3. 不依赖实现细节
        """
        return f'''
def test_{task.name}_handles_normal_case():
    """Test that {task.name} works correctly with valid input"""
    result = {task.function_name}({task.sample_input})
    assert result == {task.expected_output}

def test_{task.name}_handles_edge_case():
    """Test that {task.name} handles edge cases gracefully"""
    with pytest.raises(ValueError):
        {task.function_name}({task.edge_case_input})

def test_{task.name}_is_idempotent():
    """Test that calling {task.name} multiple times produces same result"""
    result1 = {task.function_name}({task.sample_input})
    result2 = {task.function_name}({task.sample_input})
    assert result1 == result2
'''

测试反模式检测

Superpowers 会自动检测常见的测试反模式:

TEST_ANTIPATTERNS = {
    "test_without_assertion": {
        "pattern": r"def test_.*?:\s*\n\s*[^#]*(?!assert)",
        "message": "Test function has no assertions"
    },
    "assertion_on_implementation_detail": {
        "pattern": r"assert\s+\w+\._\w+",
        "message": "Testing private implementation details makes tests brittle"
    },
    "multiple_assertions_same_concept": {
        "pattern": r"assert\s+.*\n.*assert\s+.*==",
        "message": "Multiple assertions on same concept should be combined"
    },
    "test_depends_on_external_state": {
        "pattern": r"(?!mock|fixture)(?:database|api|file)\s*\.",
        "message": "Test depends on external state, use mocks instead"
    }
}

2.3.5 systematic-debugging(系统化调试)

用途:用科学方法定位和修复 Bug

四阶段流程

## Phase 1: Reproduce(复现问题)
- 记录精确的复现步骤
- 创建最小复现案例
- 确认问题确实存在

## Phase 2: Isolate(隔离根因)
- 二分法定位问题代码
- 检查最近的代码变更
- 分析错误日志和堆栈跟踪

## Phase 3: Fix(修复问题)
- 编写失败的测试用例
- 实现修复
- 验证测试通过

## Phase 4: Prevent(预防复发)
- 添加边界测试
- 更新文档
- 考虑是否需要架构改进

调试提示词模板

# Debugging Workflow

## Current Situation
- Error message: {error_message}
- Expected behavior: {expected}
- Actual behavior: {actual}

## Step 1: Reproduce
```bash
# Run the failing scenario
{reproduction_command}

# Output
{actual_output}

Step 2: Isolate

  • Last working commit: {last_working_commit}
  • First failing commit: {first_failing_commit}
  • Changed files: {changed_files}

Step 3: Hypothesis

Based on the error and changes, the most likely cause is:
{hypothesis}

Step 4: Verify Hypothesis

# Test the hypothesis
{verification_command}

Step 5: Fix

{fix_description}

Step 6: Verify Fix

# Run all related tests
pytest tests/test_{module}.py -v

# Run original failing scenario
{reproduction_command}

Prevention

  • Added test: {new_test_file}
  • Updated docs: {doc_changes}

#### 2.3.6 using-git-worktrees(Git Worktree 工作流)

**用途**:支持并行开发,避免分支切换的开销

**为什么需要 Git Worktree?**

传统 Git 分支切换:
```bash
git checkout feature-a
# 修改代码...
git checkout feature-b
# 文件系统重写,IDE 索引重建...
git checkout feature-a
# 又要重写文件系统...

Git Worktree 方案:

# 创建独立的工作目录
git worktree add ../project-feature-a feature-a
git worktree add ../project-feature-b feature-b

# 每个目录可以独立开发,无需切换
cd ../project-feature-a
# 直接工作,IDE 状态保持

Superpowers 自动化流程

class WorktreeManager:
    def create_feature_worktree(self, feature_name: str) -> WorktreeInfo:
        """创建功能分支的工作树"""
        
        # 1. 检查分支是否存在
        branch_exists = self._check_branch_exists(feature_name)
        
        # 2. 创建工作树
        worktree_path = self.project_path.parent / f"{self.project_path.name}-{feature_name}"
        
        if branch_exists:
            subprocess.run([
                "git", "worktree", "add", 
                str(worktree_path), feature_name
            ])
        else:
            subprocess.run([
                "git", "worktree", "add", "-b", feature_name,
                str(worktree_path)
            ])
        
        # 3. 在新工作树中设置项目
        self._setup_project(worktree_path)
        
        # 4. 验证环境
        self._verify_clean_state(worktree_path)
        
        return WorktreeInfo(
            path=worktree_path,
            branch=feature_name,
            created_at=datetime.now()
        )
    
    def cleanup_worktree(self, worktree: WorktreeInfo, merge: bool = False):
        """清理工作树"""
        
        if merge:
            # 合并到主分支
            subprocess.run(["git", "checkout", "main"])
            subprocess.run(["git", "merge", worktree.branch])
        
        # 移除工作树
        subprocess.run(["git", "worktree", "remove", str(worktree.path)])
        subprocess.run(["git", "branch", "-d", worktree.branch])

2.4 技能组合与依赖

技能之间可以组合和依赖:

# skills/dependency-graph.yaml

brainstorming:
  triggers: [new_feature_request]
  produces: [design_document]
  
writing-plans:
  requires: [design_document]
  triggers: [approved_design]
  produces: [implementation_plan]
  
subagent-driven-development:
  requires: [implementation_plan]
  produces: [implemented_features]
  
test-driven-development:
  required_by: [subagent-driven-development]
  
systematic-debugging:
  triggers: [test_failure, runtime_error]

这种依赖关系确保了流程的正确顺序:你不能在没有设计的情况下写计划,不能在没有计划的情况下开发。

三、安装与配置:多平台适配

3.1 Claude Code 安装(推荐方式)

方法一:官方插件市场

# 在 Claude Code 中执行
/plugin install superpowers@claude-plugins-official

方法二:自定义市场

# 注册市场
/plugin marketplace add obra/superpowers-marketplace

# 从市场安装
/plugin install superpowers@superpowers-marketplace

3.2 其他平台安装

Codex

# 在对话中告诉 Codex:
Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.codex/INSTALL.md

Cursor

# 在 Agent 聊天中
/add-plugin superpowers

# 或在插件市场搜索 "superpowers"

OpenCode

# 在对话中执行
Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.opencode/INSTALL.md

Gemini CLI

gemini extensions install https://github.com/obra/superpowers

# 更新
gemini extensions update superpowers

3.3 手动安装(高级用户)

# 克隆仓库
git clone https://github.com/obra/superpowers.git

# 复制到技能目录
# Claude Code 全局目录
cp -r superpowers ~/.claude/skills/

# 或项目级目录(推荐)
cp -r superpowers your-project/.claude/skills/

# 重启 Claude Code

3.4 配置文件结构

安装后,Superpowers 会在项目中创建以下结构:

your-project/
├── .claude/
│   ├── skills/
│   │   └── superpowers/
│   │       ├── skills/
│   │       │   ├── brainstorming/
│   │       │   ├── writing-plans/
│   │       │   ├── test-driven-development/
│   │       │   └── ...
│   │       └── SKILL.md
│   └── settings.json
├── .superpowers/
│   ├── designs/           # 设计文档
│   ├── plans/             # 实现计划
│   └── reviews/           # 代码审查记录
└── tests/
    └── ...

四、实战案例:从零构建一个待办事项 API

让我们用一个完整案例演示 Superpowers 的工作流程。

4.1 阶段一:Brainstorming

用户输入:

帮我做一个待办事项 API

Superpowers 触发 brainstorming 技能:

# 🧠 Brainstorming Mode Activated

在开始写代码之前,我想先了解一些细节:

## 需求澄清问题

1. **数据模型**
   - 待办事项需要哪些字段?(标题、描述、截止日期、优先级、标签...)
   - 是否支持子任务?
   - 是否需要附件或评论?

2. **用户系统**
   - 是否需要用户认证?
   - 待办事项是私有的还是可以共享?
   - 是否需要团队协作功能?

3. **API 功能**
   - 需要哪些操作?(CRUD 基础上,是否需要搜索、过滤、排序?)
   - 是否需要批量操作?
   - 是否需要 Webhook 或实时通知?

4. **非功能需求**
   - 预期用户量级?
   - 响应时间要求?
   - 数据持久化偏好?(PostgreSQL/MongoDB/Redis...)

请回答这些问题,我会帮你设计一个合适的方案。

用户回答后,Superpowers 生成设计文档:

# Todo API Design Document

## Overview
A RESTful API for managing personal todo items with user authentication.

## Data Model

### User
```python
@dataclass
class User:
    id: UUID
    email: str
    password_hash: str
    created_at: datetime

Todo

@dataclass
class Todo:
    id: UUID
    user_id: UUID
    title: str
    description: str | None
    status: Literal["pending", "in_progress", "completed"]
    priority: Literal["low", "medium", "high"]
    due_date: datetime | None
    tags: list[str]
    created_at: datetime
    updated_at: datetime

API Endpoints

MethodPathDescription
POST/auth/registerRegister new user
POST/auth/loginLogin and get JWT
GET/todosList user's todos
POST/todosCreate new todo
GET/todos/{id}Get todo details
PUT/todos/{id}Update todo
DELETE/todos/{id}Delete todo
PATCH/todos/{id}/statusUpdate status

Technology Stack

  • Framework: FastAPI
  • Database: PostgreSQL
  • ORM: SQLAlchemy
  • Auth: JWT with python-jose

Design Decisions

  1. Use UUID for all IDs (better for distributed systems)
  2. Soft delete todos (allow recovery)
  3. Pagination for list endpoints (default 20 items)
  4. Rate limiting: 100 requests per minute per user

Out of Scope (for this iteration)

  • Team collaboration
  • File attachments
  • Recurring todos
  • Mobile push notifications

### 4.2 阶段二:Writing Plans

设计确认后,Superpowers 生成实现计划:

```markdown
# Implementation Plan: Todo API

## Phase 1: Project Setup (Est: 10 min)

### Task 1.1: Initialize Project Structure
- File: `pyproject.toml`, `requirements.txt`
- Verification: `python -m pytest --collect-only`

### Task 1.2: Configure Database Connection
- File: `src/database.py`
- Code:
  ```python
  from sqlalchemy import create_engine
  from sqlalchemy.orm import sessionmaker
  
  DATABASE_URL = "postgresql://user:pass@localhost/todo_db"
  
  engine = create_engine(DATABASE_URL)
  SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  • Verification: Database connection test passes

Phase 2: Core Models (Est: 15 min)

Task 2.1: Create User Model

  • File: src/models/user.py
  • Dependencies: Task 1.2
  • Tests: tests/test_user_model.py

Task 2.2: Create Todo Model

  • File: src/models/todo.py
  • Dependencies: Task 1.2, Task 2.1
  • Tests: tests/test_todo_model.py

Phase 3: Authentication (Est: 20 min)

Task 3.1: Implement Password Hashing

  • File: src/utils/security.py
  • Tests: tests/test_security.py

Task 3.2: Create JWT Utilities

  • File: src/utils/jwt.py
  • Tests: tests/test_jwt.py

Task 3.3: Implement Auth Endpoints

  • File: src/api/auth.py
  • Dependencies: Task 3.1, Task 3.2
  • Tests: tests/test_auth_api.py

Phase 4: Todo CRUD (Est: 25 min)

Task 4.1: Create Todo Service

  • File: src/services/todo.py
  • Tests: tests/test_todo_service.py

Task 4.2: Implement Todo Endpoints

  • File: src/api/todos.py
  • Dependencies: Task 4.1
  • Tests: tests/test_todos_api.py

Phase 5: Integration & Polish (Est: 15 min)

Task 5.1: Add Error Handling Middleware

  • File: src/middleware/error_handler.py

Task 5.2: Add Rate Limiting

  • File: src/middleware/rate_limiter.py

Task 5.3: Write API Documentation

  • File: docs/api.md

Total Estimated Time: 85 minutes


### 4.3 阶段三:TDD 开发

以 Task 3.1(密码哈希)为例,展示 TDD 流程:

**Step 1: RED - 写失败测试**

```python
# tests/test_security.py

import pytest
from src.utils.security import hash_password, verify_password

def test_hash_password_returns_string():
    """Password hashing should return a string"""
    result = hash_password("my_password")
    assert isinstance(result, str)

def test_hash_password_is_different_from_input():
    """Hashed password should not equal plain password"""
    plain = "my_password"
    hashed = hash_password(plain)
    assert hashed != plain

def test_verify_password_returns_true_for_correct_password():
    """Correct password should verify successfully"""
    plain = "my_password"
    hashed = hash_password(plain)
    assert verify_password(plain, hashed) is True

def test_verify_password_returns_false_for_wrong_password():
    """Wrong password should fail verification"""
    plain = "my_password"
    hashed = hash_password(plain)
    assert verify_password("wrong_password", hashed) is False

def test_same_password_different_hashes():
    """Same password should produce different hashes (salt)"""
    plain = "my_password"
    hash1 = hash_password(plain)
    hash2 = hash_password(plain)
    assert hash1 != hash2

运行测试:

$ pytest tests/test_security.py -v

FAILED - ModuleNotFoundError: No module named 'src.utils.security'

✅ RED 阶段完成 - 测试失败,符合预期。

Step 2: GREEN - 写最小代码

# src/utils/security.py

import bcrypt

def hash_password(password: str) -> str:
    """Hash a password using bcrypt"""
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

def verify_password(password: str, hashed: str) -> bool:
    """Verify a password against its hash"""
    return bcrypt.checkpw(password.encode(), hashed.encode())

运行测试:

$ pytest tests/test_security.py -v

PASSED - test_hash_password_returns_string
PASSED - test_hash_password_is_different_from_input
PASSED - test_verify_password_returns_true_for_correct_password
PASSED - test_verify_password_returns_false_for_wrong_password
PASSED - test_same_password_different_hashes

5 passed

✅ GREEN 阶段完成 - 所有测试通过。

Step 3: REFACTOR - 优化代码

# src/utils/security.py

import bcrypt
from functools import lru_cache

# 缓存 gensalt 结果以提升性能(每次生成 salt 很耗时)
@lru_cache(maxsize=1)
def _get_salt_rounds() -> int:
    """Get the default salt rounds from environment or use default"""
    import os
    return int(os.getenv("BCRYPT_ROUNDS", "12"))

def hash_password(password: str, rounds: int | None = None) -> str:
    """
    Hash a password using bcrypt.
    
    Args:
        password: The plain text password to hash
        rounds: Number of salt rounds (default: 12, higher is more secure but slower)
    
    Returns:
        The hashed password as a string
    
    Raises:
        ValueError: If password is empty or too long (>72 bytes)
    """
    if not password:
        raise ValueError("Password cannot be empty")
    
    password_bytes = password.encode('utf-8')
    if len(password_bytes) > 72:
        raise ValueError("Password too long (max 72 bytes)")
    
    rounds = rounds or _get_salt_rounds()
    salt = bcrypt.gensalt(rounds=rounds)
    return bcrypt.hashpw(password_bytes, salt).decode('utf-8')

def verify_password(password: str, hashed: str) -> bool:
    """
    Verify a password against its hash.
    
    Args:
        password: The plain text password to verify
        hashed: The hashed password to check against
    
    Returns:
        True if the password matches, False otherwise
    """
    if not password or not hashed:
        return False
    
    try:
        return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
    except (ValueError, TypeError):
        # Invalid hash format
        return False

再次运行测试确认通过。

✅ REFACTOR 阶段完成 - 代码更健壮,测试仍然通过。

4.4 阶段四:Subagent 驱动开发

对于复杂的任务,Superpowers 会派发子代理:

# Subagent Dispatch Log

## Task 4.1: Create Todo Service

### Subagent A - Implementation
- Status: ✅ Complete
- Files created: `src/services/todo.py`
- Tests written: 12
- Tests passed: 12

### Spec Review
- Status: ✅ Pass
- Notes: All required operations implemented (CRUD + search + filter)

### Code Quality Review
- Status: ⚠️ Warnings
- Issues:
  - Cyclomatic complexity 8 in `search_todos()` (threshold: 10) - OK
  - Missing type hints in 2 places - Fixed
- Final Status: ✅ Pass

---

## Task 4.2: Implement Todo Endpoints

### Subagent B - Implementation
- Status: ✅ Complete
- Files created: `src/api/todos.py`
- Tests written: 18
- Tests passed: 18

### Spec Review
- Status: ✅ Pass
- Notes: All endpoints match API design document

### Code Quality Review
- Status: ✅ Pass
- Notes: Good error handling, proper validation

---

## Summary
- Total subagents dispatched: 2
- Total tests written: 30
- All tests passing: ✅
- Code quality score: 9.2/10

4.5 阶段五:代码审查

Superpowers 自动进行代码审查:

# Code Review Report

## Overview
- Branch: feature/todo-api
- Commits: 12
- Files changed: 15
- Lines added: 847
- Lines removed: 23

## Security Review ✅
- [x] No hardcoded secrets
- [x] SQL injection protection (parameterized queries)
- [x] XSS protection (input sanitization)
- [x] Rate limiting implemented
- [x] Authentication required for all endpoints

## Performance Review ⚠️
- [x] Database indexes on frequently queried columns
- [x] Pagination for list endpoints
- [ ] N+1 query detected in `GET /todos` - Consider eager loading
  - File: `src/api/todos.py:45`
  - Suggestion: Add `joinedload(Todo.tags)`

## Code Style ✅
- [x] Follows PEP 8
- [x] Type hints on all public functions
- [x] Docstrings on all modules and classes

## Test Coverage ✅
- Overall: 94%
- Critical paths: 100%

## Recommendations
1. Fix N+1 query in todos list endpoint
2. Add integration tests for rate limiting
3. Consider adding API versioning (/v1/todos)

## Verdict
✅ Approved with minor suggestions

五、进阶用法:自定义技能

Superpowers 支持创建自定义技能来扩展功能。

5.1 技能模板

# skills/my-custom-skill/SKILL.md

---
name: my-custom-skill
description: Description of what this skill does
triggers:
  - condition 1
  - condition 2
---

# My Custom Skill

## Purpose
Explain the purpose and when to use this skill.

## Triggers
This skill activates when:
- Trigger condition 1
- Trigger condition 2

## Workflow
1. Step 1
2. Step 2
3. Step 3

## Best Practices
- Practice 1
- Practice 2

## Anti-patterns to Avoid
- Anti-pattern 1
- Anti-pattern 2

5.2 示例:创建数据库迁移技能

# skills/database-migration/SKILL.md

---
name: database-migration
description: Guide database schema changes with proper migration workflow
triggers:
  - User mentions "migration", "alter table", "schema change"
  - Model definition changes detected
---

# Database Migration Skill

## Purpose
Ensure safe and reversible database schema changes.

## Workflow

### Phase 1: Plan the Migration
1. Document what's changing and why
2. Estimate impact (downtime, data migration)
3. Create rollback plan

### Phase 2: Create Migration
```bash
alembic revision -m "description_of_change"

Phase 3: Write Migration Code

def upgrade():
    op.add_column('users', sa.Column('phone', sa.String(20)))

def downgrade():
    op.drop_column('users', 'phone')

Phase 4: Test Migration

  1. Run on development database
  2. Verify application still works
  3. Test rollback

Phase 5: Deploy

  1. Backup production database
  2. Run migration during low-traffic period
  3. Monitor for issues

Checklist

  • Migration file created
  • Upgrade function tested
  • Downgrade function tested
  • Data migration handled
  • Rollback plan documented

## 六、性能与局限

### 6.1 性能考量

**优点**:
- 减少 AI 返工次数(一次做对)
- 提高代码质量(强制最佳实践)
- 可预测的开发流程

**开销**:
- 前期需要更多时间规划
- TDD 增加代码量(测试代码)
- 子代理通信有额外开销

### 6.2 适用场景

**适合使用 Superpowers**:
- 新项目开发
- 需要高质量代码的生产系统
- 团队协作项目
- 长期维护的项目

**不适合的场景**:
- 快速原型验证
- 一次性脚本
- 实验性探索

### 6.3 已知局限

1. **Token 消耗**:工作流增加了对话长度
2. **学习曲线**:需要理解技能系统
3. **平台依赖**:功能在不同平台表现可能略有差异

## 七、生态与社区

### 7.1 相关项目

| 项目 | 描述 |
|------|------|
| superpowers-marketplace | 官方插件市场 |
| claude-code-templates | 项目模板 |
| free-claude-code | 低成本 API 代理 |

### 7.2 社区资源

- Discord: https://discord.gg/35wsABTejz
- GitHub Issues: https://github.com/obra/superpowers/issues
- Release 通知: https://primeradiant.com/superpowers/

## 八、总结:AI 编程的"纪律时代"

Superpowers 的成功揭示了一个重要趋势:AI 编程的未来不在于"更强的模型",而在于"更好的流程"。

当 AI 编程助手从"玩具"变成"工具",质量比速度更重要。Superpowers 用 123K Star 证明:**开发者需要的不是一个能写代码的 AI,而是一个能可靠地写好代码的 AI**。

核心启示:

1. **流程大于提示词**:好的流程比精心设计的提示词更可靠
2. **测试驱动一切**:没有测试的代码只是"可能的代码"
3. **系统化胜过临时方案**:可重复的流程比灵光一现更有价值
4. **证据胜过断言**:用运行结果说话,而不是 AI 的"我相信"

如果你正在使用 AI 编程助手,强烈建议尝试 Superpowers。它不会让 AI 变得更聪明,但会让 AI 变得更可靠——而这正是生产环境真正需要的。

---

## 附录:快速参考

### 安装命令速查

```bash
# Claude Code
/plugin install superpowers@claude-plugins-official

# Codex
# 在对话中说:Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.codex/INSTALL.md

# Cursor
/add-plugin superpowers

# Gemini CLI
gemini extensions install https://github.com/obra/superpowers

常用技能速查

技能用途触发条件
brainstorming需求澄清新功能请求
writing-plans分解任务设计确认后
test-driven-developmentTDD 开发编写实现代码前
subagent-driven-development并行开发计划确认后
systematic-debugging调试问题测试失败或运行错误
requesting-code-review代码审查任务完成后

关键链接

推荐文章

pip安装到指定目录上
2024-11-17 16:17:25 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
JavaScript设计模式:单例模式
2024-11-18 10:57:41 +0800 CST
Node.js中接入微信支付
2024-11-19 06:28:31 +0800 CST
Vue3中的Slots有哪些变化?
2024-11-18 16:34:49 +0800 CST
html一份退出酒场的告知书
2024-11-18 18:14:45 +0800 CST
Elasticsearch 的索引操作
2024-11-19 03:41:41 +0800 CST
Boost.Asio: 一个美轮美奂的C++库
2024-11-18 23:09:42 +0800 CST
基于Webman + Vue3中后台框架SaiAdmin
2024-11-19 09:47:53 +0800 CST
如何在Rust中使用UUID?
2024-11-19 06:10:59 +0800 CST
介绍25个常用的正则表达式
2024-11-18 12:43:00 +0800 CST
Mysql允许外网访问详细流程
2024-11-17 05:03:26 +0800 CST
纯CSS实现3D云动画效果
2024-11-18 18:48:05 +0800 CST
Go 1.23 中的新包:unique
2024-11-18 12:32:57 +0800 CST
程序员茄子在线接单