Skip to content

4.2 Spec-kit 基础概念和结构

🎯 本章目标

学完本章,你将掌握:

  • Spec-kit 的 6 阶段工作流
  • 核心文件结构(spec.md, plan.md, tasks.md)
  • 与 Claude Code 的集成机制
  • 命令(Slash Commands)系统

📁 Spec-kit 核心文件结构

项目初始化后的目录结构

my-project/
├── .claude/                    # Claude Code 集成
│   └── commands/              # Spec-kit 斜杠命令
│       ├── speckit.constitution.md
│       ├── speckit.specify.md
│       ├── speckit.clarify.md
│       ├── speckit.plan.md
│       ├── speckit.tasks.md
│       ├── speckit.implement.md
│       ├── speckit.analyze.md
│       └── speckit.checklist.md

├── .specify/                   # Spec-kit 核心目录
│   ├── memory/
│   │   └── constitution.md    # 项目宪法
│   ├── scripts/               # 自动化脚本
│   │   ├── bash/             # Unix/Linux/macOS 脚本
│   │   │   ├── common.sh
│   │   │   ├── create-new-feature.sh
│   │   │   ├── setup-plan.sh
│   │   │   └── update-agent-context.sh
│   │   └── powershell/       # Windows 脚本
│   │       ├── common.ps1
│   │       ├── create-new-feature.ps1
│   │       ├── setup-plan.ps1
│   │       └── update-agent-context.ps1
│   └── templates/             # 文档模板
│       ├── spec-template.md
│       ├── plan-template.md
│       ├── tasks-template.md
│       ├── agent-file-template.md
│       └── checklist-template.md

├── specs/                      # 功能规格目录
│   ├── 001-user-auth/         # 功能 #001
│   │   ├── spec.md           # 规格说明书
│   │   ├── plan.md           # 技术方案
│   │   ├── tasks.md          # 任务分解
│   │   ├── checklist.md      # 质量检查表
│   │   └── contracts/        # API 契约
│   │       └── api.yaml      # OpenAPI 规范
│   │
│   └── 002-photo-album/       # 功能 #002
│       ├── spec.md
│       ├── plan.md
│       └── ...

├── src/                        # 源代码(由 implement 生成)
│   ├── models/
│   ├── services/
│   ├── api/
│   └── tests/

├── .gitignore
└── README.md

文件命名规范

功能编号规则:

格式:{编号}-{功能名称}

示例:
✅ 001-user-auth
✅ 002-photo-album
✅ 123-payment-gateway

❌ 1-auth(编号不够 3 位)
❌ user-authentication(缺少编号)

分支命名规则:

Git 分支名称与功能目录一致:

功能目录:specs/001-user-auth/
Git 分支:001-user-auth

自动创建:/speckit.specify 会自动创建对应分支

🔄 六阶段工作流详解

完整流程图

┌──────────────────────────────────────────────────┐
│         SPEC-KIT 六阶段工作流                      │
└──────────────────────────────────────────────────┘

阶段 0: Constitution(宪法)[可选但推荐]
┌─────────────────────────────────────────────────┐
│ /speckit.constitution                            │
│                                                  │
│ 输入:项目的核心原则                               │
│ 输出:.specify/memory/constitution.md             │
│                                                  │
│ 内容:                                            │
│  - 架构原则(如:库优先、CLI 优先)                 │
│  - 质量标准(如:TDD、代码覆盖率)                  │
│  - 技术约束(如:最多 3 个依赖)                    │
└─────────────────────────────────────────────────┘


阶段 1: Specification(规格说明)
┌─────────────────────────────────────────────────┐
│ /speckit.specify [功能描述]                       │
│                                                  │
│ 输入:自然语言功能描述                             │
│ 输出:specs/{编号}-{名称}/spec.md                  │
│                                                  │
│ 内容:                                            │
│  - 用户故事(P1, P2, P3 优先级)                   │
│  - 功能需求(MUST, SHOULD, MAY)                  │
│  - 成功标准(可测量的目标)                         │
│  - 边缘情况                                        │
│  - [NEEDS CLARIFICATION] 标记(最多 3 个)         │
│                                                  │
│ ⚠️ 关键:技术无关,只描述 What 和 Why               │
└─────────────────────────────────────────────────┘


