specification

Generate comprehensive specification documents (PRD/Spec). Use when asked to "write spec", "create PRD", "document requirements", "user stories", "acceptance criteria", "產生規格", "寫需求文件", "specification

SKILL.md

GitHub

Specification (PRD/Spec Generator)

💡 Recommended Agent: spec-agent (Specification Specialist)

  • CLI: Input /agent and select spec-agent
  • VS Code: Use @workspace #spec-agent in Chat

When to Use This Skill

Use this skill when:

  • After brainstorming session is complete
  • Transforming clarified requirements into formal specification
  • Need structured, testable requirements documentation
  • Before creating implementation plan
  • 完成 brainstorm 後要產生正式規格文件
  • 需要將想法轉換為可測試的需求

Prerequisites

Required: 01-brainstorm.md should exist with:

  • Clear problem statement
  • Discovery answers captured (at least 5 questions, or an explicit note that the user allowed assumptions)
  • Chosen solution approach
  • Key decisions documented

Optional: Can generate spec without brainstorm, but must ask the missing clarifying questions first

Pre-Spec Gate

Before generating 03-spec.md, verify input quality:

  1. If 01-brainstorm.md exists: check whether brainstorm agentic-eval self-check completed. If Option Diversity or Requirements Coverage FAIL → surface the gap to the user and ask for explicit approval to proceed.
  2. No prior brainstorm (direct request): ask the user to confirm the core requirement in one sentence before starting.
  3. Generate a confirmed requirements summary (≤200 words) — confirmed items only, no inference. Store in 01-brainstorm.md. This is the Requirement Provenance rubric anchor.

Step-by-Step Workflow

Step 1: Clarifying Questions

If not already covered in brainstorm, or if brainstorm relied on assumptions, ask the missing questions before writing the spec:

Problem & Users:

  • What specific problem are we solving?
  • Who are the target users?
  • What are their pain points?

Scope & Boundaries:

  • What are the goals (must-have features)?
  • What are the non-goals (explicitly excluded)?
  • What is the MVP scope vs future enhancements?

Technical Constraints:

  • Security requirements (auth, data protection)
  • Performance requirements (latency, throughput)
  • Schema/API contract requirements
  • Integration points with existing systems

Domain-Specific (if applicable):

  • Financial: Money precision (decimal places)? Integer minor units or decimal string? Which operations must be idempotent? Audit trail requirements? Timezone strategy?
  • Personal Data / GDPR: Data retention policy? Access control tiers? Right to deletion?
  • Regulatory / Compliance: Approval workflow required? Non-repudiation? Audit log format?

Step 1.5: Vocabulary Lock(詞彙鎖定前置步驟)

Before writing any User Story, lock domain terminology:

  1. List all domain terms in this spec (≥ 3 terms)
  2. For each term: confirm consistency with existing code / documentation
  3. New terms: tag as [NEW TERM] and add definition to the Assumptions section
  4. Completion condition: no unmarked [NEW TERM] exists before Step 2
Term Definition Source
[term] [definition] existing code / doc / [NEW TERM]

Do NOT proceed to Step 2 until all terms are confirmed or tagged.

Step 2: Generate Structured Spec

Create changes/<YYYY-MM-DD>-<slug>/03-spec.md with the following structure:


Template:

# Specification: {Feature Name}

## Overview
{Brief 2-3 sentence description of what this feature does and why it matters}

## Context
{Background information, related systems, and why this is needed now}

## Goals
Primary objectives and business value:
1. {Goal 1: e.g., "Enable users to export transaction history"}
2. {Goal 2: e.g., "Improve reporting speed by 50%"}
3. {Goal 3}

## Non-Goals
Explicitly excluded from this implementation:
- {Non-goal 1: e.g., "Real-time streaming (future enhancement)"}
- {Non-goal 2: e.g., "Support for legacy file formats"}

## Assumptions
Items assumed without explicit user confirmation — **must be reviewed before plan stage**:
- `[ASSUMED]` {e.g., "Timestamps stored in UTC"}
- `[ASSUMED]` {e.g., "UUID used as primary key"}

