主题
OpenSpec 使用示例
本文档提供 OpenSpec 的实际使用示例,帮助你快速上手规范驱动开发。
快速开始
完整工作流概览
OpenSpec 的工作流包含四个主要步骤:
- 起草提案 - 创建变更提案,描述你想要实现的功能
- 审核对齐 - 与 AI 助手一起审核和完善规范
- 实现任务 - 按照任务清单逐步实现功能
- 归档变更 - 将完成的变更合并回规范源
第一个变更示例
假设你想为项目添加用户个人资料搜索过滤功能。
步骤 1:起草提案
向 AI 助手发送请求:
text
你: 创建一个 OpenSpec 变更提案,添加按角色和团队搜索用户资料的过滤功能
(支持斜杠命令的工具可使用: /openspec:proposal 添加用户资料搜索过滤)
AI: 我将为用户资料过滤功能创建 OpenSpec 变更提案。
*创建 openspec/changes/add-profile-filters/ 目录,包含 proposal.md、tasks.md 和规范增量*步骤 2:验证和审核
检查变更是否正确创建:
bash
$ openspec list
# 输出示例:
# Active changes:
# - add-profile-filters (created: 2025-01-15)
$ openspec validate add-profile-filters
# 输出示例:
# ✓ Proposal format valid
# ✓ Tasks format valid
# ✓ Spec deltas valid
$ openspec show add-profile-filters
# 显示提案详情、任务列表和规范增量步骤 3:完善规范
与 AI 迭代完善规范:
text
你: 能否为角色和团队过滤器添加验收标准?
AI: 我将更新规范增量,添加角色和团队过滤器的场景。
*编辑 openspec/changes/add-profile-filters/specs/profile/spec.md 和 tasks.md*步骤 4:实现变更
规范确认后开始实现:
text
你: 规范看起来不错,开始实现这个变更。
(支持斜杠命令的工具可使用: /openspec:apply add-profile-filters)
AI: 我将按照 add-profile-filters 变更中的任务进行实现。
*实现 openspec/changes/add-profile-filters/tasks.md 中的任务*
*标记任务完成: Task 1.1 ✓, Task 1.2 ✓, Task 2.1 ✓...*步骤 5:归档变更
实现完成后归档:
text
AI: 所有任务已完成,实现已就绪。
你: 请归档这个变更
(支持斜杠命令的工具可使用: /openspec:archive add-profile-filters)
AI: 我将归档 add-profile-filters 变更。
*运行: openspec archive add-profile-filters --yes*
✓ 变更归档成功。规范已更新。准备好进行下一个功能!或者在终端手动运行:
bash
$ openspec archive add-profile-filters --yes
# 输出示例:
# ✓ Archived change: add-profile-filters
# ✓ Updated specs: profile/spec.md
# ✓ Change moved to: openspec/archive/add-profile-filters/场景一:添加新功能 - 双因素认证
这个示例展示如何使用 OpenSpec 为现有系统添加全新的双因素认证(2FA)功能。
背景
你的项目已有基本的用户认证系统,现在需要添加双因素认证以提高安全性。
步骤 1:创建变更提案
text
你: 创建一个 OpenSpec 变更提案,为用户登录添加双因素认证功能,
支持 TOTP(基于时间的一次性密码)和短信验证两种方式。AI 将创建以下文件结构:
openspec/changes/add-2fa/
├── proposal.md
├── tasks.md
├── design.md
└── specs/
└── auth/
└── spec.md步骤 2:查看生成的提案
bash
$ openspec show add-2faproposal.md 内容示例:
markdown
# Change Proposal: Add Two-Factor Authentication
## Summary
Add two-factor authentication (2FA) to enhance login security.
## Motivation
Current single-factor authentication is vulnerable to credential theft.
2FA adds an additional security layer.
## Scope
- TOTP support via authenticator apps
- SMS verification as fallback
- User preference management
- Recovery codes for account recovery步骤 3:审核规范增量
specs/auth/spec.md 增量内容:
markdown
# Delta for Auth
## ADDED Requirements
### Requirement: Two-Factor Authentication Setup
The system MUST allow users to enable 2FA on their account.
#### Scenario: Enable TOTP
- WHEN a user requests to enable TOTP
- THEN the system SHALL generate a secret key
- AND display a QR code for authenticator app scanning
- AND require verification of the first code before activation
#### Scenario: Enable SMS verification
- WHEN a user requests to enable SMS 2FA
- THEN the system SHALL verify the phone number
- AND send a test verification code
### Requirement: Two-Factor Authentication Login
The system MUST require 2FA verification during login for enabled accounts.
#### Scenario: TOTP verification
- WHEN a user with TOTP enabled submits valid credentials
- THEN the system SHALL prompt for TOTP code
- AND verify the code before granting access
#### Scenario: SMS verification
- WHEN a user with SMS 2FA enabled submits valid credentials
- THEN the system SHALL send an SMS code
- AND verify the code before granting access步骤 4:查看任务清单
bash
$ cat openspec/changes/add-2fa/tasks.mdtasks.md 内容示例:
markdown
## 1. Database Setup
- [ ] 1.1 Add 2FA settings columns to users table
- [ ] 1.2 Create recovery_codes table
- [ ] 1.3 Create 2fa_verification_logs table
## 2. Backend Implementation
- [ ] 2.1 Implement TOTP secret generation and QR code
- [ ] 2.2 Implement TOTP verification endpoint
- [ ] 2.3 Implement SMS sending service integration
- [ ] 2.4 Implement SMS verification endpoint
- [ ] 2.5 Modify login flow to check 2FA status
- [ ] 2.6 Implement recovery code generation and usage
## 3. Frontend Updates
- [ ] 3.1 Create 2FA setup wizard component
- [ ] 3.2 Create TOTP input component
- [ ] 3.3 Create SMS verification component
- [ ] 3.4 Update login flow UI for 2FA challenge
- [ ] 3.5 Create recovery code display and download步骤 5:实现并归档
bash
# 验证规范格式
$ openspec validate add-2fa
# ✓ All validations passed
# 实现完成后归档
$ openspec archive add-2fa --yes
# ✓ Archived change: add-2fa
# ✓ Updated specs: auth/spec.md场景二:修改现有功能 - API 分页优化
这个示例展示如何使用 OpenSpec 修改现有的 API 功能,将简单的分页改为游标分页以提高性能。
背景
你的项目有一个用户列表 API,目前使用基于偏移量的分页(offset-based pagination),在数据量大时性能较差。需要改为游标分页(cursor-based pagination)。
步骤 1:创建变更提案
text
你: 创建一个 OpenSpec 变更提案,将用户列表 API 从偏移量分页改为游标分页,
以提高大数据集的查询性能。需要保持向后兼容。步骤 2:查看生成的规范增量
这次是修改现有功能,所以规范增量会包含 MODIFIED 部分:
bash
$ openspec show optimize-paginationspecs/api/spec.md 增量内容:
markdown
# Delta for API
## MODIFIED Requirements
### Requirement: User List Pagination
The system SHALL support cursor-based pagination for the user list endpoint.
#### Scenario: Cursor pagination (NEW)
- WHEN a client requests users with a cursor parameter
- THEN the system SHALL return users after the cursor position
- AND include next_cursor in the response
- AND include has_more boolean flag
#### Scenario: Legacy offset pagination (DEPRECATED)
- WHEN a client requests users with offset/limit parameters
- THEN the system SHALL continue to support offset pagination
- AND log a deprecation warning
- AND include deprecation notice in response headers
#### Scenario: Default behavior
- WHEN a client requests users without pagination parameters
- THEN the system SHALL use cursor pagination by default
- AND return first page with default limit
## ADDED Requirements
### Requirement: Pagination Performance
The system MUST maintain consistent query performance regardless of page position.
#### Scenario: Deep pagination
- WHEN a client requests a page deep in the dataset
- THEN the query time SHALL NOT increase linearly with offset
- AND response time SHALL remain under 200ms for datasets up to 1M records步骤 3:查看任务清单
tasks.md 内容示例:
markdown
## 1. Database Optimization
- [ ] 1.1 Add index on cursor column (created_at, id)
- [ ] 1.2 Analyze and optimize existing queries
## 2. Backend Implementation
- [ ] 2.1 Implement cursor encoding/decoding utility
- [ ] 2.2 Modify user list query to support cursor pagination
- [ ] 2.3 Add backward compatibility layer for offset pagination
- [ ] 2.4 Add deprecation logging for offset pagination
- [ ] 2.5 Update API response schema with cursor fields
## 3. Documentation Updates
- [ ] 3.1 Update API documentation with new pagination format
- [ ] 3.2 Add migration guide for API consumers
- [ ] 3.3 Document deprecation timeline for offset pagination
## 4. Testing
- [ ] 4.1 Add performance tests for cursor pagination
- [ ] 4.2 Add backward compatibility tests
- [ ] 4.3 Add edge case tests (empty results, single item, etc.)步骤 4:迭代完善
text
你: 请在规范中添加错误处理场景,比如无效游标的情况。
AI: 我将更新规范增量,添加错误处理场景。更新后的规范增量:
markdown
## ADDED Requirements
### Requirement: Pagination Error Handling
The system MUST handle invalid pagination parameters gracefully.
#### Scenario: Invalid cursor
- WHEN a client provides an invalid or expired cursor
- THEN the system SHALL return 400 Bad Request
- AND include error message explaining the issue
- AND suggest using fresh request without cursor
#### Scenario: Invalid limit
- WHEN a client provides limit outside allowed range (1-100)
- THEN the system SHALL clamp to nearest valid value
- AND include warning in response headers步骤 5:验证和归档
bash
# 验证所有规范格式正确
$ openspec validate optimize-pagination
# ✓ Proposal format valid
# ✓ Tasks format valid
# ✓ Spec deltas valid
# ✓ MODIFIED requirements reference existing specs
# 实现完成后归档
$ openspec archive optimize-pagination --yes
# ✓ Archived change: optimize-pagination
# ✓ Updated specs: api/spec.md
# ✓ Change moved to: openspec/archive/optimize-pagination/常见问题与解决方案
Q1: AI 助手没有显示 OpenSpec 斜杠命令
问题描述: 运行 openspec init 后,AI 助手中没有出现 /openspec:proposal 等命令。
解决方案:
- 重启 AI 助手(斜杠命令在启动时加载)
- 确认
openspec init成功完成 - 检查是否选择了正确的 AI 工具
bash
# 重新运行初始化,选择你的 AI 工具
$ openspec init
# 验证配置文件已创建
$ ls -la .claude/commands/ # Claude Code
$ ls -la .cursor/commands/ # CursorQ2: 规范验证失败
问题描述: 运行 openspec validate 时报错。
解决方案:
bash
$ openspec validate my-change
# 错误示例:
# ✗ Missing scenario in requirement "User Authentication"确保每个 Requirement 都有至少一个 Scenario:
markdown
# 错误 ❌
### Requirement: User Authentication
The system SHALL authenticate users.
# 正确 ✓
### Requirement: User Authentication
The system SHALL authenticate users.
#### Scenario: Valid credentials
- WHEN a user submits valid credentials
- THEN the system SHALL grant accessQ3: 如何处理跨多个规范的变更
问题描述: 一个功能需要修改多个规范文件。
解决方案: OpenSpec 支持在一个变更中包含多个规范增量:
openspec/changes/my-feature/
├── proposal.md
├── tasks.md
└── specs/
├── auth/
│ └── spec.md # 认证相关变更
├── api/
│ └── spec.md # API 相关变更
└── database/
└── spec.md # 数据库相关变更Q4: 如何回滚已归档的变更
问题描述: 归档后发现问题,需要回滚。
解决方案: OpenSpec 不提供自动回滚,但你可以:
- 查看归档的变更内容:
bash
$ ls openspec/archive/my-change/
$ cat openspec/archive/my-change/specs/*/spec.md- 手动撤销规范中的变更,或创建新的变更提案来修复问题
Q5: 团队成员使用不同的 AI 工具
问题描述: 团队中有人用 Claude Code,有人用 Cursor。
解决方案: OpenSpec 支持多工具共存:
bash
# 初始化时选择多个工具
$ openspec init
# 选择: Claude Code, Cursor, GitHub Copilot
# 或者后续添加工具支持
$ openspec update所有工具共享相同的 openspec/ 目录和规范,只是斜杠命令配置不同。
最佳实践
1. 保持提案聚焦
每个变更提案应该聚焦于单一功能或改进:
markdown
# 好的做法 ✓
Change: Add user profile avatar upload
# 避免 ❌
Change: Add avatar upload, improve search, fix login bug2. 编写清晰的场景
使用 Given-When-Then 格式编写场景,确保可测试:
markdown
#### Scenario: Upload valid image
- GIVEN a logged-in user
- WHEN the user uploads a PNG image under 5MB
- THEN the system SHALL save the image
- AND update the user's avatar URL
- AND return success response3. 任务粒度适中
任务应该足够小以便跟踪进度,但不要过于琐碎:
markdown
# 好的粒度 ✓
- [ ] 2.1 Implement image upload endpoint
- [ ] 2.2 Add image validation (format, size)
- [ ] 2.3 Integrate with storage service
# 太粗 ❌
- [ ] 2.1 Implement entire avatar feature
# 太细 ❌
- [ ] 2.1 Create upload function
- [ ] 2.2 Add try-catch block
- [ ] 2.3 Log upload start4. 及时归档完成的变更
不要让完成的变更长期停留在 changes/ 目录:
bash
# 定期检查活跃变更
$ openspec list
# 完成后立即归档
$ openspec archive completed-feature --yes5. 使用 project.md 定义项目约定
在 openspec/project.md 中定义团队约定,AI 助手会遵循这些约定:
markdown
# Project Context
## Tech Stack
- Backend: Node.js with TypeScript
- Database: PostgreSQL
- API Style: REST with OpenAPI spec
## Conventions
- Use camelCase for variables
- Use PascalCase for types/interfaces
- All APIs must have request/response validation
- All database changes require migration files6. 版本控制规范文件
将 openspec/ 目录纳入版本控制:
bash
# .gitignore 中不要忽略 openspec
# openspec/ ❌ 不要添加这行
# 提交规范变更
$ git add openspec/
$ git commit -m "feat: add user avatar upload spec"下一步
- 阅读 OpenSpec 规范驱动开发 了解完整文档
- 在你的项目中运行
openspec init开始使用 - 加入 OpenSpec Discord 社区获取帮助