sparc-workflow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SPARC Workflow Skill

SPARC工作流Skill

Systematic software development through Specification, Pseudocode, Architecture, Refinement (TDD), and Completion phases.
通过Specification、Pseudocode、Architecture、Refinement(TDD)和Completion五个阶段实现系统化软件开发。

Quick Start

快速开始

bash
undefined
bash
undefined

Run full SPARC development cycle

运行完整的SPARC开发周期

Run TDD-focused workflow

运行聚焦TDD的工作流

List available SPARC modes

列出可用的SPARC模式

undefined
undefined

When to Use

适用场景

  • Implementing a new feature from scratch
  • Complex problem requiring structured analysis before coding
  • Building production-quality code with comprehensive tests
  • Refactoring existing code systematically
  • API or UI development requiring clear specifications
  • 从零开始实现新功能
  • 需要先进行结构化分析的复杂问题
  • 构建带有全面测试的生产级代码
  • 系统化重构现有代码
  • 需要明确规格的API或UI开发

Prerequisites

前置条件

  • Understanding of TDD (Test-Driven Development)
  • Project with
    .agent-os/
    directory structure
  • Access to testing framework (pytest, jest, etc.)
  • 理解TDD(测试驱动开发)概念
  • 项目具备
    .agent-os/
    目录结构
  • 可访问测试框架(如pytest、jest等)

Overview

概述

SPARC is a systematic methodology for software development that ensures quality through structured phases. Each phase builds on the previous, creating well-documented, well-tested code.
SPARC是一种系统化的软件开发方法论,通过结构化的各个阶段确保代码质量。每个阶段都基于前一阶段的成果,最终生成文档完善、测试充分的代码。

SPARC Phases

SPARC各阶段

┌─────────────────────────────────────────────────────────────────┐
│  S → P → A → R → C                                              │
│                                                                  │
│  Specification → Pseudocode → Architecture → Refinement → Done  │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│  S → P → A → R → C                                              │
│                                                                  │
│  Specification → Pseudocode → Architecture → Refinement → Done  │
└─────────────────────────────────────────────────────────────────┘

Phase Overview

阶段概览

PhaseFocusOutput
SpecificationWhat to buildRequirements document
PseudocodeHow it worksAlgorithm design
ArchitectureHow it fitsSystem design
RefinementMake it workTested implementation
CompletionMake it rightProduction-ready code
阶段核心关注点输出成果
Specification(需求规格)明确要开发的内容需求文档
Pseudocode(伪代码)梳理实现逻辑算法设计方案
Architecture(架构设计)明确系统适配方式系统设计方案
Refinement(迭代优化)实现功能并验证经过测试的实现代码
Completion(完成交付)优化至生产可用生产就绪代码

Phase 1: Specification

阶段1:需求规格

Purpose

目标

Define what needs to be built with clear, measurable requirements.
通过清晰、可衡量的需求定义要开发的内容。

Process

流程

  1. Gather requirements from user prompt
  2. Identify acceptance criteria
  3. Define scope (in-scope and out-of-scope)
  4. Document constraints and assumptions
  1. 从用户需求中收集信息
  2. 确定验收标准
  3. 定义范围(包含项与排除项)
  4. 记录约束条件与假设前提

Output Template

输出模板

markdown
undefined
markdown
undefined

Feature Specification

功能规格说明

Overview

概述

[One paragraph describing the feature]
[一段描述该功能的文字]

Requirements

需求

Functional Requirements

功能需求

  1. FR-1: [Requirement]
  2. FR-2: [Requirement]
  3. FR-3: [Requirement]
  1. FR-1: [需求内容]
  2. FR-2: [需求内容]
  3. FR-3: [需求内容]

Non-Functional Requirements

非功能需求

  1. NFR-1: Performance - [Requirement]
  2. NFR-2: Security - [Requirement]
  3. NFR-3: Usability - [Requirement]
  1. NFR-1: 性能 - [需求内容]
  2. NFR-2: 安全性 - [需求内容]
  3. NFR-3: 易用性 - [需求内容]