阶段 2: Clarification(澄清)[可选]
┌─────────────────────────────────────────────────┐
│ /speckit.clarify                                 │
│                                                  │
│ 输入:spec.md 中的 [NEEDS CLARIFICATION] 标记      │
│ 输出:更新后的 spec.md                             │
│                                                  │
│ 过程:                                            │
│  1. AI 识别所有待澄清项                            │
│  2. 逐个提问(最多 5 个问题)                       │
│  3. 提供多选或简答选项                              │
│  4. 根据回答更新 spec.md                           │
│  5. 记录澄清过程                                   │
└─────────────────────────────────────────────────┘


阶段 3: Planning(技术方案)
┌─────────────────────────────────────────────────┐
│ /speckit.plan [技术栈描述]                        │
│                                                  │
│ 输入:                                            │
│  - spec.md(需求)                                │
│  - constitution.md(约束)                        │
│  - 技术选型                                        │
│                                                  │
│ 输出:                                            │
│  - specs/{编号}/plan.md(技术方案)                │
│  - specs/{编号}/contracts/(API 契约)             │
│                                                  │
│ 内容:                                            │
│  - 技术栈(语言、框架、数据库)                      │
│  - 数据模型                                        │
│  - API 契约(OpenAPI/GraphQL)                    │
│  - 测试策略                                        │
│  - 宪法合规性检查                                   │
│  - 复杂度证明                                      │
│                                                  │
│ ⚠️ 关键:所有技术决策在此阶段确定                     │
└─────────────────────────────────────────────────┘


