SpecKit:使用 Claude Code 進行規格驅動開發
掌握 SpecKit 規格驅動開發。學習如何先撰寫規格,然後讓 Claude 以完整的可追溯性系統化地實作它們。
⚠️ 社群模式聲明: SpecKit 是社群開發的工作流程模式,並非官方 Claude Code 功能。本文描述的命令和概念基於 Claude Bootstrap Kit,這是一個使用自訂技能和工作流程擴展 Claude Code 的社群專案。官方 Claude Code 功能請參閱 docs.anthropic.com。
SpecKit 是建立在 Claude Code 自訂技能系統之上的規格驅動開發框架。你不是直接跳入程式碼,而是先撰寫規格,然後 Claude 以完整的可追溯性系統化地實作它們。
這種方法確保清晰度、減少重工,並創建與程式碼保持同步的文件。
為什麼要規格驅動開發?
程式碼優先的問題
開發者:「實作使用者註冊」
Claude:[實作註冊]
開發者:「其實,我需要郵件驗證」
Claude:[新增郵件驗證]
開發者:「還要支援 SSO」
Claude:[重構以支援 SSO]
開發者:「等等,那速率限制呢?」
結果: 多次迭代、需求不明確、沒有文件。
SpecKit 的方法
開發者:/speckit-specify User Registration Feature
→ 撰寫包含所有需求的規格
→ 釐清模糊之處
→ 獲得批准
開發者:/speckit-plan
→ 建立技術計畫
→ 記錄架構決策
開發者:/speckit-implement
→ Claude 依據規格實作
→ 完整可追溯性
→ 自動生成文件
結果: 一次迭代、需求明確、文件完整。
SpecKit 工作流程
┌────────────────────────────────────────────────────────────────┐
│ SPECKIT WORKFLOW │
│ │
│ ┌──────────────┐ │
│ │ SPECIFY │ 撰寫純產品規格 │
│ │ │ 尚不涉及技術細節 │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ CLARIFY │ 解決 [NEEDS CLARIFICATION] 標記 │
│ │ │ 做出產品決策 │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ PLAN │ 技術實作計畫 │
│ │ │ 架構決策 │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ TASKS │ 將計畫分解為可執行任務 │
│ │ │ 建立實作路線圖 │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ IMPLEMENT │ 以完整可追溯性執行任務 │
│ │ │ 將程式碼連結到規格 │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ VALIDATE │ 驗證實作是否符合規格 │
│ │ │ 跨文件一致性檢查 │
│ └──────────────┘ │
│ │
└────────────────────────────────────────────────────────────────┘
SpecKit 命令
| 命令 | 用途 |
|---|---|
/speckit-init | 在專案中初始化 SpecKit |
/speckit-specify | 撰寫功能規格 |
/speckit-clarify | 解決模糊之處 |
/speckit-plan | 建立技術計畫 |
/speckit-tasks | 分解為實作任務 |
/speckit-implement | 執行實作 |
/speckit-validate | 驗證實作 |
/speckit | 執行完整工作流程 |
開始使用
初始化 SpecKit
/speckit-init
建立的目錄結構:
.speckit/
├── constitution.md # 專案原則(9 條規則)
├── specifications/ # 功能規格
├── plans/ # 技術計畫
├── tasks/ # 實作任務
└── README.md # SpecKit 文件
憲法
SpecKit 強制執行 9 條不可變原則:
# .speckit/constitution.md
## The 9 Principles
### 1. Library-First
All reusable logic lives in libraries, not in CLI or UI code.
### 2. CLI Interface
Features are accessible via CLI before any other interface.
### 3. Test-First
Tests are written before implementation.
### 4. Research-Driven
Decisions are backed by research, not assumptions.
### 5. Specification Consistency
Implementation matches specification exactly.
### 6. Simplicity
Choose the simplest solution that works.
### 7. Anti-Abstraction
Don't abstract until you have 3+ concrete cases.
### 8. Minimal Scope
Implement exactly what's specified, nothing more.
### 9. Integration-First
Integration tests are prioritized over unit tests.
階段 1:SPECIFY
撰寫規格
/speckit-specify User Registration Feature
Claude 引導你完成:
# Specification: User Registration
## Overview
[描述此功能的一段文字]
## User Stories
As a [user type], I want to [action] so that [benefit].
## Acceptance Criteria
- [ ] User can register with email and password
- [ ] Email is validated for format
- [ ] Password meets security requirements
- [ ] Confirmation email is sent
- [ ] User cannot register with existing email
## User Flow
1. User enters email and password
2. System validates input
3. System creates account
4. System sends confirmation email
5. User is redirected to confirmation page
## Edge Cases
- Invalid email format → Show error message
- Weak password → Show requirements
- Existing email → Show "account exists" message
- Email delivery fails → Show retry option
## Out of Scope
- Social login (future feature)
- Two-factor authentication (future feature)
- Password reset (separate spec)
## [NEEDS CLARIFICATION]
- Maximum password length?
- Email template content?
- Redirect destination after registration?
規格模板
---
id: SPEC-001
title: Feature Name
status: draft | review | approved | implemented
author: Developer Name
created: 2026-01-10
updated: 2026-01-10
---
# Feature Name
## Overview
[What and why]
## User Stories
[Who, what, why]
## Acceptance Criteria
[Testable requirements]
## User Flow
[Step-by-step flow]
## Edge Cases
[Error handling]
## Out of Scope
[What this doesn't include]
## [NEEDS CLARIFICATION]
[Unresolved questions]
## Dependencies
[Other features/specs needed]
## Metrics
[How to measure success]
階段 2:CLARIFY
解決模糊之處
/speckit-clarify SPEC-001
Claude 識別所有 [NEEDS CLARIFICATION] 標記:
Found 3 items needing clarification:
1. Maximum password length?
Context: Security requirements for password validation
Options:
a) 128 characters (industry standard)
b) 256 characters (extra safety)
c) Unlimited (trust the user)
Recommendation: 128 characters (balances security and usability)
2. Email template content?
Context: Confirmation email sent to new users
Decision needed: Marketing wants branded template
3. Redirect destination after registration?
Context: Where to send user after successful registration
Options:
a) Dashboard
b) Profile setup
c) Welcome page
做出決策
User: "Use 128 char limit, simple text email for now,
redirect to profile setup."
Claude:
→ Updates specification with decisions
→ Removes [NEEDS CLARIFICATION] markers
→ Adds decision rationale
更新後的規格:
## Decisions Made
### Password Length
- **Decision:** 128 character maximum
- **Rationale:** Industry standard, balances security and usability
- **Date:** 2026-01-10
### Email Template
- **Decision:** Simple text email
- **Rationale:** MVP approach, branded template in future phase
- **Date:** 2026-01-10
### Post-Registration Redirect
- **Decision:** Redirect to profile setup
- **Rationale:** Encourages profile completion, improves user experience
- **Date:** 2026-01-10
階段 3:PLAN
建立技術計畫
/speckit-plan SPEC-001
Claude 建立技術計畫:
# Technical Plan: User Registration
## Architecture Overview
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ Frontend │ —> │ API │ —> │ Database │ │ (React) │ │ (Express) │ │ (Postgres) │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ │ ▼ │ │ ┌─────────────┐ │ │ │ Email │ │ │ │ (Resend) │ │ │ └─────────────┘ │ │ │ └──────────────────────────────────────►│
## Database Schema
```sql
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
email_verified BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE email_verifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id),
token VARCHAR(255) UNIQUE NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ
);
API Design
POST /api/auth/register
// Request
{
email: string; // Valid email format
password: string; // 8-128 chars, complexity requirements
}
// Response (201)
{
message: "Registration successful. Please check your email.";
userId: string;
}
// Error (400)
{
error: "validation_error";
details: { field: string; message: string }[];
}
// Error (409)
{
error: "email_exists";
message: "An account with this email already exists.";
}
Security Considerations
- Password Hashing: bcrypt with cost factor 12
- Rate Limiting: 5 attempts per email per hour
- Token Security: 256-bit random token, 24h expiry
- Input Validation: Zod schemas on server
Dependencies
bcrypt- Password hashingresend- Email deliveryzod- Input validationprisma- Database ORM
Risks and Mitigations
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Email delivery fails | Medium | High | Retry queue, fallback provider |
| Password breach | Low | Critical | bcrypt, no plaintext storage |
| Rate limit bypass | Low | Medium | IP-based limiting backup |
## 階段 4:TASKS
### 分解為任務
/speckit-tasks SPEC-001
Claude 建立可執行任務:
```markdown
# Implementation Tasks: User Registration
## Task Overview
| ID | Task | Priority | Estimate | Dependencies |
|----|------|----------|----------|--------------|
| T1 | Database migration | High | 30 min | None |
| T2 | Validation schemas | High | 30 min | None |
| T3 | Registration API | High | 1 hour | T1, T2 |
| T4 | Email service | High | 45 min | None |
| T5 | Email integration | High | 30 min | T3, T4 |
| T6 | Registration form | Medium | 1 hour | T3 |
| T7 | Integration tests | High | 1 hour | T3, T5 |
| T8 | E2E tests | Medium | 45 min | T6 |
## Task Details
### T1: Database Migration
**Files:** `prisma/migrations/XXXX_add_users.sql`
**Spec Reference:** SPEC-001 > Database Schema
Create migration for:
- users table
- email_verifications table
Acceptance:
- [ ] Migration runs successfully
- [ ] Rollback works
### T2: Validation Schemas
**Files:** `src/lib/validation/auth.ts`
**Spec Reference:** SPEC-001 > API Design
Create Zod schemas for:
- Email validation
- Password validation (8-128 chars, complexity)
Acceptance:
- [ ] Email schema rejects invalid formats
- [ ] Password schema enforces requirements
### T3: Registration API
**Files:** `src/api/auth/register.ts`
**Spec Reference:** SPEC-001 > API Design
Implement POST /api/auth/register:
- Input validation
- Duplicate email check
- Password hashing
- User creation
- Response formatting
Acceptance:
- [ ] Returns 201 on success
- [ ] Returns 400 on validation error
- [ ] Returns 409 on duplicate email
[Continue for T4-T8...]
階段 5:IMPLEMENT
執行任務
/speckit-implement SPEC-001
Claude 以可追溯性進行實作:
/**
* Registration API Handler
*
* @spec SPEC-001
* @task T3
* @acceptance
* - Returns 201 on success
* - Returns 400 on validation error
* - Returns 409 on duplicate email
*/
export async function registerUser(req: Request, res: Response) {
// Validate input per SPEC-001 > API Design
const validation = RegistrationSchema.safeParse(req.body);
if (!validation.success) {
return res.status(400).json({
error: 'validation_error',
details: validation.error.flatten().fieldErrors
});
}
const { email, password } = validation.data;
// Check for existing user per SPEC-001 > Edge Cases
const existingUser = await db.user.findUnique({
where: { email }
});
if (existingUser) {
return res.status(409).json({
error: 'email_exists',
message: 'An account with this email already exists.'
});
}
// Hash password per Technical Plan > Security
const passwordHash = await bcrypt.hash(password, 12);
// Create user per SPEC-001 > Database Schema
const user = await db.user.create({
data: { email, passwordHash }
});
// Send verification email per SPEC-001 > User Flow
await sendVerificationEmail(user.id, email);
// Return success per SPEC-001 > API Design
return res.status(201).json({
message: 'Registration successful. Please check your email.',
userId: user.id
});
}
可追溯性註解
每個實作都連結回規格:
// @spec SPEC-001
// @task T3
// @acceptance Returns 201 on success
這使得以下功能成為可能:
- 規格覆蓋率: 哪些規格已實作?
- 變更影響: 規格變更時哪些程式碼會受影響?
- 審計軌跡: 為什麼要寫這段程式碼?
階段 6:VALIDATE
驗證
/speckit-validate SPEC-001
Claude 進行驗證:
# Validation Report: SPEC-001
## Specification Coverage
| Acceptance Criteria | Status | Evidence |
|---------------------|--------|----------|
| User can register with email and password | ✅ | T3 implementation |
| Email is validated for format | ✅ | T2 schema |
| Password meets security requirements | ✅ | T2 schema |
| Confirmation email is sent | ✅ | T5 integration |
| User cannot register with existing email | ✅ | T3 duplicate check |
## Test Coverage
| Task | Tests | Passing |
|------|-------|---------|
| T3 Registration API | 8 | 8 ✅ |
| T6 Registration Form | 5 | 5 ✅ |
| T7 Integration Tests | 12 | 12 ✅ |
| T8 E2E Tests | 6 | 6 ✅ |
## Constitution Compliance
| Principle | Status |
|-----------|--------|
| Library-First | ✅ Validation in lib/ |
| Test-First | ✅ Tests written before impl |
| Specification Consistency | ✅ All criteria met |
| Simplicity | ✅ No over-engineering |
| Minimal Scope | ✅ Only specified features |
## Documentation Status
- [x] API documentation generated
- [x] Code comments with spec references
- [x] README updated
## Result: ✅ VALIDATED
完整工作流程範例
# 初始化 SpecKit
/speckit-init
# 撰寫規格
/speckit-specify Payment Processing Feature
# 釐清模糊之處
/speckit-clarify SPEC-002
# 建立技術計畫
/speckit-plan SPEC-002
# 分解為任務
/speckit-tasks SPEC-002
# 實作
/speckit-implement SPEC-002
# 驗證
/speckit-validate SPEC-002
或使用組合命令:
/speckit Payment Processing Feature
這會互動式地執行所有階段。
與其他工具的整合
SpecKit + Memory
# 將決策儲存到 memory
/memory-save
Claude:
→ Saves SPEC-001 decisions to knowledge graph
→ Available in future sessions
→ Searchable for similar features
SpecKit + GitHub
# 建立帶有規格參考的 PR
/commit-push-pr
Claude:
→ Creates PR with SPEC-001 reference
→ Links to specification document
→ Includes acceptance criteria checklist
最佳實踐
1. 先規格再寫程式碼
Good:
/speckit-specify User Authentication
[Write complete spec]
[Get approval]
[Then implement]
Avoid:
[Start coding]
[Realize requirements unclear]
[Refactor repeatedly]
2. 保持規格原子性
Good:
- SPEC-001: User Registration
- SPEC-002: User Login
- SPEC-003: Password Reset
Avoid:
- SPEC-001: Complete Authentication System
3. 標記所有模糊之處
Good:
## [NEEDS CLARIFICATION]
- What happens on third failed login?
- Should we lock the account?
- For how long?
Avoid:
[Assuming you know the answer]
[Making product decisions in code]
4. 在程式碼中參考規格
/**
* @spec SPEC-001
* @task T3
* @acceptance Returns 201 on success
*/
5. 合併前先驗證
/speckit-validate SPEC-001
# Only merge if validated
SpecKit 目錄結構
.speckit/
├── constitution.md # 專案原則
├── specifications/
│ ├── SPEC-001-registration.md
│ ├── SPEC-002-login.md
│ └── SPEC-003-password-reset.md
├── plans/
│ ├── PLAN-001-registration.md
│ ├── PLAN-002-login.md
│ └── PLAN-003-password-reset.md
├── tasks/
│ ├── TASKS-001-registration.md
│ ├── TASKS-002-login.md
│ └── TASKS-003-password-reset.md
└── validation/
├── VALID-001-registration.md
└── ...
效益
對開發者而言
- 寫程式碼前需求清晰
- 減少重工
- 更好的估算
- 內建文件
對團隊而言
- 共同理解
- 品質一致
- 更容易上手
- 知識保存
對專案而言
- 完整可追溯性
- 稽核合規
- 變更影響分析
- 活文件
開始使用
今天:
- 在你的專案中執行
/speckit-init - 撰寫一份規格
- 跟隨它完成整個實作流程
本週:
- 為常見功能開發規格模板
- 與你的審查流程整合
- 訓練團隊使用 SpecKit 工作流程
本月:
- 新功能全面採用
- 為現有功能補寫規格
- 衡量重工減少程度
SpecKit 改變你建構軟體的方式——從混亂的迭代到深思熟慮的建構。把它寫下來,達成共識,然後精確地建構你所規定的內容。
注意: SpecKit 是使用 Claude Code 的自訂技能系統建立的社群開發工作流程模式。它不是 Anthropic 的官方產品。其底層概念利用了官方 Claude Code 功能,如 Task 工具、agents 和基於 markdown 的技能定義。
參考資料:
- Claude Code 官方文件 - 官方 Claude Code 功能
- Claude Code Skills 系統 - 如何建立自訂技能
- 社群專案:Claude Bootstrap Kit