Scope

范围

In Scope

包含项

  • [Item 1]
  • [Item 2]
  • [项1]
  • [项2]

Out of Scope

排除项

  • [Item 1]
  • [Item 2]
  • [项1]
  • [项2]

Acceptance Criteria

验收标准

  • AC-1: [Testable criterion]
  • AC-2: [Testable criterion]
  • AC-3: [Testable criterion]
  • AC-1: [可测试的标准]
  • AC-2: [可测试的标准]
  • AC-3: [可测试的标准]

Constraints

约束条件

  • [Technical constraint]
  • [Business constraint]
  • [技术约束]
  • [业务约束]

Assumptions

假设前提

  • [Assumption 1]
  • [Assumption 2]
undefined
  • [假设1]
  • [假设2]
undefined

Specification Checklist

需求规格检查清单

  • All requirements are clear and unambiguous
  • Each requirement is testable
  • Scope is explicitly defined
  • Constraints are documented
  • User stories follow "As a... I want... So that..." format
  • 所有需求清晰且无歧义
  • 每个需求均可测试
  • 范围已明确定义
  • 约束条件已记录
  • 用户故事遵循“作为...,我希望...,以便...”格式

Phase 2: Pseudocode

阶段2:伪代码

Purpose

目标

Design the algorithm and logic before implementation.
在实现前设计算法与逻辑。

Process

流程

  1. Break down requirements into logical steps
  2. Write language-agnostic pseudocode
  3. Identify edge cases
  4. Design error handling
  1. 将需求拆解为逻辑步骤
  2. 编写与语言无关的伪代码
  3. 识别边界情况
  4. 设计错误处理逻辑

Pseudocode Guidelines

伪代码指南

FUNCTION process_data(input_data):
    // Validate input
    IF input_data is empty:
        RAISE ValidationError("Input cannot be empty")

    // Initialize result
    result = EMPTY_LIST

    // Process each item
    FOR EACH item IN input_data:
        // Check conditions
        IF item.meets_criteria():
            processed_item = transform(item)
            APPEND processed_item TO result

    RETURN result

FUNCTION transform(item):
    // Apply transformation logic
    new_value = item.value * MULTIPLIER
    RETURN Item(new_value, item.metadata)
FUNCTION process_data(input_data):
    // 验证输入
    IF input_data is empty:
        RAISE ValidationError("Input cannot be empty")

    // 初始化结果
    result = EMPTY_LIST

    // 处理每个条目
    FOR EACH item IN input_data:
        // 检查条件
        IF item.meets_criteria():
            processed_item = transform(item)
            APPEND processed_item TO result

    RETURN result

FUNCTION transform(item):
    // 应用转换逻辑
    new_value = item.value * MULTIPLIER
    RETURN Item(new_value, item.metadata)

Pseudocode Best Practices

伪代码最佳实践

  1. Be explicit: Show all decision points
  2. Include error handling: Show how errors are managed
  3. Note complexity: O(n), O(n²), etc.
  4. Identify data structures: Lists, maps, trees
  5. Show edge cases: Empty input, single item, maximum size
  1. 表述明确:展示所有决策点
  2. 包含错误处理:说明错误的处理方式
  3. 标注复杂度:如O(n)、O(n²)等
  4. 明确数据结构:如列表、映射、树等
  5. 覆盖边界情况:空输入、单个条目、最大规模输入

Output Template

输出模板

markdown
undefined
markdown
undefined

Pseudocode Design

伪代码设计

Main Algorithm

主算法

``` FUNCTION main_feature(params): [Algorithm steps] ```
``` FUNCTION main_feature(params): [算法步骤] ```

Helper Functions

辅助函数

