Skip to content

Latest commit

 

History

History
795 lines (621 loc) · 34.6 KB

File metadata and controls

795 lines (621 loc) · 34.6 KB
name spec-driven-development
description Use this skill for any complex, large-scope, or multi-session software feature or project, especially on existing/production codebases where breaking changes must be avoided. Enforces a strict three-phase workflow — Requirements, Design, Tasks — before any code is written, with mandatory approval gates between phases and full traceability from requirement to design decision to implementation task to code. Creates a persistent .spec/<feature>/ folder in the target project so every phase survives context resets and stays auditable. Trigger on: any request to build a new feature, plan a complex change, architect a system, or any task where the user says "spec this out", "plan this properly", "don't break anything", or describes a feature with non-trivial scope (more than a single function/file change).

agent.md — Spec-Driven Development Controller

Code is the last thing you write, not the first. A feature built without a spec is a guess wearing a deadline. This file controls how every complex change gets planned, approved, and built — in that order, never out of order, never skipped, never assumed.


0. PHILOSOPHY — WHY THIS EXISTS

Big projects break in three predictable ways:

  1. The agent starts coding from a vague request and discovers halfway through that the requirement meant something different than assumed. Rework follows.
  2. The agent makes a design decision invisibly, inside its own reasoning, that the user never saw or approved. Six months later nobody remembers why it was built that way.
  3. The agent touches existing code without mapping the blast radius first, and a "small" change breaks three other features that depended on the old behavior.

Spec-Driven Development (SDD) eliminates all three by forcing three distinct, sequential, human-approved documents to exist BEFORE a single line of implementation code is written:

REQUIREMENTS  →  DESIGN  →  TASKS  →  IMPLEMENTATION
   (what)        (how)      (steps)      (code)

Each phase produces a durable file. Each file is approved before the next phase starts. Each implementation task traces back to a design decision, which traces back to a requirement. Nothing gets built that wasn't specified. Nothing gets specified that wasn't approved.


1. THIS SKILL'S OWN FOLDER STRUCTURE

This skill package is organized exactly like the artifacts it produces, so the templates are easy to find and the pattern is easy to remember:

spec-driven-development/
├── agent.md                  ← This file. The controller. Read first, always.
├── requirement/
│   └── requirement.md        ← Master template for Phase 1 (Requirements)
├── design/
│   └── design.md             ← Master template for Phase 2 (Design)
└── tasks/
    └── task.md                ← Master template for Phase 3 (Tasks)

Note on file naming: If this skill is loaded into an agent runtime that auto-discovers skills by a fixed filename (e.g. requires SKILL.md in a folder matching the name: field), duplicate this file as SKILL.md inside a spec-driven-development/ folder. The content is identical — agent.md is the name used throughout this document and in all generated specs because that is the controller name this workflow refers to internally.


2. HOW SPECS APPEAR IN ANY TARGET PROJECT CODEBASE

When this skill is invoked inside a real project (any language, any framework, any size), it creates a .spec/ directory at the project root. Every feature, change, or unit of work gets its own sub-folder, named with a short kebab-case slug.

<project-root>/
├── .spec/
│   ├── REGISTRY.md                       ← Index of all specs in this project (see §9)
│   │
│   ├── add-creator-payout-system/         ← One folder per feature/change
│   │   ├── requirement/
│   │   │   └── requirement.md
│   │   ├── design/
│   │   │   └── design.md
│   │   └── tasks/
│   │       └── task.md
│   │
│   ├── migrate-auth-to-jwt/
│   │   ├── requirement/
│   │   │   └── requirement.md
│   │   ├── design/
│   │   │   └── design.md
│   │   └── tasks/
│   │       └── task.md
│   │
│   └── refactor-credit-ledger/
│       ├── requirement/
│       │   └── requirement.md
│       ├── design/
│       │   └── design.md
│       └── tasks/
│           └── task.md
│
├── src/                                   ← The actual project, untouched in structure
└── ...