> If this section is non-empty, the human must confirm or correct each item before handoff to plan-agent.

## User Stories

### Story 1: {Actor} wants to {Action}
**As a** {user role}
**I want** {capability}
**So that** {benefit}

**Acceptance Criteria**:
- [ ] {Testable criterion 1} — **Observable Outcome**: {what exact output/state/response confirms this passes}
- [ ] {Testable criterion 2} — **Observable Outcome**: {…}
- [ ] {Testable criterion 3} — **Observable Outcome**: {…}

**Edge Cases**:
- {Edge case 1 and how to handle it}
- {Edge case 2}

---

### Story 2: {Title}
{Repeat structure}

---

## Functional Requirements

### FR-1: {Requirement Title}
**Description**: {Detailed description}
**Priority**: Must-Have / Should-Have / Nice-to-Have
**Dependencies**: {Other FRs or systems this depends on}

### FR-2: {Title}
{Repeat structure}

---

## Technical Considerations

### Security
- **Authentication**: {How users are authenticated}
- **Authorization**: {Who can access what}
- **Data Protection**: {Encryption, PII handling}
- **Input Validation**: {What inputs are validated and how}

### Performance
- **Latency**: {Expected response times}
- **Throughput**: {Requests per second}
- **Scalability**: {How this scales with load}

### Observability
- **Logging**: {Key events to log, level, format — e.g., "Log all state changes at INFO with correlation ID"}
- **Metrics**: {Key metrics to track — e.g., "Request count, p99 latency, error rate"}
- **Alerts**: {Alert conditions — e.g., "Alert if error rate > 1% for 5 minutes"}
- **Health Check**: {What indicates healthy state — e.g., "GET /health returns 200 when DB and cache reachable"}
- **Tracing**: {Correlation ID / distributed tracing requirements}

### API/Schema Contracts
- **Endpoints**: {List of API endpoints or contract references}
- **Data Models**: {Key entities and their relationships}
- **Versioning**: {How breaking changes are handled}

### Financial Systems Requirements (if applicable)
- **Money Precision**: Use `decimal` with {X} decimal places OR store as integer minor units (e.g., cents)
- **Currency**: Explicitly store currency code (ISO 4217)
- **Idempotency**: {Which operations support Idempotency-Key header}
- **Audit Trail**: {What events are logged and where}
- **Timezone**: Store timestamps in UTC, display in user timezone

---

## Data Model (if applicable)

### Entity: {EntityName}
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | UUID | Yes | Unique identifier |
| `amount` | Decimal(19,4) | Yes | Transaction amount |
| `currency` | String(3) | Yes | ISO 4217 currency code |
| `createdAt` | DateTime (UTC) | Yes | Creation timestamp |

{Additional entities}

---

## API Contracts (if applicable)