``` FUNCTION helper_one(input): [Steps]
FUNCTION helper_two(input): [Steps] ```
``` FUNCTION helper_one(input): [步骤]
FUNCTION helper_two(input): [步骤] ```

Error Handling

错误处理

``` TRY: [Main logic] CATCH ValidationError: [Handle validation] CATCH ProcessingError: [Handle processing] FINALLY: [Cleanup] ```
``` TRY: [主逻辑] CATCH ValidationError: [处理验证错误] CATCH ProcessingError: [处理处理错误] FINALLY: [清理操作] ```

Edge Cases

边界情况

CaseInputExpected Output
Empty[][]
Single[1][processed_1]
Maximum[1..10000][processed_all]
场景输入预期输出
空输入[][]
单个条目[1][processed_1]
最大规模[1..10000][processed_all]

Complexity Analysis

复杂度分析

  • Time: O(n)
  • Space: O(n)
undefined
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
undefined

Phase 3: Architecture

阶段3:架构设计

Purpose

目标

Design how the feature fits into the system architecture.
设计该功能如何融入现有系统架构。

Process

流程

  1. Identify affected components
  2. Design interfaces and contracts
  3. Plan data flow
  4. Consider dependencies
  1. 识别受影响的组件
  2. 设计接口与契约
  3. 规划数据流
  4. 考虑依赖关系

Architecture Considerations

架构设计要点

markdown
undefined
markdown
undefined

Component Design

组件设计

New Components

新增组件

  • ComponentA: [Purpose]
  • ComponentB: [Purpose]
  • ComponentA: [用途]
  • ComponentB: [用途]

Modified Components

修改组件

  • ExistingComponent: [Changes needed]
  • ExistingComponent: [所需修改]

Interface Design

接口设计

```python class IProcessor(Protocol): def process(self, data: InputData) -> OutputData: """Process input and return output.""" ...
def validate(self, data: InputData) -> bool:
    """Validate input data."""
    ...
```
```python class IProcessor(Protocol): def process(self, data: InputData) -> OutputData: """处理输入并返回输出。""" ...
def validate(self, data: InputData) -> bool:
    """验证输入数据。"""
    ...
```

Data Flow

数据流

``` Input → Validator → Processor → Transformer → Output ↓ ↓ Logger Cache ```
``` 输入 → 验证器 → 处理器 → 转换器 → 输出 ↓ ↓ 日志器 缓存 ```

Dependencies

依赖关系

Internal

内部依赖

  • module_a (version ≥ 1.2.0)
  • module_b
  • module_a(版本 ≥ 1.2.0)
  • module_b

External

外部依赖

  • library_x (version 2.0.0)
  • library_x(版本 2.0.0)

File Structure

文件结构

``` src/ └── feature_name/ ├── init.py ├── processor.py # Main processing logic ├── validator.py # Input validation ├── transformer.py # Data transformation └── models.py # Data models ```
undefined
``` src/ └── feature_name/ ├── init.py ├── processor.py # 核心处理逻辑 ├── validator.py # 输入验证 ├── transformer.py # 数据转换 └── models.py # 数据模型 ```
undefined

Phase 4: Refinement (TDD)

阶段4:迭代优化(TDD)

Purpose

目标

Implement the feature using Test-Driven Development.
通过测试驱动开发(TDD)实现功能。

TDD Cycle

TDD循环

┌──────────────┐
│   1. RED     │  Write failing test
└──────┬───────┘
┌──────────────┐
│   2. GREEN   │  Write minimal code to pass
└──────┬───────┘
┌──────────────┐
│  3. REFACTOR │  Improve code quality
└──────┬───────┘
       └──────────► Repeat
┌──────────────┐
│   1. RED     │  编写失败的测试用例
└──────┬───────┘
┌──────────────┐
│   2. GREEN   │  编写最少代码使测试通过
└──────┬───────┘
┌──────────────┐
│  3. REFACTOR │  提升代码质量
└──────┬───────┘
       └──────────► 重复循环

