sparc-workflow
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSPARC 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
undefinedbash
undefinedRun full SPARC development cycle
运行完整的SPARC开发周期
Run TDD-focused workflow
运行聚焦TDD的工作流
List available SPARC modes
列出可用的SPARC模式
undefinedundefinedWhen 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 directory structure
.agent-os/ - 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
阶段概览
| Phase | Focus | Output |
|---|---|---|
| Specification | What to build | Requirements document |
| Pseudocode | How it works | Algorithm design |
| Architecture | How it fits | System design |
| Refinement | Make it work | Tested implementation |
| Completion | Make it right | Production-ready code |
| 阶段 | 核心关注点 | 输出成果 |
|---|---|---|
| Specification(需求规格) | 明确要开发的内容 | 需求文档 |
| Pseudocode(伪代码) | 梳理实现逻辑 | 算法设计方案 |
| Architecture(架构设计) | 明确系统适配方式 | 系统设计方案 |
| Refinement(迭代优化) | 实现功能并验证 | 经过测试的实现代码 |
| Completion(完成交付) | 优化至生产可用 | 生产就绪代码 |
Phase 1: Specification
阶段1:需求规格
Purpose
目标
Define what needs to be built with clear, measurable requirements.
通过清晰、可衡量的需求定义要开发的内容。
Process
流程
- Gather requirements from user prompt
- Identify acceptance criteria
- Define scope (in-scope and out-of-scope)
- Document constraints and assumptions
- 从用户需求中收集信息
- 确定验收标准
- 定义范围(包含项与排除项)
- 记录约束条件与假设前提
Output Template
输出模板
markdown
undefinedmarkdown
undefinedFeature Specification
功能规格说明
Overview
概述
[One paragraph describing the feature]
[一段描述该功能的文字]
Requirements
需求
Functional Requirements
功能需求
- FR-1: [Requirement]
- FR-2: [Requirement]
- FR-3: [Requirement]
- FR-1: [需求内容]
- FR-2: [需求内容]
- FR-3: [需求内容]
Non-Functional Requirements
非功能需求
- NFR-1: Performance - [Requirement]
- NFR-2: Security - [Requirement]
- NFR-3: Usability - [Requirement]
- NFR-1: 性能 - [需求内容]
- NFR-2: 安全性 - [需求内容]
- 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]
undefinedSpecification 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
流程
- Break down requirements into logical steps
- Write language-agnostic pseudocode
- Identify edge cases
- Design error handling
- 将需求拆解为逻辑步骤
- 编写与语言无关的伪代码
- 识别边界情况
- 设计错误处理逻辑
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
伪代码最佳实践
- Be explicit: Show all decision points
- Include error handling: Show how errors are managed
- Note complexity: O(n), O(n²), etc.
- Identify data structures: Lists, maps, trees
- Show edge cases: Empty input, single item, maximum size
- 表述明确:展示所有决策点
- 包含错误处理:说明错误的处理方式
- 标注复杂度:如O(n)、O(n²)等
- 明确数据结构:如列表、映射、树等
- 覆盖边界情况:空输入、单个条目、最大规模输入
Output Template
输出模板
markdown
undefinedmarkdown
undefinedPseudocode 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
边界情况
| Case | Input | Expected 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)
undefinedPhase 3: Architecture
阶段3:架构设计
Purpose
目标
Design how the feature fits into the system architecture.
设计该功能如何融入现有系统架构。
Process
流程
- Identify affected components
- Design interfaces and contracts
- Plan data flow
- Consider dependencies
- 识别受影响的组件
- 设计接口与契约
- 规划数据流
- 考虑依赖关系
Architecture Considerations
架构设计要点
markdown
undefinedmarkdown
undefinedComponent 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 # 数据模型
```
undefinedPhase 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流程
-
Write Test Firstpython
def test_process_valid_input(): """Test processing with valid input.""" processor = Processor() result = processor.process([1, 2, 3]) assert result == [2, 4, 6] -
Run Test (Should Fail)bash
pytest tests/test_processor.py -v # Expected: FAILED -
Write Minimal Implementationpython
class Processor: def process(self, data): return [x * 2 for x in data] -
Run Test (Should Pass)bash
pytest tests/test_processor.py -v # Expected: PASSED -
Refactorpython
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]
-
先编写测试用例python
def test_process_valid_input(): """测试处理有效输入的场景。""" processor = Processor() result = processor.process([1, 2, 3]) assert result == [2, 4, 6] -
运行测试(应失败)bash
pytest tests/test_processor.py -v # 预期结果: FAILED -
编写最少实现代码python
class Processor: def process(self, data): return [x * 2 for x in data] -
运行测试(应通过)bash
pytest tests/test_processor.py -v # 预期结果: PASSED -
重构代码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
undefinedpython
undefinedUnit 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."""
...
undefinedclass TestProcessorPerformance:
def test_large_dataset_performance(self):
"""测试处理大型数据集的性能。"""
...
undefinedPhase 5: Completion
阶段5:完成交付
Purpose
目标
Finalize for production: documentation, cleanup, and verification.
完成生产就绪的最终准备:文档编写、代码清理与验证。
Completion Checklist
完成交付检查清单
markdown
undefinedmarkdown
undefinedCode 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- 配置已文档化
- 迁移脚本已准备(如需要)
- 回滚计划已制定
- 监控已部署
undefinedUsing SPARC with Claude Flow
与Claude Flow结合使用SPARC
Start SPARC Workflow
启动SPARC工作流
bash
undefinedbash
undefinedAvailable Modes
可用模式
| Mode | Focus |
|---|---|
| Full development cycle |
| API development |
| UI development |
| Testing focus |
| Code improvement |
| 模式 | 核心关注点 |
|---|---|
| 完整开发周期 |
| API开发 |
| UI开发 |
| 聚焦测试 |
| 代码优化 |
TDD Mode
TDD模式
bash
undefinedbash
undefinedSPARC 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
undefinedbash
undefinedUse the create-spec workflow
使用create-spec工作流
Reference: @~/.agent-os/instructions/create-spec.md
参考文档: @~/.agent-os/instructions/create-spec.md
undefinedundefinedExecuting Tasks
执行任务
bash
undefinedbash
undefinedUse the execute-tasks workflow
使用execute-tasks工作流
Reference: @~/.agent-os/instructions/execute-tasks.md
参考文档: @~/.agent-os/instructions/execute-tasks.md
undefinedundefinedError 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
需求规格
- Write requirements from user perspective
- Make every requirement testable
- Explicitly define boundaries
- Get stakeholder approval
- 从用户视角编写需求
- 确保每个需求均可测试
- 明确定义边界
- 获取相关方批准
Pseudocode
伪代码
- Stay language-agnostic
- Show all decision branches
- Include error paths
- Note time/space complexity
- 保持与语言无关
- 展示所有决策分支
- 包含错误处理路径
- 标注时间/空间复杂度
Architecture
架构设计
- Keep components loosely coupled
- Design for testability
- Plan for scalability
- Document dependencies
- 保持组件低耦合
- 设计时考虑可测试性
- 规划可扩展性
- 记录依赖关系
Refinement
迭代优化
- One test per behavior
- Test edge cases first
- Keep tests isolated
- Maintain fast test suite
- 每个测试用例对应一个行为
- 优先测试边界情况
- 保持测试用例独立
- 维护快速运行的测试套件
Completion
完成交付
- Review all checklist items
- Run full test suite
- Update documentation
- Plan deployment
- 检查所有清单项
- 运行完整测试套件
- 更新所有文档
- 规划部署方案
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集成