Rules for the .spec/ directory

  • One folder per feature/change. Never mix two unrelated features in one spec folder.
  • Slug naming: kebab-case, verb-first where possible (add-, fix-, migrate-, refactor-, remove-). Short enough to type, specific enough to identify at a glance in REGISTRY.md.
  • Files are created in order: requirement.md first, always. design.md only after requirements are approved. task.md only after design is approved.
  • Files are never deleted. A spec that is abandoned is marked STATUS: ABANDONED in its own header and in REGISTRY.md — it stays as a historical record of what was considered and why it was not pursued.
  • .spec/ is committed to version control. It is part of the project's permanent record, not a scratch directory. Treat it with the same care as the source code itself.

3. THE PHASE GATE STATE MACHINE — THE CORE RULE

This is the single most important rule in this entire skill. Internalize it completely.

┌─────────────┐     APPROVAL      ┌─────────────┐     APPROVAL      ┌─────────────┐     APPROVAL      ┌────────────────┐
│ REQUIREMENTS│  ───────GATE────► │   DESIGN    │  ───────GATE────► │    TASKS    │  ───────GATE────► │ IMPLEMENTATION │
│   (Phase 1) │     REQUIRED      │  (Phase 2)  │     REQUIRED      │  (Phase 3)  │     REQUIRED      │   (Phase 4)    │
└─────────────┘                   └─────────────┘                   └─────────────┘                   └────────────────┘

The Absolute Rules

  1. NEVER write design content before requirements.md is explicitly approved.
  2. NEVER write task content before design.md is explicitly approved.
  3. NEVER write or modify implementation code before task.md is explicitly approved.
  4. NEVER silently skip a phase because the request "seems simple." If it's simple, the requirement and design documents will be short — but they still exist.
  5. Approval is explicit, not implied. The agent must directly ask: "Requirements are ready for review above. Reply 'approved' or tell me what to change before I move to design." Silence, a topic change, or a vague "ok continue" is NOT approval — confirm explicitly if there is any ambiguity.
  6. If new information emerges during a later phase that contradicts an earlier approved phase, STOP. Do not patch around it. Go back, update the earlier document, flag the change, and get re-approval before continuing forward (see §10 Change Management).

When This Gating Can Be Compressed (Rare Exceptions)

For genuinely trivial changes (rename a variable, fix a typo, change a CSS color value), full SDD is overhead, not protection. Use judgment:

USE FULL SDD WHEN:
  - The change touches more than 2-3 files
  - The change affects an existing API contract, data schema, or auth flow
  - The change is user-facing and has UX implications
  - The user explicitly says "spec this", "plan this properly", or "don't break anything"
  - The codebase is large/unfamiliar and blast radius is uncertain
  - Multiple people/agents might work on related work and need a shared reference

SKIP TO LIGHTWEIGHT MODE WHEN:
  - Single-file, single-function change with no external impact
  - The user explicitly asks for a quick fix and accepts the informality
  - It is genuinely a one-line change

LIGHTWEIGHT MODE: Still create the .spec/ folder and all three files, but each may be
just a few lines. The structure stays. The ceremony shrinks. Never skip the folder entirely
for anything that touches more than one file — the traceability is cheap insurance.

4. PHASE 0 — CONTEXT ANCHORING (BEFORE WRITING REQUIREMENTS)

This phase prevents the most damaging failure mode: writing a requirement that conflicts with how the existing system actually works.

BEFORE WRITING A SINGLE LINE OF requirement.md:

[ ] Read any existing project-level agent instructions
    (AGENT.md, CLAUDE.md, PROJECT_STRUCTURE.md, README.md, or equivalent — whatever
    this specific project uses as its source of truth)

[ ] Read .spec/REGISTRY.md if it exists — check for related or conflicting specs
    Is there an in-progress spec that touches the same area?
    Is there a completed spec whose design decisions constrain this new work?

[ ] Identify the existing system boundary this feature touches:
    - What modules/files/services currently exist in this area?
    - What is the current data model for anything this feature reads or writes?
    - What other features currently depend on the code this feature will touch?
    - Is there an existing pattern/convention this should follow for consistency?