TDD Process

TDD流程

  1. Write Test First
    python
    def test_process_valid_input():
        """Test processing with valid input."""
        processor = Processor()
        result = processor.process([1, 2, 3])
        assert result == [2, 4, 6]
  2. Run Test (Should Fail)
    bash
    pytest tests/test_processor.py -v
    # Expected: FAILED
  3. Write Minimal Implementation
    python
    class Processor:
        def process(self, data):
            return [x * 2 for x in data]
  4. Run Test (Should Pass)
    bash
    pytest tests/test_processor.py -v
    # Expected: PASSED
  5. Refactor
    python
    class Processor:
        def __init__(self, multiplier: int = 2):
            self.multiplier = multiplier
    
        def process(self, data: List[int]) -> List[int]:
            return [x * self.multiplier for x in data]
  1. 先编写测试用例
    python
    def test_process_valid_input():
        """测试处理有效输入的场景。"""
        processor = Processor()
        result = processor.process([1, 2, 3])
        assert result == [2, 4, 6]
  2. 运行测试(应失败)
    bash
    pytest tests/test_processor.py -v
    # 预期结果: FAILED
  3. 编写最少实现代码
    python
    class Processor:
        def process(self, data):
            return [x * 2 for x in data]
  4. 运行测试(应通过)
    bash
    pytest tests/test_processor.py -v
    # 预期结果: PASSED
  5. 重构代码
    python
    class Processor:
        def __init__(self, multiplier: int = 2):
            self.multiplier = multiplier
    
        def process(self, data: List[int]) -> List[int]:
            return [x * self.multiplier for x in data]

Test Categories

测试分类

python
undefined
python
undefined

Unit Tests

单元测试

class TestProcessor: def test_process_valid_input(self): """Test with valid input.""" ...
def test_process_empty_input(self):
    """Test with empty input."""
    ...

def test_process_invalid_input(self):
    """Test with invalid input raises error."""
    ...
class TestProcessor: def test_process_valid_input(self): """测试有效输入场景。""" ...
def test_process_empty_input(self):
    """测试空输入场景。"""
    ...

def test_process_invalid_input(self):
    """测试无效输入是否抛出错误。"""
    ...

Integration Tests

集成测试

class TestProcessorIntegration: def test_end_to_end_workflow(self): """Test complete workflow.""" ...
class TestProcessorIntegration: def test_end_to_end_workflow(self): """测试完整工作流。""" ...

Performance Tests

性能测试

class TestProcessorPerformance: def test_large_dataset_performance(self): """Test performance with large dataset.""" ...
undefined
class TestProcessorPerformance: def test_large_dataset_performance(self): """测试处理大型数据集的性能。""" ...
undefined

Phase 5: Completion

阶段5:完成交付

Purpose

目标

Finalize for production: documentation, cleanup, and verification.
完成生产就绪的最终准备:文档编写、代码清理与验证。

Completion Checklist

完成交付检查清单

markdown
undefined
markdown
undefined

Code Quality

代码质量

  • All tests passing
  • Test coverage ≥ 80%
  • No linting errors
  • Type hints complete
  • Docstrings complete
  • 所有测试通过
  • 测试覆盖率 ≥ 80%
  • 无代码检查错误
  • 类型提示完整
  • 文档字符串完整

Documentation

文档

  • README updated
  • API documentation
  • Usage examples
  • Changelog entry
  • README已更新
  • API文档已完善
  • 包含使用示例
  • 更新变更日志

Security

安全性

  • Input validation
  • Error messages safe
  • No hardcoded secrets
  • Dependencies audited
  • 已实现输入验证
  • 错误信息安全(不泄露敏感内容)
  • 无硬编码密钥
  • 依赖已审计

Performance