阶段 4: Task Breakdown(任务分解)
┌─────────────────────────────────────────────────┐
│ /speckit.tasks                                   │
│                                                  │
│ 输入:                                            │
│  - spec.md(需求)                                │
│  - plan.md(技术方案)                             │
│                                                  │
│ 输出:specs/{编号}/tasks.md                       │
│                                                  │
│ 内容:                                            │
│  - Phase 1: Setup(初始化)                       │
│  - Phase 2: Foundation(基础设施)                 │
│  - Phase 3: User Stories(用户故事实现)            │
│  - Phase 4: Polish(打磨)                        │
│  - 依赖关系标注                                    │
│  - [P] 并行任务标记                                │
│  - [US#] 用户故事关联                              │
│                                                  │
│ 格式:                                            │
│  - [ ] T001 [P] [US1] 任务描述 at /absolute/path  │
└─────────────────────────────────────────────────┘


阶段 5: Implementation(实现)
┌─────────────────────────────────────────────────┐
│ /speckit.implement                               │
│                                                  │
│ 输入:                                            │
│  - tasks.md(任务列表)                            │
│  - plan.md(技术方案)                             │
│  - spec.md(需求)                                │
│                                                  │
│ 输出:                                            │
│  - src/ 目录下的源代码                             │
│  - tests/ 目录下的测试代码                         │
│  - 更新后的 tasks.md(标记完成)                    │
│                                                  │
│ 执行流程:                                         │
│  1. 按 Phase 顺序执行                              │
│  2. 遵循依赖关系                                   │
│  3. TDD:先写测试再写实现                           │
│  4. [P] 任务并行执行                               │
│  5. 遇错暂停,等待修复                              │
│  6. 每阶段完成后验证                                │
└─────────────────────────────────────────────────┘


阶段 6: Quality Validation(质量验证)[可选]
┌─────────────────────────────────────────────────┐
│ /speckit.analyze                                 │
│ /speckit.checklist                               │
│                                                  │
│ 功能:                                            │
│  - analyze: 验证 spec/plan/tasks 一致性           │
│  - checklist: 生成质量检查清单                     │
│                                                  │
│ 检查项:                                          │
│  - 宪法合规性                                      │
│  - 需求覆盖率                                      │
│  - 测试覆盖率                                      │
│  - 安全标准                                        │
│  - 性能标准                                        │
└─────────────────────────────────────────────────┘

📄 核心文件详解

1. spec.md(规格说明书)

用途: 技术无关的需求描述

结构:

markdown
# Feature: [功能名称]

**Feature Branch**: 001-feature-name
**Created**: 2025-01-15
**Status**: Draft | Planning | In Progress | Complete

## User Scenarios(用户场景)

### P1: [主要场景名称]
**Description**: 用自然语言描述用户旅程
**Priority**: P1 (Critical - 核心功能,必须有)
**Priority Justification**: 为什么这是 P1?
**Independent Test**: 如何独立测试这个场景?

#### Acceptance Criteria(验收标准)
- Given [前置条件]
- When [用户操作]
- Then [预期结果]
- And [额外验证点]

### P2: [重要场景]
**Priority**: P2 (Important - 重要但非核心)
...

### P3: [增强场景]
**Priority**: P3 (Nice-to-have - 锦上添花)
...

### Edge Cases(边缘情况)
- **场景**: [异常情况描述]
  - **预期行为**: [系统应如何响应]

## Requirements(需求)

### Functional Requirements(功能需求)
- FR-001: 系统 **MUST** [强制能力] when [条件]
- FR-002: 用户 **MUST** be able to [必须能够做什么]
- FR-003: 系统 **SHOULD** [推荐能力](非强制)
- FR-004: **NEEDS CLARIFICATION**: [不明确的需求问题]

### Key Entities(关键实体)
- **Entity Name**: [实体描述]
  - Attributes: [属性列表]
  - Relationships: [与其他实体的关系]

## Success Criteria(成功标准)

### User Experience(用户体验)
- SC-001: 用户完成 [操作] 在 < X 秒内
- SC-002: [用户满意度指标]

### System Performance(系统性能)
- SC-003: API 响应时间 < 200ms (P95)
- SC-004: 支持 [并发量]

### Business Impact(业务影响)
- SC-005: [可测量的业务成果]

## Clarifications(澄清记录)[可选]
### Session 2025-01-15
- Q: [问题] → A: [答案]
  - Updated: [如何更新了 spec]

关键原则:

  1. 技术无关

    markdown
    ❌ 错误:"用 React Hooks 实现用户登录"
    ✅ 正确:"用户可以通过邮箱和密码登录"
  2. 可测量的成功标准

    markdown
    ❌ 错误:"系统要快"
    ✅ 正确:"API 响应时间 < 200ms (P95)"
  3. 独立可测试的用户故事

    markdown
    ❌ 错误:"实现完整的用户系统"(太大)
    ✅ 正确:
       - P1: 用户注册
       - P2: 用户登录
       - P3: 密码重置
       (每个可独立开发和测试)
  4. 限制澄清标记

    markdown
    最多 3 个 [NEEDS CLARIFICATION] 标记
    
    如果超过 3 个 → 说明需求太模糊,需要更多前期讨论

2. plan.md(技术方案)

用途: 将技术无关的 spec 转化为可执行的技术设计

结构:

markdown
# Implementation Plan: [功能名称]

**Branch**: 001-feature-name
**Date**: 2025-01-15
**Spec**: /absolute/path/to/specs/001-feature/spec.md

## Summary(摘要)
[1-2 段话总结需求和技术方案]

## Technical Context(技术上下文)
- **Language/Version**: Python 3.11+ / Node.js 20+ / Go 1.21+
- **Primary Dependencies**: FastAPI 0.104, SQLAlchemy 2.0, pytest
- **Storage**: PostgreSQL 15 / MongoDB 6.0 / Redis 7.0
- **Testing Framework**: pytest / Jest / Go testing
- **Target Platform**: Linux containers / Kubernetes / Serverless
- **Performance Goals**: < 200ms P95 latency, 10k RPS
- **Constraints**:
  - Offline-capable
  - Max 100MB memory
  - **NEEDS CLARIFICATION**: [技术上不明确的点]

## Constitution Check(宪法检查)

### Simplicity Gate (Article VII)(简洁性门控)
- [ ] Using ≤3 dependencies? **YES / NO**
  - Justification: [如果超过,为什么?]
- [ ] No future-proofing? **YES / NO**
  - Justification: [是否有过度设计?]

### Anti-Abstraction Gate (Article VIII)(反抽象门控)
- [ ] Using framework directly? **YES / NO**
  - Justification: [是否添加了不必要的封装?]
- [ ] Single model representation? **YES / NO**
  - Justification: [是否有多余的数据表示?]

### TDD Gate (Article III)(测试驱动门控)
- [ ] Test-first approach documented? **YES / NO**
  - Strategy: [测试策略说明]

## Project Structure(项目结构)

### Documentation(文档)

specs/001-feature/ ├── plan.md(本文件) ├── research.md(调研结果) ├── data-model.md(数据模型详细设计) ├── quickstart.md(快速开始指南) └── contracts/ ├── api.yaml(OpenAPI 3.0) └── events.md(事件定义)


### Source Code(源代码)

src/ ├── models/ # 数据模型 │ ├── user.py │ └── album.py ├── services/ # 业务逻辑 │ ├── auth.py │ └── album.py ├── api/ # API 端点 │ ├── users.py │ └── albums.py └── tests/ # 测试 ├── test_models.py ├── test_services.py └── test_api.py


## Phase 0: Research(调研阶段)
[解决所有 spec.md 中的 NEEDS CLARIFICATION]

### Security Research(安全调研)
- OAuth2 vs JWT: [研究结论]
- Password hashing: bcrypt vs Argon2

### Performance Benchmarks(性能基准)
- PostgreSQL vs MongoDB for this use case
- Caching strategy (Redis vs in-memory)

### Library Compatibility(库兼容性)
- FastAPI + SQLAlchemy: Proven, stable
- Alembic for migrations

## Phase 1: Design(设计阶段)

### Data Model(数据模型)

#### User Entity(用户实体)
```python
# /absolute/path/to/src/models/user.py
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from datetime import datetime

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    email = Column(String(255), unique=True, nullable=False)
    password_hash = Column(String(60), nullable=False)  # bcrypt
    email_verified = Column(Boolean, default=False)
    created_at = Column(DateTime, default=datetime.utcnow)

    # Relationships
    albums = relationship("Album", back_populates="user")

API Contract(API 契约)

OpenAPI Specification (contracts/api.yaml):

yaml
openapi: 3.0.0
info:
  title: Photo Album API
  version: 1.0.0

paths:
  /api/users/register:
    post:
      summary: Register new user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
              properties:
                email:
                  type: string
                  format: email
                  example: user@example.com
                password:
                  type: string
                  format: password
                  minLength: 8
                  example: SecurePass123
      responses:
        '201':
          description: User created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  user_id:
                    type: integer
                    example: 42
                  message:
                    type: string
                    example: "Verification email sent"
        '409':
          description: Email already registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

Test Strategy(测试策略)

  • Unit Tests: 每个 model, service 函数
  • Integration Tests: API 端点 + 数据库
  • E2E Tests: 完整用户流程
  • Test Coverage: Minimum 80%

Complexity Justification(复杂度证明)

ComponentComplexityJustificationAlternatives Rejected
AuthHighOAuth2 + JWT required by enterpriseSimple password-only (insecure)
CachingMediumRedis for session managementIn-memory (not scalable)

**关键原则:**

1. **绝对路径**
   ```markdown
   ❌ 错误:src/models/user.py
   ✅ 正确:/Users/project/src/models/user.py
  1. 宪法合规

    markdown
    ✅ 每个违反宪法的决策必须有明确理由
    ❌ 不允许无理由的复杂设计
  2. 契约优先

    markdown
    ✅ OpenAPI spec 定义后,前后端并行开发
    ❌ 不能等后端实现完再定义 API

3. tasks.md(任务分解)

用途: 将 plan 分解为可执行的任务清单

结构:

markdown
# Tasks: [功能名称]

## Format(格式说明)

[TaskID] [Markers] [Story] Description at /absolute/file/path

Markers: [P] = Parallel-capable(可并行执行) [US#] = User Story number(用户故事编号)


## Phase 1: Setup(初始化阶段)
[共享基础设施,所有用户故事的前置依赖]

- [ ] T001 Initialize project with Python 3.11 venv at /project/
  Command: `python3.11 -m venv /project/.venv`

- [ ] T002 [P] Install core dependencies at /project/requirements.txt
  Dependencies: FastAPI==0.104.0, SQLAlchemy==2.0.0, pytest==7.4.0

- [ ] T003 [P] Configure project structure at /project/

/project/ ├── src/ ├── tests/ ├── migrations/ └── config/


- [ ] T004 Create .gitignore at /project/.gitignore
Ignore: .venv/, __pycache__/, *.pyc, .env

## Phase 2: Foundation(基础阶段)
[阻塞所有用户故事的核心设施]

- [ ] T005 Create database schema at /project/migrations/001_create_users.sql
```sql
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  password_hash VARCHAR(60) NOT NULL,
  email_verified BOOLEAN DEFAULT FALSE,
  created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users(email);
  • [ ] T006 Implement User model at /project/src/models/user.py

    • Fields: id, email, password_hash, email_verified, created_at
    • Validations: Email format, password length
  • [ ] T007 Implement database connection at /project/src/db.py

    • SQLAlchemy engine with connection pooling
    • Session factory with context manager
    • Load DATABASE_URL from environment

Phase 3: User Stories(用户故事阶段)

US1: User Registration(用户注册)

[从 spec.md 的 P1 场景映射而来]

  • [ ] T008 [US1] Create password hashing service at /project/src/services/auth.py Functions:

    • hash_password(plain: str) -> str # bcrypt cost=12
    • verify_password(plain: str, hashed: str) -> bool
  • [ ] T009 [P] [US1] Implement email service at /project/src/services/email.py Functions:

    • send_verification_email(email: str, token: str) -> bool
    • Use SMTP from environment (SMTP_HOST, SMTP_PORT)
    • Template: /project/templates/verification_email.html
  • [ ] T010 [US1] Create registration endpoint POST /api/users/register File: /project/src/api/users.py Logic:

    1. Validate email format (regex)
    2. Validate password strength (8+ chars, uppercase, number)
    3. Check email uniqueness (query database)
    4. Hash password (auth service)
    5. Save user to database
    6. Generate verification token (JWT, 24hr expiry)
    7. Send verification email (email service)
    8. Return 201 with user ID Error handling:
    • 400: Invalid input
    • 409: Email already exists
  • [ ] T011 [P] [US1] Write integration test at /project/tests/test_registration.py Test cases:

    • test_successful_registration()
    • test_duplicate_email_returns_409()
    • test_weak_password_returns_400()
    • test_invalid_email_format_returns_400()
    • test_verification_email_sent()

CHECKPOINT: Validate US1 independently before US2

US2: Email Verification(邮箱验证)

[独立于 US1,可并行或顺序开发]

  • [ ] T012 [US2] Create token generation service at /project/src/services/tokens.py Functions:

    • generate_verification_token(user_id: int) -> str # JWT
    • verify_token(token: str) -> int | None # Returns user_id
  • [ ] T013 [US2] Implement verification endpoint GET /api/users/verify File: /project/src/api/users.py Logic:

    1. Extract token from query param
    2. Verify token (tokens service)
    3. Update user.email_verified = True
    4. Return 200 with success message Error handling:
    • 400: Invalid/expired token
    • 404: User not found
  • [ ] T014 [P] [US2] Write integration test at /project/tests/test_verification.py Test cases:

    • test_valid_token_verifies_email()
    • test_expired_token_returns_400()
    • test_invalid_token_returns_400()

CHECKPOINT: Validate US2 independently

Phase 4: Polish & Cross-Cutting Concerns(打磨阶段)

  • [ ] T015 Add API documentation at /project/docs/api.md

    • Auto-generate from OpenAPI spec
    • Include usage examples
  • [ ] T016 Implement rate limiting at /project/src/middleware/rate_limit.py

    • 5 registration attempts per hour per IP
    • Use Redis for tracking
  • [ ] T017 Security audit for OWASP Top 10 Checklist:

    • [ ] SQL Injection protection (SQLAlchemy ORM)
    • [ ] XSS prevention (input sanitization)
    • [ ] CSRF tokens (for future web UI)
    • [ ] Secure password storage (bcrypt)
    • [ ] HTTPS enforcement
  • [ ] T018 Performance optimization

    • Add database indexes
    • Enable query caching
    • Optimize email sending (async)

**关键原则:**

1. **任务格式**
   ```markdown
   格式:[ID] [Markers] [Story] Description at /path

   示例:
   - [ ] T009 [P] [US1] Implement email service at /project/src/services/email.py
         ^^^^ ^^^ ^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         ID   并行 故事  任务描述                   绝对路径
  1. 并行标记

    markdown
    [P] = 可并行执行(不同文件,无依赖)
    
    - [ ] T002 [P] Install dependencies
    - [ ] T003 [P] Configure linting
    ↑ 这两个可以同时做
    
    - [ ] T005 Create database schema
    - [ ] T006 Implement User model (depends on T005)
    ↑ 这两个必须顺序做
  2. 阶段依赖

    markdown
    Phase 1: Setup
       ↓ (完成后才能进入 Phase 2)
    Phase 2: Foundation(阻塞所有用户故事)
       ↓ (完成后才能进入 Phase 3)
    Phase 3: User Stories(可独立验证)
       ↓ (完成后才能进入 Phase 4)
    Phase 4: Polish
  3. Checkpoint(检查点)

    markdown
    每个用户故事后必须有 CHECKPOINT
    
    **CHECKPOINT**: Validate US1 independently before US2
    
    意义:独立测试,确保功能可用后再继续

🔌 与 Claude Code 的集成机制

Slash Commands(斜杠命令)系统

命令发现机制:

Claude Code 启动时:

扫描 .claude/commands/ 目录

加载所有 .md 文件

解析文件名 → 命令名

命令在聊天界面可用

命令文件结构:

markdown
<!-- .claude/commands/speckit.specify.md -->

# /speckit.specify - Create Feature Specification

## Prompt

You are creating a new feature specification following the Specification-Driven Development methodology.

## User Input

The user will provide: $ARGUMENTS

This should be a natural language description of the feature they want to build.

## Process

1. **Extract Feature Information**
   - Parse the feature description
   - Generate a short, meaningful feature name (2-4 words, no stop words)
   - Example: "user can upload photos" → "photo-upload"

2. **Determine Feature Number**
   - Check existing feature numbers:
     - Remote branches: `git ls-remote origin | grep 'refs/heads/[0-9]'`
     - Local branches: `git branch | grep '^[0-9]'`
     - Specs directory: `ls specs/ | grep '^[0-9]'`
   - Use highest number + 1
   - Format: 3 digits (001, 002, 003, ...)

3. **Execute Script**
   Run: `.specify/scripts/bash/create-new-feature.sh "$ARGUMENTS"`

   This script will:
   - Create specs/{number}-{name}/ directory
   - Copy spec-template.md → specs/{number}-{name}/spec.md
   - Create git branch {number}-{name}
   - Export SPECIFY_FEATURE environment variable

4. **Generate Specification**
   Using the spec template, create a detailed specification with:

   - **User Scenarios** (prioritized P1, P2, P3)
     - Each scenario independently testable
     - Given-When-Then format

   - **Functional Requirements**
     - MUST/SHOULD/MAY notation
     - Technology-agnostic
     - Maximum 3 [NEEDS CLARIFICATION] markers

   - **Success Criteria**
     - Measurable (numbers, times, percentages)
     - User-focused (not technical metrics)

   - **Edge Cases**
     - Error handling
     - Boundary conditions

5. **Iterate and Refine**
   - Present draft to user
   - Iterate up to 3 times to improve clarity
   - Ensure all sections are complete

## Output

Provide the user with:
- Feature number and branch name
- Path to spec.md
- Summary of the specification
- Next step recommendation: `/speckit.clarify` or `/speckit.plan`

## Example

User: "I want users to be able to create photo albums"

Output:

✓ Created feature 001-photo-albums ✓ Branch: 001-photo-albums ✓ Spec: specs/001-photo-albums/spec.md

Summary

P1: Users can create albums with titles P2: Users can add photos to albums P3: Users can share albums

Next step: Run /speckit.plan [tech stack] to create implementation plan

参数传递:

bash
用户输入:/speckit.specify Build a photo album organizer

系统处理:
  1. 命令名:speckit.specify
  2. 参数:$ARGUMENTS = "Build a photo album organizer"
  3. 加载:.claude/commands/speckit.specify.md
  4. 替换:$ARGUMENTS  "Build a photo album organizer"
  5. 执行:prompt 中的指令

脚本自动化

脚本执行流程:

bash
# create-new-feature.sh 核心逻辑

#!/bin/bash

# 1. 获取项目根目录
REPO_ROOT=$(git rev-parse --show-toplevel)

# 2. 解析功能描述,生成短名称
FEATURE_DESC="$1"
FEATURE_NAME=$(echo "$FEATURE_DESC" | \
  sed 's/[^a-zA-Z0-9 ]//g' | \  # 移除特殊字符
  tr '[:upper:]' '[:lower:]' | \ # 转小写
  tr -s ' ' '-' | \              # 空格转连字符
  sed 's/^-//;s/-$//')           # 移除首尾连字符

# 3. 确定特性编号(三来源取最大值)
REMOTE_MAX=$(git ls-remote origin | grep -oE '[0-9]{3}' | sort -n | tail -1)
LOCAL_MAX=$(git branch -a | grep -oE '[0-9]{3}' | sort -n | tail -1)
SPECS_MAX=$(ls specs/ 2>/dev/null | grep -oE '^[0-9]{3}' | sort -n | tail -1)

MAX_NUM=$(echo -e "$REMOTE_MAX\n$LOCAL_MAX\n$SPECS_MAX" | sort -n | tail -1)
NEXT_NUM=$(printf "%03d" $((MAX_NUM + 1)))

# 4. 创建目录和分支
BRANCH_NAME="${NEXT_NUM}-${FEATURE_NAME}"
FEATURE_DIR="specs/${BRANCH_NAME}"

mkdir -p "$FEATURE_DIR"
git checkout -b "$BRANCH_NAME"

# 5. 复制模板
cp .specify/templates/spec-template.md "$FEATURE_DIR/spec.md"

# 6. 导出环境变量
export SPECIFY_FEATURE="$NEXT_NUM"
export SPECIFY_FEATURE_DIR="$FEATURE_DIR"
export SPECIFY_SPEC_FILE="$FEATURE_DIR/spec.md"

# 7. 输出结果(JSON 格式,方便 AI 解析)
cat <<EOF
{
  "feature_number": "$NEXT_NUM",
  "branch_name": "$BRANCH_NAME",
  "feature_dir": "$FEATURE_DIR",
  "spec_file": "$FEATURE_DIR/spec.md"
}
EOF

跨平台支持:

Unix/Linux/macOS → .specify/scripts/bash/*.sh
Windows          → .specify/scripts/powershell/*.ps1

自动选择:
  - macOS: Bash
  - Linux: Bash
  - Windows: PowerShell

手动指定:
  specify init my-project --script ps  # 强制用 PowerShell

🎯 最佳实践

1. 何时创建 Constitution?

推荐创建宪法的场景:

✅ 团队协作项目(统一标准)
✅ 长期维护项目(防止技术债务)
✅ 企业项目(合规要求)
✅ 复杂系统(架构约束)

❌ 一次性脚本(无必要)
❌ 快速原型(过度约束)

宪法示例:

markdown
# 项目宪法 v1.0

## 第 1 条:简洁优先
所有功能必须使用 ≤3 个外部依赖

## 第 2 条:测试驱动开发
所有代码必须先写测试再写实现
最低测试覆盖率:80%

## 第 3 条:API 契约优先
所有 API 必须先定义 OpenAPI 规范再实现

## 约束条件
- 性能:API 响应 < 200ms (P95)
- 安全:OWASP Top 10 合规
- 技术栈:Python 3.11+, PostgreSQL 15+

2. Spec vs Plan 的边界

Spec(规格)应该包含:

markdown
✅ 用户故事(用户视角的功能描述)
✅ 功能需求(系统能做什么)
✅ 成功标准(如何测量成功)
✅ 边缘情况(异常如何处理)

❌ 技术选型(React vs Vue)
❌ 数据库设计(表结构)
❌ API 接口(endpoint 定义)
❌ 代码示例

Plan(方案)应该包含:

markdown
✅ 技术栈(Python, FastAPI, PostgreSQL)
✅ 数据模型(表结构、字段、关系)
✅ API 契约(OpenAPI 规范)
✅ 测试策略(单元测试、集成测试)
✅ 宪法合规性检查
✅ 复杂度证明

❌ 用户故事(应在 spec)
❌ 成功标准(应在 spec)

示例对比:

markdown
# spec.md(正确)
## 用户故事
用户可以创建相册来组织照片

## 功能需求
- 必须支持上传 JPG, PNG 格式
- 必须显示缩略图

---

# plan.md(正确)
## 技术栈
- 前端:React 18
- 后端:Python FastAPI
- 存储:AWS S3

## 数据模型
```python
class Album(Base):
    id: int
    user_id: int
    title: str
    photos: List[Photo]

### 3. 任务粒度

**合适的任务粒度:**
```markdown
✅ 单个任务 = 1-2 小时工作量
✅ 单个文件或单个功能
✅ 可独立审查

❌ 太粗:"实现用户认证系统"(太大)
❌ 太细:"添加第 42 行代码"(太小)

推荐示例:
- [ ] T008 Create User model at /project/src/models/user.py
      (1 个文件,明确的输出)

- [ ] T009 Implement password hashing at /project/src/services/auth.py
      (1 个功能模块,明确的边界)

4. Checkpoint 使用

何时设置 Checkpoint?

markdown
✅ 每个用户故事完成后
✅ 关键基础设施完成后
✅ 跨团队集成点

示例:
## Phase 2: Foundation
- [ ] T005 Create database schema
- [ ] T006 Implement User model

**CHECKPOINT**:
  - Run migrations
  - Verify database connectivity
  - Test User CRUD operations

## Phase 3: User Story 1
- [ ] T008 Create registration endpoint
- [ ] T009 Send verification email

**CHECKPOINT**:
  - Test registration flow end-to-end
  - Verify email sent successfully
  - Validate US1 acceptance criteria

💡 小结

本章我们学习了:

六阶段工作流:Constitution → Specify → Clarify → Plan → Tasks → Implement ✅ 核心文件结构:spec.md(What), plan.md(How), tasks.md(When) ✅ 集成机制:Slash Commands + 脚本自动化 ✅ 最佳实践:何时用宪法、Spec vs Plan 边界、任务粒度、Checkpoint

下一步: 4.3 创建你的第一个 Spec - 通过 3 个实战案例掌握 Spec-kit!


Spec-kit 核心概念教程 v1.0 | 2025 Edition

基于 MIT 许可证发布。内容版权归作者所有。