[ ] If the codebase is large and unfamiliar, do a focused recon pass:
    - Map the relevant directory structure
    - Find the entry points (routes, handlers, components) in the affected area
    - Note any existing tests covering this area (they define current expected behavior)

THIS IS NOT OPTIONAL FOR ANY NON-TRIVIAL CHANGE. A requirement written without
understanding the existing system is a requirement that will conflict with reality
during implementation — which means rework, or worse, a breaking change that ships.

5. PHASE 1 — REQUIREMENTS (requirement/requirement.md)

Purpose

Capture what must be true when this feature is done — from the perspective of the people and systems that will use it. No implementation detail belongs here. No code, no file names, no library choices. Pure intent and observable behavior.

Format Rule: EARS Syntax for Acceptance Criteria

Every acceptance criterion must use one of these five sentence patterns. This format is unambiguous, testable, and removes the vagueness that causes scope disputes later.

UBIQUITOUS:        THE SYSTEM SHALL <always-true behavior>
EVENT-DRIVEN:       WHEN <trigger occurs> THE SYSTEM SHALL <response>
STATE-DRIVEN:        WHILE <system is in this state> THE SYSTEM SHALL <response>
UNWANTED BEHAVIOR:    IF <undesired condition occurs> THEN THE SYSTEM SHALL <response>
OPTIONAL FEATURE:      WHERE <feature/config is enabled> THE SYSTEM SHALL <response>

Examples:

WHEN a user submits a withdrawal request exceeding their available balance,
THE SYSTEM SHALL reject the request and return error code INSUFFICIENT_BALANCE.

WHILE a creator's payout currency is set to USD,
THE SYSTEM SHALL display all commission figures in USD with a $ symbol.

IF a payment webhook is received with an unverifiable signature,
THEN THE SYSTEM SHALL discard the event and log a security alert.

Required Sections in requirement.md

# Requirement: <Feature Name>

**Status**: DRAFT | IN REVIEW | APPROVED | SUPERSEDED | ABANDONED
**Spec Folder**: .spec/<slug>/
**Created**: <date>
**Last Updated**: <date>
**Author/Requested By**: <user/stakeholder>

## 1. Summary
One paragraph. What is this feature and why does it need to exist right now?

## 2. Background & Context
What exists today? What problem does this solve? What prompted this request?
Reference Phase 0 findings — what did context anchoring reveal about the current system?

## 3. Goals
What this feature MUST achieve to be considered successful. Numbered, specific, measurable
where possible.

## 4. Non-Goals (Explicitly Out of Scope)
What this feature deliberately does NOT do. This prevents scope creep and sets correct
expectations. Just as important as the goals section.

## 5. User Stories
As a <role>, I want <capability>, so that <benefit>.
(One or more stories. Each gets a short ID: US-1, US-2, ...)

## 6. Functional Requirements (EARS Format)
Numbered REQ-IDs, each with one or more acceptance criteria in EARS syntax.

### REQ-1: <short title>
- REQ-1.1: WHEN ... THE SYSTEM SHALL ...
- REQ-1.2: IF ... THEN THE SYSTEM SHALL ...

### REQ-2: <short title>
- REQ-2.1: ...

## 7. Non-Functional Requirements
Performance, security, scalability, accessibility, compliance, localization —
anything that is a quality attribute rather than a feature behavior.

## 8. Existing System Impact (CRITICAL — Do Not Skip)
- What existing features, APIs, or data does this touch?
- What existing user-facing behavior, if any, changes?
- What is the risk level of breaking something that currently works?
  (NONE / LOW / MEDIUM / HIGH — justify the rating)

## 9. Edge Cases & Error Conditions
Enumerate the non-happy-path scenarios that must be handled.
Empty states, concurrent access, invalid input, partial failure, timeout, etc.

## 10. Dependencies
Other specs, features, or external systems this requirement depends on or blocks.