性能

  • Benchmarks run
  • Memory usage checked
  • No N+1 queries
  • Caching implemented (if needed)
  • 已运行基准测试
  • 已检查内存使用情况
  • 无N+1查询问题
  • 已实现缓存(如需要)

Deployment

部署

  • Configuration documented
  • Migration scripts (if needed)
  • Rollback plan
  • Monitoring in place
undefined
  • 配置已文档化
  • 迁移脚本已准备(如需要)
  • 回滚计划已制定
  • 监控已部署
undefined

Using SPARC with Claude Flow

与Claude Flow结合使用SPARC

Start SPARC Workflow

启动SPARC工作流

bash
undefined
bash
undefined

Available Modes

可用模式

ModeFocus
dev
Full development cycle
api
API development
ui
UI development
test
Testing focus
refactor
Code improvement
模式核心关注点
dev
完整开发周期
api
API开发
ui
UI开发
test
聚焦测试
refactor
代码优化

TDD Mode

TDD模式

bash
undefined
bash
undefined

SPARC File Locations

SPARC文件存储位置

.agent-os/
├── specs/
│   └── feature-name/
│       ├── spec.md              # Specification
│       ├── tasks.md             # Task breakdown
│       └── sub-specs/
│           ├── pseudocode.md    # Pseudocode
│           ├── architecture.md  # Architecture
│           ├── tests.md         # Test spec
│           └── api-spec.md      # API spec (if applicable)
└── product/
    └── decisions.md             # Decision log
.agent-os/
├── specs/
│   └── feature-name/
│       ├── spec.md              # 需求规格
│       ├── tasks.md             # 任务拆解
│       └── sub-specs/
│           ├── pseudocode.md    # 伪代码
│           ├── architecture.md  # 架构设计
│           ├── tests.md         # 测试规格
│           └── api-spec.md      # API规格(如适用)
└── product/
    └── decisions.md             # 决策日志

Execution Checklist

执行检查清单

  • Requirements gathered and documented in spec.md
  • Pseudocode designed with edge cases identified
  • Architecture defined with clear interfaces
  • Tests written BEFORE implementation (TDD)
  • Implementation passes all tests
  • Code refactored for quality
  • Documentation complete
  • Code review completed
  • Deployed to staging/production
  • 需求已收集并记录在spec.md中
  • 伪代码已设计并识别边界情况
  • 架构已定义且接口清晰
  • 测试用例在实现前编写(TDD)
  • 实现代码通过所有测试
  • 代码已重构以提升质量
  • 文档已完成
  • 代码评审已完成
  • 已部署至预发布/生产环境

Integration with Agent OS

与Agent OS集成

Creating a Spec

创建规格说明

bash
undefined
bash
undefined

Use the create-spec workflow

使用create-spec工作流

Reference: @~/.agent-os/instructions/create-spec.md

参考文档: @~/.agent-os/instructions/create-spec.md

undefined
undefined

Executing Tasks

执行任务

bash
undefined
bash
undefined

Use the execute-tasks workflow

使用execute-tasks工作流

Reference: @~/.agent-os/instructions/execute-tasks.md

参考文档: @~/.agent-os/instructions/execute-tasks.md

undefined
undefined

Error Handling

错误处理

Specification Phase Issues

需求规格阶段问题

  • Unclear requirements: Ask clarifying questions before proceeding
  • Scope creep: Document out-of-scope items explicitly
  • Missing acceptance criteria: Derive from requirements
  • 需求不明确:在继续前提出澄清问题
  • 范围蔓延:明确记录排除项
  • 缺失验收标准:从需求中推导验收标准

TDD Phase Issues

TDD阶段问题

  • Tests too complex: Break into smaller units
  • Flaky tests: Isolate external dependencies with mocks
  • Low coverage: Add edge case tests
  • 测试用例过于复杂:拆分为更小的单元测试
  • 测试用例不稳定:使用Mock隔离外部依赖
  • 覆盖率低:添加边界情况测试用例

Completion Phase Issues