### POST /api/v1/{resource}
**Request**:
```json
{
  "field1": "value",
  "field2": 123
}

Response (200 OK):

{
  "id": "uuid",
  "status": "created"
}

Error Responses:

  • 400 Bad Request: Invalid input
  • 409 Conflict: Duplicate idempotency key
  • 422 Unprocessable Entity: Business rule violation

Success Metrics

How we measure if this feature is successful:

  1. {Metric 1: e.g., "Export usage increases by 30%"}
  2. {Metric 2: e.g., "Support tickets for reporting decrease by 50%"}
  3. {Metric 3}

Open Questions

Items requiring further clarification before implementation:

  1. {Question 1}
  2. {Question 2}

References

  • Brainstorm: 01-brainstorm.md
  • Decision Log: 02-decision-log.md
  • Related ADRs: {Links if applicable}

---

### Step 3: Validation & Handoff Gate

Ensure the spec meets quality criteria before handing off to plan-agent.

**Completeness Checklist**:
- [ ] All user stories have acceptance criteria
- [ ] Edge cases and error scenarios are covered
- [ ] Security requirements are explicit
- [ ] Performance requirements are defined
- [ ] Observability requirements documented (logging, metrics, alerts, health check)
- [ ] API/schema contracts are documented (if applicable)
- [ ] Financial requirements specify precision (if applicable)
- [ ] Success metrics are measurable
- [ ] Assumptions section filled (all `[ASSUMED]` items listed)

**Testability Check**:
- Can a junior developer implement this without asking clarifying questions?
- Is every AC phrased as a verifiable outcome (not vague intent)?
- Are error conditions and edge cases documented?

**Financial Systems Check** (if applicable):
- ✅ Money uses `decimal` or integer minor units (NO float/double)
- ✅ Currency is explicitly stored
- ✅ Idempotency requirements documented
- ✅ Audit trail requirements defined
- ✅ Timezone handling specified

**Assumptions Review** ⛔ BLOCKING:
- Walk through each `[ASSUMED]` item with the user
  - User confirms → remove the `[ASSUMED]` tag
  - User corrects → update the spec
  - User approves proceeding despite unknowns → move item to Open Questions
- All `[ASSUMED]` items must be resolved before handoff

**Open Questions Gate** ⛔ BLOCKING:
- If Open Questions remain unresolved: **STOP** — ask the user to resolve or explicitly approve proceeding with known gaps
- Do NOT hand off to plan-agent while Open Questions are present without explicit user approval

### Specialist Lens Review

Before running agentic-eval, switch through 4 specialist perspectives. Each **must** produce ≥ 1 confirmation or add a new AC:

| Lens | Question | Output Format |
|------|----------|---------------|
| 🔒 Security | Is auth, input validation, and data protection specified? | `🔒 Security: [已覆蓋 / 新增 AC:...]` |
| ⚡ Performance | Are latency, throughput, and scalability targets defined? | `⚡ Performance: [已覆蓋 / 新增 AC:...]` |
| 🧪 QA | Can every AC be expressed as a failing test? Observable Outcome present? | `🧪 QA: [已覆蓋 / 新增 AC:...]` |
| 🎨 UX | Are error messages, loading states, and accessibility addressed? | `🎨 UX: [已覆蓋 / 新增 AC:...]` |

> Do NOT skip to agentic-eval until all 4 lenses are completed. See [specialist-lens-review.md](./references/specialist-lens-review.md) for full checklist.

**agentic-eval Self-Review** (risk-adaptive supporting check):
Run `/agentic-eval` with the `#spec` rubric only when the selected Standard mode is risk-triggered or a named High-Risk gate requests this evidence. It is self-evaluation, not independent review, and cannot override deterministic test/build/gate evidence or the blocking conditions in `WORKFLOW.md`.

| Check | Threshold |
|-------|-----------|
| AC Testability | Every AC expressible as a failing test — **HARD STOP** if any fails |
| Completeness | All FR have ≥1 AC; edge cases + error conditions covered |
| Traceability | Spec goals trace back to brainstorm problem statement |
| Observability | Logging, metrics, alerts, health check documented |
| Domain Safety | Financial precision / GDPR / regulatory checks passed (if applicable) |

**Gate PASS → Hand off to plan-agent**
**Gate FAIL → Fix the failing dimension and re-run**

## Output Template

The generated `03-spec.md` should be:
- **Readable**: A junior developer can understand it
- **Testable**: Every requirement has acceptance criteria
- **Complete**: Covers happy path, edge cases, and errors
- **Traceable**: Links back to brainstorm and decision log

## Quality Criteria

**Must Have**:
- ✅ User stories with acceptance criteria
- ✅ Functional requirements prioritized
- ✅ Security and performance considerations
- ✅ Error handling and edge cases documented

**Domain-Specific Must Have (if applicable)**:
- ✅ **Financial**: Money precision specified (NO floats); Idempotency documented for transactions; Audit trail defined
- ✅ **Personal Data**: Retention policy and deletion workflow documented

**Nice to Have**:
- API contracts with request/response examples
- Data model diagrams
- Sequence diagrams for complex flows

## Next Step

After spec completion:

**CLI**:

Input: "幫我規劃實作計畫" [System loads implementation-planning skill] → /agent → Select plan-agent → Generate 04-plan.md


**VS Code**:

Input: /create-plan Or use: "create implementation plan"


Or use workflow orchestrator:

Input: "what's next?" [System detects spec complete, recommends plan stage]


## Troubleshooting

### "I don't have brainstorm.md yet"
**Solution**: Either:
1. Run brainstorming first (recommended): "開始 brainstorming"
2. Proceed without it (agent will ask more questions)

### "The spec is too vague"
**Solution**: Add more acceptance criteria to user stories. Each criterion should be testable (pass/fail).

### "How detailed should the spec be?"
**Solution**: Detailed enough that:
- A junior developer can implement without confusion
- Acceptance criteria are testable
- But not so detailed that it prescribes implementation (that's for plan stage)

### "Should I include diagrams?"
**Solution**: 
- **Yes**: For complex data flows, state machines, or multi-system integrations
- **No**: For simple CRUD operations or straightforward features
- Use tools like Excalidraw or Mermaid for quick diagrams

## Financial Systems Best Practices *(if applicable)*

### Money Handling
**DON'T**:
```csharp
double price = 19.99; // ❌ Floating point = rounding errors

DO:

// Option 1: Decimal
decimal price = 19.99M;

// Option 2: Integer minor units
int priceInCents = 1999; // Store cents, display as $19.99
string currency = "USD";

Idempotency

For transactional endpoints, specify:

POST /api/v1/transactions
Header: Idempotency-Key: {unique-uuid}

Behavior:
- First request: Process transaction
- Repeat request (same key): Return original result (no duplicate)
- Different key: Process as new transaction

Audit Trail

Document what events to log:

  • Transaction created/updated/deleted
  • User: who performed action
  • Timestamp: when (UTC)
  • IP/correlation-id: traceability

Related Documentation

References

Read references/ac-format-guide.md when writing or reviewing Acceptance Criteria, or when the user asks for Observable Outcome examples (API, performance, UI domains — 6 example pairs).

Read references/specialist-lens-review.md when executing Specialist Lens Review in Step 3, or when the user asks for the full Security / Performance / QA / UX checklist and output template.

Read references/consult-review-protocol.md when the spec involves schema design or frontend UI work and a dba-agent or frontend-designer-agent consult is warranted.


💡 Tip: A good spec is complete when you can hand it to a developer and they don't need to ask clarifying questions.

Common Rationalizations

在撰寫規格文件過程中,AI 可能以下列藉口略過關鍵步驟:

常見藉口 反制說明
"Assumptions 都在腦子裡,不需要寫下來" ⛔ 每個 Assumption 必須以 [ASSUMED] 明確標記——隱性假設是規格缺陷的首要來源,交付前逐項確認不可省略
"我已經知道所有術語的定義,不需要詞彙鎖定" 詞彙不一致是 AI 幻覺的主要誘因——所有領域術語必須在 Step 2 前明確列出,並與現有程式碼/文件對齊
"我從作者視角已充分考慮各面向,不需要多角度審查" Specialist Lens Review 不可跳過——必須依序切換 Security / Performance / QA / UX 四個視角,不得以一次整體掃描替代
"AC 已經很清楚,不需要特別標示可觀察結果" 無法描述「如何在測試中驗證」的 AC 不算完成——Observable Outcome 是 AC 可測性的最低標準

Verification

在輸出 03-spec.md 前,逐項確認(Gate = 交付前閘門;Verification = 自我完成確認):

  • Test-Path changes/<slug>/03-spec.md 回傳 True(規格文件已實際建立於 Change Package 目錄)
  • 所有 [ASSUMED] 條目已與使用者逐項確認(或移至 Open Questions 並獲明確授權)
  • 每個 User Story 的所有 AC 均可表達為一個失敗測試(AC Testability 通過)
  • Specialist Lens Review 已完成:Security / Performance / QA / UX 各視角各產出 ≥1 個確認或新增 AC
  • Technical Considerations 含 Security、Performance、Observability 三節(不得為空)
  • Open Questions 欄位已填寫或明確標記「無未解問題」
  • 規格文件可讓初級開發者無需追加提問即可開始實作計畫