## 11. Open Questions
Anything unresolved that needs a decision before design can begin.
This section should be EMPTY before the requirement is approved — if it's not empty,
the requirement is not ready for approval yet.

## 12. Approval
- [ ] Reviewed by: <name/role>
- [ ] Approved on: <date>
- [ ] Approval note: <any conditions attached to the approval>

Phase 1 Exit Checklist (Before Requesting Approval)

[ ] Every requirement uses EARS syntax — no vague prose acceptance criteria
[ ] Non-goals section is filled in, not left as a placeholder
[ ] Existing System Impact section is complete and honest about risk
[ ] Open Questions section is empty (all questions were resolved through user dialogue)
[ ] No implementation details have leaked in (no file names, no library names, no code)
[ ] User stories map clearly to functional requirements (every story has REQ-IDs backing it)

6. PHASE 2 — DESIGN (design/design.md)

Purpose

Capture how the approved requirements will be technically realized — architecture, data, contracts, sequencing, and crucially, the impact on the existing system and the strategy for changing it without breaking it.

Required Sections in design.md

# Design: <Feature Name>

**Status**: DRAFT | IN REVIEW | APPROVED | SUPERSEDED
**Spec Folder**: .spec/<slug>/
**Requirement Reference**: requirement/requirement.md (must be APPROVED before this exists)
**Created**: <date>
**Last Updated**: <date>

## 1. Overview
One paragraph technical summary of the approach. The "elevator pitch" of the solution.

## 2. Architecture
High-level diagram (mermaid syntax) showing new/modified components and how they connect
to the existing system.

```mermaid
graph TD
    A[Existing: API Gateway] --> B[New: PayoutService]
    B --> C[Existing: CreatorCommission Lib]
    B --> D[New: PayoutLedger Collection]

3. Components Affected

Component Change Type Risk Notes
src/lib/creatorCommission.js MODIFIED MEDIUM Adds payout trigger, existing logic unchanged
src/models/Payout.js NEW LOW New collection, no existing dependents
src/api/creator/payout.js NEW LOW New route, additive
src/api/auth/* UNCHANGED NONE Not touched

Change Type legend: NEW (created from scratch) / MODIFIED (existing code changes) / REMOVED (existing code deleted) / UNCHANGED (explicitly confirmed not touched).

4. Existing System Impact Analysis (CRITICAL — Do Not Skip)

For every component marked MODIFIED or REMOVED above:

  • What currently depends on this component's existing behavior?
  • What breaks if this change ships exactly as designed?
  • What is the mitigation? (see §5 Backward Compatibility Strategy)

5. Backward Compatibility & Non-Breaking Strategy

  • Is this change purely additive? (new fields, new endpoints, new optional params) → Lowest risk. Prefer this whenever possible.
  • Does this modify existing behavior? If so: → Feature flag strategy: how is the new behavior gated until verified safe? → Versioning strategy: does an API need a v2 instead of breaking v1? → Migration strategy: if data schema changes, is it additive-first (add new field, dual-write, backfill, switch reads, remove old field later) rather than a destructive single-step migration?
  • Rollback plan: if this ships and something breaks, what is the exact rollback procedure?

6. Data Model Changes

Schema diffs, new collections/tables, field additions, index changes. Mark each as ADDITIVE (safe) or BREAKING (requires migration strategy from §5).

7. API Contracts

For every new or modified endpoint: method, path, request shape, response shape, error codes, auth requirements. Note version if this is a breaking change to an existing contract.

8. Sequence Diagrams (Key Flows)

For any flow involving multiple components or async steps, a mermaid sequence diagram.

sequenceDiagram
    User->>API: POST /creator/payout/request
    API->>PayoutService: validate balance
    PayoutService->>PayoutLedger: check min payout threshold
    PayoutLedger-->>PayoutService: eligible
    PayoutService->>API: 200 payout queued
Loading

9. Error Handling Strategy

How are failures surfaced? What gets retried, what fails fast, what gets logged/alerted?

10. Security Considerations

Auth/authz implications, data exposure risk, input validation strategy, rate limiting needs.

11. Performance Considerations

Expected load, query patterns, caching strategy, any N+1 risk, indexing needs.

12. Testing Strategy

Requirement ID Test Type Coverage Plan
REQ-1 Unit Validate EARS criteria REQ-1.1, REQ-1.2
REQ-2 Integration End-to-end payout flow with mock payment gateway

13. Technical Decisions Log

For every non-obvious choice, record it so the reasoning survives past this conversation.

Decision:

  • Options considered: A) ..., B) ..., C) ...
  • Chosen:
  • Rationale:
  • Trade-offs accepted: <what we're giving up>

14. Open Questions

Must be empty before approval — same rule as Phase 1.

15. Approval

  • Reviewed by: <name/role>
  • Approved on:
  • Approval note:

### Phase 2 Exit Checklist (Before Requesting Approval)

[ ] Every requirement from requirement.md is addressed by at least one design element [ ] Existing System Impact Analysis is complete for every MODIFIED/REMOVED component [ ] Backward Compatibility & Non-Breaking Strategy is filled in — not skipped [ ] If any change is BREAKING, the migration/versioning plan is concrete, not vague [ ] Rollback plan exists for any change with MEDIUM or HIGH risk [ ] Testing strategy maps to every requirement ID [ ] Open Questions section is empty


---

## 7. PHASE 3 — TASKS (`tasks/task.md`)

### Purpose
Break the approved design into a sequence of small, atomic, independently verifiable
implementation steps. This is the only document that should be open while coding.

### Required Sections in task.md

```markdown
# Tasks: <Feature Name>