完成交付阶段问题

  • Documentation gaps: Review against checklist
  • Performance issues: Profile and optimize hot paths
  • Security concerns: Run security audit tools
  • 文档缺失:对照检查清单补充
  • 性能问题:分析并优化热点路径
  • 安全隐患:运行安全审计工具

Metrics & Success Criteria

指标与成功标准

  • Test Coverage: >= 80% for all new code
  • Code Quality: Zero linting errors, all type hints present
  • Documentation: 100% of public APIs documented
  • Performance: Meets defined NFR benchmarks
  • TDD Adherence: Tests written before implementation
  • 测试覆盖率:所有新代码≥80%
  • 代码质量:无代码检查错误,类型提示完整
  • 文档:100%的公共API已文档化
  • 性能:满足定义的非功能需求基准
  • TDD合规性:测试用例在实现前编写

Best Practices

最佳实践

Specification

需求规格

  1. Write requirements from user perspective
  2. Make every requirement testable
  3. Explicitly define boundaries
  4. Get stakeholder approval
  1. 从用户视角编写需求
  2. 确保每个需求均可测试
  3. 明确定义边界
  4. 获取相关方批准

Pseudocode

伪代码

  1. Stay language-agnostic
  2. Show all decision branches
  3. Include error paths
  4. Note time/space complexity
  1. 保持与语言无关
  2. 展示所有决策分支
  3. 包含错误处理路径
  4. 标注时间/空间复杂度

Architecture

架构设计

  1. Keep components loosely coupled
  2. Design for testability
  3. Plan for scalability
  4. Document dependencies
  1. 保持组件低耦合
  2. 设计时考虑可测试性
  3. 规划可扩展性
  4. 记录依赖关系

Refinement

迭代优化

  1. One test per behavior
  2. Test edge cases first
  3. Keep tests isolated
  4. Maintain fast test suite
  1. 每个测试用例对应一个行为
  2. 优先测试边界情况
  3. 保持测试用例独立
  4. 维护快速运行的测试套件

Completion

完成交付

  1. Review all checklist items
  2. Run full test suite
  3. Update documentation
  4. Plan deployment
  1. 检查所有清单项
  2. 运行完整测试套件
  3. 更新所有文档
  4. 规划部署方案

Integration Points

集成点

MCP Tools

MCP工具

javascript
// Start SPARC mode
    mode: "dev",
    task_description: "Implement user authentication"
})

// Orchestrate tasks
    task: "Complete SPARC refinement phase",
    strategy: "sequential",
    priority: "high"
})
javascript
// 启动SPARC模式
    mode: "dev",
    task_description: "Implement user authentication"
})

// 编排任务
    task: "Complete SPARC refinement phase",
    strategy: "sequential",
    priority: "high"
})

Related Skills

相关Skill

  • agent-orchestration - Multi-agent coordination
  • compliance-check - Standards verification
  • repo-sync - Repository management
  • agent-orchestration - 多Agent协调
  • compliance-check - 标准验证
  • repo-sync - 仓库管理

References

参考文档

  • Agent OS Create Spec
  • Agent OS Execute Tasks

  • Agent OS Create Spec
  • Agent OS Execute Tasks

Version History

版本历史

  • 1.1.0 (2026-01-02): Upgraded to SKILL_TEMPLATE_v2 format - added Quick Start, When to Use, Execution Checklist, Error Handling, Metrics, Integration Points, MCP hooks
  • 1.0.0 (2024-10-15): Initial release with 5 SPARC phases, TDD integration, Claude Flow support, Agent OS integration
  • 1.1.0 (2026-01-02): 升级为SKILL_TEMPLATE_v2格式 - 添加快速开始、适用场景、执行检查清单、错误处理、指标、集成点、MCP钩子
  • 1.0.0 (2024-10-15): 初始版本,包含5个SPARC阶段、TDD集成、Claude Flow支持、Agent OS集成