**Status**: DRAFT | IN REVIEW | APPROVED | IN PROGRESS | COMPLETE
**Spec Folder**: .spec/<slug>/
**Design Reference**: design/design.md (must be APPROVED before this exists)
**Created**: <date>
**Last Updated**: <date>
**Progress**: <N> / <Total> tasks complete

## Task List

Each task is atomic: completable in one focused work session, independently verifiable,
and traceable to the requirement and design section it implements.

- [ ] **TASK-001**: <short imperative title — "Create Payout schema">
  - **Implements**: REQ-3, Design §6 (Data Model Changes)
  - **Files touched**: `src/models/Payout.js` (new)
  - **Description**: <what exactly to build>
  - **Definition of Done**: <specific, checkable completion criteria>
  - **Depends on**: none
  - **Risk**: LOW (additive, new file)

- [ ] **TASK-002**: <short imperative title — "Add payout eligibility check">
  - **Implements**: REQ-1, REQ-2, Design §9 (Error Handling)
  - **Files touched**: `src/lib/creatorCommission.js` (modified)
  - **Description**: <what exactly to build>
  - **Definition of Done**: <specific, checkable completion criteria>
  - **Depends on**: TASK-001
  - **Risk**: MEDIUM (modifies existing function — see Design §4 impact analysis)
  - **Regression check**: <what existing test/behavior must still pass after this task>

- [ ] **TASK-003**: **[NON-BREAKING CHECKPOINT]** Run full existing test suite
  - **Purpose**: Verify TASK-001 and TASK-002 introduced no regressions before proceeding
  - **Definition of Done**: All existing tests pass; any failure is investigated and
    resolved before continuing to the next task, not deferred

... (continue numbering through full implementation)

- [ ] **TASK-0NN**: **[FINAL]** Update project documentation
  - **Files touched**: PROJECT_STRUCTURE.md / README.md / equivalent (as used by this project)
  - **Description**: Document the new feature in the project's own source-of-truth files
  - **Definition of Done**: A new developer reading only the updated docs could understand
    this feature without reading this spec folder

## Milestones
Group tasks into logical checkpoints if the feature is large enough to warrant it.

### Milestone 1: Data Layer (TASK-001 to TASK-003)
### Milestone 2: Business Logic (TASK-004 to TASK-008)
### Milestone 3: API Surface (TASK-009 to TASK-012)
### Milestone 4: Integration & Verification (TASK-013 to TASK-0NN)

## Approval
- [ ] Reviewed by: <name/role>
- [ ] Approved on: <date>

Rules for Writing Good Tasks

EVERY TASK MUST BE:
  ATOMIC      — one logical unit of work, not "build the whole feature"
  TRACEABLE   — references the exact REQ-ID and Design section it implements
  VERIFIABLE  — has a specific Definition of Done, not "make it work"
  ORDERED     — dependencies are explicit, sequence respects them
  RISK-RATED  — LOW/MEDIUM/HIGH based on the Design's impact analysis

INSERT NON-BREAKING CHECKPOINTS:
  After any task or group of tasks marked MEDIUM or HIGH risk, insert an explicit
  checkpoint task that runs existing tests / manual verification before proceeding.
  This is what prevents "I built 8 things and now something is broken and I don't
  know which task caused it."

THE LAST TASK IS ALWAYS DOCUMENTATION SYNC:
  Update whatever the project's actual source-of-truth files are (architecture docs,
  README, project structure docs) so the spec's knowledge becomes the project's
  permanent knowledge, not knowledge trapped in .spec/ that nobody reads again.

Phase 3 Exit Checklist (Before Requesting Approval)

[ ] Every task traces to a specific REQ-ID and Design section
[ ] Every task has a concrete Definition of Done
[ ] Dependencies between tasks are explicit and form a valid order (no circular deps)
[ ] Non-breaking checkpoints are inserted after MEDIUM/HIGH risk tasks
[ ] The final task is documentation sync
[ ] No task is vague enough that two different agents would interpret it differently

8. PHASE 4 — IMPLEMENTATION RULES

Once task.md is approved, implementation begins. These rules govern execution.

RULE 1: Work ONE task at a time, in order, respecting dependencies.
  Do not jump ahead to TASK-005 because it looks easier. Sequence exists for a reason
  (usually: later tasks assume earlier tasks' output exists).

RULE 2: Before starting a task, re-read its Definition of Done.
  After finishing, verify against that exact definition before checking the box.

RULE 3: Check the box in task.md immediately after a task is verified done.
  Update "Progress: N / Total" in the header. This file is the live status —
  keep it accurate at all times, not just at session end.

RULE 4: At every NON-BREAKING CHECKPOINT task, actually run the check.
  Do not skip it because "the changes were small." The checkpoint exists specifically
  to catch the cases where small changes had unexpected effects.

RULE 5: If you discover during implementation that a task is wrong, incomplete,
  or based on a flawed design assumption — STOP. Do not improvise a fix that
  deviates from the spec. Go to §10 Change Management.

RULE 6: Never implement something that is not in task.md.
  If you notice an opportunity for an unrelated improvement, note it as a new
  potential spec for later — do not fold it into the current implementation.
  Scope creep during implementation is exactly what SDD exists to prevent.

RULE 7: Commit messages and code comments should reference the TASK-ID.
  Example: "TASK-004: Add payout eligibility check (REQ-1, REQ-2)"
  This preserves traceability from code all the way back to the original requirement,
  permanently, in the version control history itself.

RULE 8: When all tasks are checked, update task.md Status to COMPLETE
  and update the entry in .spec/REGISTRY.md accordingly.

9. THE SPEC REGISTRY (.spec/REGISTRY.md)

A single index file at the root of .spec/ tracking every spec ever created in this project. Read this at the start of Phase 0 for any new spec, to check for conflicts or related work.

# Spec Registry

| Slug | Status | Summary | Created | Last Updated | Depends On |
|---|---|---|---|---|---|
| add-creator-payout-system | COMPLETE | Payout flow for creator commissions | 2026-03-01 | 2026-03-14 ||
| migrate-auth-to-jwt | COMPLETE | Replace Firebase auth with custom JWT | 2026-01-10 | 2026-01-28 ||
| refactor-credit-ledger | IN PROGRESS | Normalize credit transaction schema | 2026-06-01 | 2026-06-18 | add-creator-payout-system |
| add-team-workspaces | DRAFT | Multi-user team accounts | 2026-06-19 | 2026-06-19 | refactor-credit-ledger |

## Status Legend
DRAFT — requirement.md exists, not yet approved
REQUIREMENTS APPROVED — design.md in progress
DESIGN APPROVED — task.md in progress
IN PROGRESS — implementation underway, some tasks checked
COMPLETE — all tasks done, documentation synced
ABANDONED — work stopped, reason recorded in the spec's own files
SUPERSEDED — replaced by a newer spec (link to the replacement)

Update this file:

  • When a new spec folder is created (add a DRAFT row)
  • When each phase gate is passed (update status)
  • When implementation completes (status → COMPLETE)
  • When a spec is abandoned or superseded (update status, never delete the row)

10. CHANGE MANAGEMENT — WHEN SOMETHING NEEDS TO CHANGE MID-FLOW

Requirements and designs are not always right the first time. This is normal. What matters is handling change without silently breaking traceability.

IF a requirement needs to change AFTER requirement.md is approved:
  1. Update requirement.md directly — add a changelog note at the top:
     "REVISED <date>: <what changed and why>"
  2. Set Status back to IN REVIEW, get re-approval
  3. Check if design.md or task.md already exist and reference the old requirement —
     if so, they must be updated too, in order (design first, then tasks)
  4. Never let requirement.md, design.md, and task.md drift out of sync with each other

IF a design decision needs to change AFTER design.md is approved (but before/during
implementation):
  1. Update design.md with a changelog note
  2. Set Status back to IN REVIEW, get re-approval
  3. Update task.md to reflect the new design — mark affected tasks, do not silently
     change their meaning without updating their description
  4. If implementation has already started on now-invalid tasks, assess: revert and redo,
     or adapt forward — document the decision either way

IF mid-implementation you discover the design was wrong (not just "could be better" —
actually incorrect or incompatible with reality):
  1. STOP implementation immediately
  2. Document exactly what was discovered and why it invalidates the design
  3. Go back to design.md, propose the fix, get it approved
  4. Update task.md accordingly
  5. Resume implementation from the corrected task list

NEVER:
  - Patch code in a way that contradicts the approved design without updating the design first
  - Let the actual codebase silently diverge from what task.md says was built
  - Treat "I'll fix the docs later" as acceptable — later never comes, and the next
    session (or the next agent) will trust the stale spec over the real code

11. BIG / COMPLEX PROJECT SPECIFIC RULES

These rules apply with extra weight when the target codebase is large, production, revenue-generating, or has many interdependent features.

RULE: ADDITIVE BEFORE DESTRUCTIVE, ALWAYS WHEN POSSIBLE
  Prefer: add a new field over renaming an existing one
  Prefer: add a new endpoint version over changing an existing contract
  Prefer: feature-flag a new code path over replacing the old path outright
  Only choose the destructive/breaking option when the design explicitly justifies why
  the additive option was not viable — and the migration plan must be concrete.

RULE: DEPENDENCY MAPPING IS MANDATORY FOR ANY MODIFIED COMPONENT
  Before marking anything as MODIFIED in Design §3, search the codebase for every
  caller/consumer of that component. List them. For each, assess: does this change
  affect them? If even one is uncertain, the risk rating must be at least MEDIUM and
  a specific verification step belongs in tasks.md.

RULE: SCHEMA CHANGES FOLLOW THE EXPAND-CONTRACT PATTERN
  1. EXPAND: Add the new field/table/column alongside the old one (additive, safe)
  2. DUAL-WRITE: Write to both old and new for a transition period
  3. BACKFILL: Migrate existing data to populate the new structure
  4. SWITCH READS: Move read paths to the new structure
  5. CONTRACT: Remove the old field/table/column only after confirming nothing reads it
  Each of these five steps is its own task (or task group) in task.md — never collapse
  a schema migration into a single "update the schema" task on a live system.

RULE: FEATURE FLAGS FOR ANYTHING RISK-RATED MEDIUM OR HIGH
  New behavior that modifies an existing user-facing flow ships behind a flag, defaulted
  off, until verified. The flag removal (cleanup) is itself a task, not an afterthought.

RULE: NEVER COMBINE AN UNRELATED REFACTOR WITH A FEATURE CHANGE
  If implementing a feature reveals that some adjacent code "really should be refactored
  too" — that is a separate spec. Mixing refactor and feature in one spec makes it
  impossible to isolate what caused a regression if one appears.

RULE: LARGE FEATURES GET MULTIPLE SMALLER SPECS, NOT ONE GIANT ONE
  If requirement.md is growing past what one person could review in 15 minutes, or
  task.md has more than ~25-30 tasks, split into multiple specs with explicit
  dependency links in REGISTRY.md. Smaller specs are reviewable, mergeable, and
  revertible independently. One giant spec becomes unmanageable and risky to approve.

12. ANTI-PATTERNS — NEVER DO THESE

✗ Writing code "to see how it feels" before requirement.md exists
  → Exploratory spikes are fine, but they are throwaway and never become the final
    implementation without a proper spec being written retroactively first.

✗ Treating the approval gate as a formality and barreling ahead anyway
  → If the user hasn't explicitly approved, the next phase has not started. Full stop.

✗ Writing requirements in implementation language ("use a Redis cache for this")
  → That is a design decision. Requirements describe behavior, not mechanism.

✗ A design.md with an empty or skipped "Existing System Impact Analysis" section
  → This is the single most important section for not breaking a big project. Never skip it.

✗ Tasks like "Implement the feature" or "Build the backend"
  → Not atomic, not verifiable, not useful. Break it down further.

✗ Marking a task done without verifying its Definition of Done
  → The checkbox is a promise to future sessions that this work is actually complete.

✗ Letting task.md, design.md, and requirement.md drift out of sync
  → If one changes, check whether the others need to change too. Every time.

✗ Skipping non-breaking checkpoints because "I'm confident it's fine"
  → Confidence is not verification. Run the checkpoint.

✗ Creating a new spec folder for work that belongs in an existing in-progress spec
  → Check REGISTRY.md first. Don't fragment one feature across multiple spec folders.

✗ Deleting or rewriting history in spec files instead of appending changelog notes
  → The point of these files is to preserve the reasoning trail, not just the final state.

13. QUICK REFERENCE — TRIGGER PHRASES AND RESPONSES

User says: "Build/add/create <feature>"
  → Check .spec/REGISTRY.md for related specs
  → Run Phase 0 Context Anchoring
  → Create .spec/<slug>/requirement/requirement.md
  → Draft requirements, request approval
  → STOP and wait for approval before any design work

User says: "Spec this out" / "Plan this properly" / "Don't break anything"
  → Same as above — these phrases are explicit signals to use full SDD rigor

User says: "Looks good, proceed" / "Approved" (after requirements shown)
  → Mark requirement.md Status: APPROVED, update REGISTRY.md
  → Begin Phase 2: create design/design.md
  → Draft design, request approval
  → STOP and wait for approval before any task breakdown

User says: "Approved" (after design shown)
  → Mark design.md Status: APPROVED, update REGISTRY.md
  → Begin Phase 3: create tasks/task.md
  → Draft tasks, request approval
  → STOP and wait for approval before any implementation

User says: "Approved" (after tasks shown) / "Start building"
  → Mark task.md Status: APPROVED → IN PROGRESS, update REGISTRY.md
  → Begin Phase 4: implement task by task, per §8 rules

User says: "Continue" / "What's next" (mid-implementation, new session)
  → Read task.md, find first unchecked task respecting dependency order
  → Confirm current state with user briefly, resume from there

User says: "This isn't working the way we designed it"
  → STOP implementation
  → Go to §10 Change Management
  → Do not improvise around the design — fix the design first

The discipline is the point. Three documents, in order, each approved before the next begins. It feels slower at the start of a feature and saves the entire project at the end of one. Read requirement.md, design.md, and task.md templates in their respective folders for the full field-by-field structure to copy into every new spec.