# Spec-Driven Development (SDD) 🎯

## Flip the Script: Code Serves Specs Now

**The Old Way Was Backwards**

For decades, we've been doing it wrong. Code was king, and specs were just... suggestions? We'd write PRDs, create design docs, draw fancy diagrams—then toss them aside once the "real work" began. Specs were scaffolding we'd build and then forget about. Code was truth. Everything else was just... vibes that got lost in translation.

Here's the problem: code kept moving forward while specs gathered dust. When your asset (code) and your implementation are the same thing, you can't easily spin up parallel experiments or pivot without rebuilding everything from scratch. The specs couldn't keep up, so they became lies we told ourselves.

**SDD Flips the Power Dynamic**

Spec-Driven Development says: **nah, let's invert this whole thing**. 

In SDD, code serves specifications—not the other way around. Your PRD isn't a "guide" for implementation; it's the **source** that generates implementation. Technical plans don't "inform" coding; they're precise definitions that **produce** code. This isn't a tweak to how we build software. This is a complete paradigm shift.

**Closing the Gap (By Eliminating It)**

There's always been this annoying gap between "what we want" and "what we built." We've tried everything to bridge it: better docs, more detailed requirements, stricter processes. All of these fail because they accept the gap as inevitable. They try to narrow it but never close it.

SDD? We just eliminate the gap entirely. When specifications and their implementation plans are **executable**—when they generate code—there is no gap. Just transformation. Spec → Plan → Code. Direct line. No telephone game.

**AI Makes This Possible (Finally)**

This transformation is happening now because AI can actually understand and implement complex specifications. AI can create detailed implementation plans that humans can review and validate. But here's the catch: raw AI generation without structure produces chaos. Just vibing with ChatGPT won't cut it.

SDD provides that structure—specifications and implementation plans that are precise, complete, and unambiguous enough to generate working systems. The spec becomes your primary artifact. Code becomes its expression in whatever language or framework you're using.

**Intent-Driven Development FTW**

In this new world:
- **Maintaining software** = evolving specifications
- **Debugging** = fixing specs and plans that generated incorrect code  
- **Refactoring** = restructuring specs for clarity
- **Adding features** = updating specs and regenerating

Your team's intent lives in natural language, design assets, core principles, and guidelines. The **lingua franca** of development moves to a higher level. Code becomes the last-mile delivery mechanism.

Want to experiment with a new approach? Just create a new implementation plan from the same spec (0 → 1 → 1' → 2 → 3 → N). Because we're creative beings who need room to explore.

**Focus on What Matters**

Your development team gets to focus on:
- 🎨 **Creativity** - exploring solutions
- 🧪 **Experimentation** - trying new approaches  
- 🧠 **Critical thinking** - solving real problems

Not on mechanical translation from spec to code.

## How SDD Actually Works ⚡

**From Vague Idea to Complete Spec (Fast)**

You start with an idea. Usually it's vague, incomplete, kind of fuzzy around the edges. That's fine—that's normal. Through iterative dialogue with AI, that fuzzy idea becomes a comprehensive PRD.

The AI becomes your thought partner:
- Asks clarifying questions you didn't think of
- Identifies edge cases hiding in the shadows
- Helps define precise, measurable acceptance criteria

What used to take days of meetings and documentation? Now happens in hours of focused spec work. The traditional SDLC gets transformed—requirements and design become **continuous activities** rather than waterfall phases. And because everything's in version control with branches and merges, it's a **team process** from day one.

**Living Specifications That Adapt**

Here's where it gets cool: when a product manager updates acceptance criteria, implementation plans automatically flag affected technical decisions. When an architect discovers a better pattern, the PRD updates to reflect new possibilities. Everything stays in sync because the spec is the source.

**Research Agents Do the Homework**

Throughout the specification process, research agents gather critical context in the background:
- Library compatibility checks
- Performance benchmarks  
- Security implications
- Your company's standards (database choices, auth requirements, deployment policies)

All of this seamlessly integrates into every specification. No more "oh wait, we can't use that library because of corporate policy" surprises.

**From PRD to Plan to Code**

From your PRD, AI generates implementation plans that map requirements to technical decisions:
- Every technology choice has documented rationale
- Every architectural decision traces back to specific requirements
- Consistency validation happens continuously (not as a one-time gate)

The AI analyzes specs for ambiguity, contradictions, and gaps as an ongoing refinement process. It's like having a tireless reviewer who never gets bored.

**Start Generating Early**

Code generation kicks off as soon as specs and plans are "stable enough"—they don't have to be perfect or complete. Early generations might be exploratory, testing whether the spec makes sense in practice:

- Domain concepts → Data models
- User stories → API endpoints  
- Acceptance scenarios → Tests

This merges development and testing through specification. Test scenarios aren't written after code—they're part of the spec that generates both implementation and tests.

**The Feedback Loop Never Stops**

The magic extends beyond initial development. Production metrics and incidents don't just trigger hotfixes—they update specifications for the next regeneration:

- Performance bottlenecks → New non-functional requirements
- Security vulnerabilities → Constraints for all future generations
- User feedback → Refined acceptance criteria

This iterative dance between specification, implementation, and operational reality is where true understanding emerges. The traditional SDLC transforms into continuous evolution.

## Why Now? (The Perfect Storm) 🌩️

Three massive trends converge to make SDD not just possible, but **necessary**:

### 1. AI Crossed the Threshold 🤖

AI capabilities hit a sweet spot where natural language specifications can reliably generate working code. We're not talking about replacing developers—we're talking about **amplifying** their effectiveness by automating the boring translation work.

This unlocks:
- 🚀 **Rapid exploration** - try multiple approaches quickly
- 🔄 **Easy start-overs** - pivot without pain
- ➕➖ **Fearless changes** - add, remove, modify without dread
- 🧠 **More thinking time** - less typing, more designing

### 2. Complexity Is Out of Control 📈

Modern systems are wild. You're integrating dozens of services, frameworks, and dependencies. Keeping all these pieces aligned with your original intent through manual processes? Good luck with that.

SDD provides systematic alignment through specification-driven generation. As frameworks evolve to become more AI-first (or architect around more reusable components), SDD keeps you on track.

### 3. Change Is the Only Constant ⚡

Requirements don't just change anymore—they **sprint**. Pivoting isn't exceptional; it's Tuesday. Modern product development demands rapid iteration based on:
- User feedback that comes in real-time
- Market conditions that shift overnight  
- Competitive pressures that never sleep

**The Traditional Approach Breaks Down**

Every pivot requires manually propagating changes through documentation, design, and code. You get two bad choices:
1. **Slow and careful** updates that kill velocity
2. **Fast and reckless** changes that accumulate technical debt

Neither works.

**SDD Changes the Game**

Want to run a what-if experiment? "If we need to pivot the app to sell more T-shirts, how would we implement that?" With SDD, you can actually try it without rebuilding everything.

SDD transforms requirement changes from **obstacles** into **normal workflow**:
- Change a core requirement in the PRD → Implementation plans update automatically
- Modify a user story → Corresponding API endpoints regenerate
- Pivot your business model → Systematic regeneration, not manual rewrite

This isn't just about initial development. It's about **maintaining engineering velocity** through the inevitable chaos of real-world product development.

## Core Principles 💎

### Specs Are the New Code

The specification is your primary artifact. Code? That's just its expression in a particular language and framework. Maintaining software means evolving specifications. It's that simple.

### Executable > Aspirational

Specifications must be precise, complete, and unambiguous enough to actually generate working systems. No hand-waving. No "and then magic happens." This eliminates the gap between intent and implementation.

### Always Refining, Never Done

Consistency validation isn't a one-time gate you pass through. It's continuous. AI analyzes specifications for ambiguity, contradictions, and gaps as an ongoing process. Like a really dedicated editor who never sleeps.

### Research-Powered Context

Research agents gather critical context throughout the specification process:
- Technical options and trade-offs
- Performance implications
- Organizational constraints  
- Industry best practices

They do the homework so you can focus on decisions.

### Production Teaches, Specs Learn

Bidirectional feedback is key. Production reality informs specification evolution:
- Metrics → Requirements
- Incidents → Constraints
- Operational learnings → Specification refinements

Your specs get smarter with every deployment.

### Branch Out and Explore

Generate multiple implementation approaches from the same specification. Explore different optimization targets:
- 🚀 Performance-optimized version
- 🧹 Maintainability-focused version
- 😊 UX-first version
- 💰 Cost-optimized version

Same spec, different expressions. Choose your own adventure.

## How to Actually Do This 🛠️

Right now, practicing SDD means assembling your own toolkit and maintaining discipline. You'll need:

- 🤖 **AI assistants** for iterative spec development
- 🔍 **Research agents** for gathering technical context
- ⚙️ **Code generation tools** for translating specs to implementation  
- 📚 **Version control** adapted for spec-first workflows
- ✅ **Consistency checking** through AI analysis of spec documents

**The Golden Rule**: Treat specifications as the source of truth, with code as generated output that serves the spec—not the other way around.

That's the mindset shift. Everything else flows from there.

## VibeDraft: SDD Made Easy 🚀

The SDD methodology gets supercharged with three commands that automate the whole `specification → planning → tasking` workflow:

### 1. `/vibedraft.draft` - Start the Vibe

This command takes your fuzzy feature idea and transforms it into a complete, structured specification with automatic repo management:

**What it does:**
- 📊 **Auto-numbers features** - scans existing specs to find the next number (001, 002, 003...)
- 🌿 **Creates your branch** - generates a semantic branch name from your description and creates it
- 📝 **Fills the template** - copies and customizes the feature spec template with your requirements
- 📁 **Sets up directories** - creates proper `specs/[branch-name]/` structure for everything

**You give it**: A simple feature description  
**You get**: A complete, numbered, branched, structured specification

### 2. `/vibedraft.plan` - Map the Route

Once you have a spec, this command creates a comprehensive implementation plan:

**What it does:**
- 🔍 **Analyzes your spec** - reads and understands requirements, user stories, and acceptance criteria
- ⚖️ **Checks the constitution** - ensures alignment with project constitution and architectural principles
- 🏗️ **Translates to tech** - converts business requirements into technical architecture and implementation details
- 📚 **Generates docs** - creates data models, API contracts, and test scenarios
- ✨ **Makes a quickstart** - produces a validation guide with key scenarios

**You give it**: Technical hints (optional)  
**You get**: A complete implementation roadmap

### 3. `/vibedraft.tasks` - Break It Down

After planning, this command analyzes everything and generates an executable task list organized into **phases**:

**What it does:**
- 📖 **Reads all the docs** - pulls in `plan.md` (required) plus `data-model.md`, `contracts/`, and `research.md`
- ✅ **Derives tasks** - converts contracts, entities, and scenarios into specific, actionable tasks
- 🎯 **Organizes phases** - groups tasks into Setup, Foundational, User Stories, and Polish phases
- ⚡ **Marks parallel work** - tags independent tasks `[P]` for safe parallelization
- 📊 **Tracks progress** - creates a phase progress overview with visual indicators

**You give it**: Context (optional)  
**You get**: A complete, phase-organized task list with progress tracking

### Real Talk: Building a Chat Feature

Let's compare how this actually works in practice:

**The Old Way (Traditional):**

```text
1. Write a PRD in a document → 2-3 hours
2. Create design documents → 2-3 hours
3. Set up project structure manually → 30 minutes
4. Write technical specifications → 3-4 hours
5. Create test plans → 2 hours

Total: ~12 hours of documentation work (before any actual coding!)
```

**The VibeDraft Way:**

```bash
# Step 1: Start the vibe (5 minutes)
/vibedraft.draft Real-time chat system with message history and user presence

# ✨ Automatically:
# - Creates branch "003-chat-system"
# - Generates specs/003-chat-system/spec.md
# - Populates it with structured requirements

# Step 2: Map the route (5 minutes)
/vibedraft.plan WebSocket for real-time messaging, PostgreSQL for history, Redis for presence

# Step 3: Break it down (5 minutes)
/vibedraft.tasks

# ✨ Creates everything:
# - specs/003-chat-system/plan.md
# - specs/003-chat-system/research.md (WebSocket library comparisons)
# - specs/003-chat-system/data-model.md (Message and User schemas)
# - specs/003-chat-system/contracts/ (WebSocket events, REST endpoints)
# - specs/003-chat-system/quickstart.md (Key validation scenarios)
# - specs/003-chat-system/tasks.md (Phase-organized task list with progress tracking)
```

**In 15 minutes, you get:**

✅ Complete feature spec with user stories and acceptance criteria  
✅ Detailed implementation plan with technology choices and rationale  
✅ API contracts and data models ready for code generation  
✅ Comprehensive test scenarios (automated + manual)  
✅ Phase-organized task list with progress tracking  
✅ All documents properly versioned in a feature branch

**That's 12 hours → 15 minutes. But more importantly:**

- No forgotten details (templates ensure completeness)
- Traceable decisions (every choice links back to requirements)
- Living documentation (specs stay in sync because they generate code)
- Rapid iteration (change requirements and regenerate in minutes, not days)

## Templates: The Secret Sauce 🎨

### How We Guide AI to Make Better Specs

The true power isn't just automation—it's how templates guide AI toward better specifications. Templates act as sophisticated prompts that channel AI behavior in productive ways:

#### 1. Keep Implementation Out of Specs

The feature spec template explicitly says:

```text
- ✅ Focus on WHAT users need and WHY
- ❌ Avoid HOW to implement (no tech stack, APIs, code structure)
```

This keeps the AI from jumping straight to "let's use React with Redux" when it should be thinking "users need real-time updates of their data." Proper abstraction levels mean your specs stay stable even when implementation tech changes.

#### 2. No Guessing Allowed

Both templates mandate `[NEEDS CLARIFICATION]` markers:

```text
When creating this spec from a user prompt:
1. Mark all ambiguities: Use [NEEDS CLARIFICATION: specific question]
2. Don't guess: If the prompt doesn't specify something, mark it
```

This stops the AI from making plausible but potentially wrong assumptions. No more "I'll just assume email/password auth"—if it's not specified, it gets flagged as `[NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]`.

#### 3. Built-In Quality Checks

Templates include checklists that act as "unit tests" for specifications:

```markdown
### Requirement Completeness
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Requirements are testable and unambiguous
- [ ] Success criteria are measurable
```

The AI must self-review systematically, catching gaps before they become problems. It's like a built-in QA framework.

#### 4. Constitutional Gatekeeping

Implementation plans enforce architectural principles through phase gates:

```markdown
### Phase -1: Pre-Implementation Gates
#### Simplicity Gate (Article VII)
- [ ] Using ≤3 projects?
- [ ] No future-proofing?
#### Anti-Abstraction Gate (Article VIII)
- [ ] Using framework directly?
- [ ] Single model representation?
```

These gates prevent over-engineering. If a gate fails, the AI must document why in "Complexity Tracking," creating accountability for every architectural decision.

#### 5. Keep It Readable

Templates enforce proper information architecture:

```text
IMPORTANT: This implementation plan should remain high-level and readable.
Any code samples, detailed algorithms, or extensive technical specs
must be placed in the appropriate implementation-details/ file
```

This prevents specs from becoming unreadable code dumps. The AI learns to maintain appropriate detail levels—complexity goes to separate files, main doc stays navigable.

#### 6. Tests First, Always

Implementation templates enforce test-first development:

```text
### File Creation Order
1. Create contracts/ with API specifications
2. Create test files in order: contract → integration → e2e → unit
3. Create source files to make tests pass
```

This ordering ensures the AI thinks about testability and contracts before implementation. More robust, more verifiable.

#### 7. No Speculation

Templates explicitly ban speculation:

```text
- [ ] No speculative or "might need" features
- [ ] All phases have clear prerequisites and deliverables
```

This stops the AI from adding "nice to have" features that bloat implementation. Every feature must trace back to a concrete user story with clear acceptance criteria.

### The Result: Better Specs, Every Time

These constraints work together to produce specifications that are:

- ✅ **Complete** - checklists ensure nothing is forgotten
- ✅ **Unambiguous** - forced clarification markers highlight uncertainties
- ✅ **Testable** - test-first thinking baked in
- ✅ **Maintainable** - proper abstraction levels and information hierarchy
- ✅ **Implementable** - clear phases with concrete deliverables

Templates transform AI from a creative writer into a disciplined specification engineer, channeling its capabilities toward consistently high-quality, executable specifications that actually drive development.

## The Constitution: Your Architectural DNA 🧬

At the heart of SDD is a constitution—a set of immutable principles that govern how specs become code. The constitution (`memory/constitution.md`) is your architectural DNA, ensuring every generated implementation maintains consistency, simplicity, and quality.

### Nine Articles That Shape Everything

The constitution has nine articles that govern development. Here are the key ones:

#### Article I: Library-First (Always)

Every feature starts as a standalone library. No exceptions. This forces modular design from day one:

```text
Every feature in VibeDraft MUST begin its existence as a standalone library.
No feature shall be implemented directly within application code without
first being abstracted into a reusable library component.
```

This ensures specs generate modular, reusable code—not monolithic apps. When AI generates a plan, it must structure features as libraries with clear boundaries and minimal dependencies.

#### Article II: Everything Gets a CLI

Every library must expose functionality through a command-line interface:

```text
All CLI interfaces MUST:
- Accept text as input (stdin, arguments, or files)
- Produce text as output (stdout)
- Support JSON format for structured data exchange
```

This enforces observability and testability. AI can't hide functionality in opaque classes—everything must be accessible and verifiable through text-based interfaces.

#### Article III: Tests First (Non-Negotiable)

The most transformative article—no code before tests:

```text
This is NON-NEGOTIABLE: All implementation MUST follow strict Test-Driven Development.
No implementation code shall be written before:
1. Unit tests are written
2. Tests are validated and approved by the user
3. Tests are confirmed to FAIL (Red phase)
```

This completely inverts traditional AI code generation. No more "generate code and hope." AI must first generate comprehensive tests that define behavior, get them approved, and only then generate implementation.

#### Articles VII & VIII: Keep It Simple

These paired articles combat over-engineering:

```text
Section 7.3: Minimal Project Structure
- Maximum 3 projects for initial implementation
- Additional projects require documented justification

Section 8.1: Framework Trust
- Use framework features directly rather than wrapping them
```

When AI wants to create elaborate abstractions, these articles force it to justify every layer of complexity. The implementation plan template's "Phase -1 Gates" enforce this directly.

#### Article IX: Test in the Real World

Prioritizes real-world testing over isolated unit tests:

```text
Tests MUST use realistic environments:
- Prefer real databases over mocks
- Use actual service instances over stubs
- Contract tests mandatory before implementation
```

This ensures generated code works in practice, not just in theory. No more "works on my mock."

### How We Enforce the Constitution

Implementation plan templates operationalize these articles through concrete checkpoints:

```markdown
### Phase -1: Pre-Implementation Gates
#### Simplicity Gate (Article VII)
- [ ] Using ≤3 projects?
- [ ] No future-proofing?

#### Anti-Abstraction Gate (Article VIII)
- [ ] Using framework directly?
- [ ] Single model representation?

#### Integration-First Gate (Article IX)
- [ ] Contracts defined?
- [ ] Contract tests written?
```

These gates act like compile-time checks for architectural principles. AI can't proceed without either passing the gates or documenting justified exceptions in "Complexity Tracking."

### Why Immutable Principles Matter

The constitution's power is its immutability. Implementation details can evolve, but core principles stay constant. This gives you:

1. ⏱️ **Consistency across time** - code generated today follows the same principles as code generated next year
2. 🤖 **Consistency across AIs** - different AI models produce architecturally compatible code
3. 🏛️ **Architectural integrity** - every feature reinforces (not undermines) system design
4. ✨ **Quality guarantees** - test-first, library-first, and simplicity principles ensure maintainable code

### The Constitution Can Evolve (Carefully)

While principles are immutable, their application can evolve:

```text
Section 4.2: Amendment Process
Modifications to this constitution require:
- Explicit documentation of the rationale for change
- Review and approval by project maintainers
- Backwards compatibility assessment
```

This lets the methodology learn and improve while maintaining stability. The constitution shows its own evolution with dated amendments, demonstrating how principles refine based on real-world experience.

### It's More Than Rules—It's a Philosophy

The constitution shapes how AI thinks about code generation:

- 🔍 **Observability over opacity** - everything inspectable through CLI interfaces
- 🎯 **Simplicity over cleverness** - start simple, add complexity only when proven necessary
- 🌍 **Integration over isolation** - test in real environments, not artificial ones
- 🧩 **Modularity over monoliths** - every feature is a library with clear boundaries

By embedding these principles into the spec and planning process, SDD ensures generated code isn't just functional—it's maintainable, testable, and architecturally sound. The constitution transforms AI from a code generator into an architectural partner that respects and reinforces your system design.

## The Transformation ✨

**This isn't about replacing developers.** It's about amplifying human capability by automating the boring mechanical translation work.

It's about creating a tight feedback loop where specifications, research, and code evolve together—each iteration bringing deeper understanding and better alignment between intent and implementation.

**Software development has always struggled** with the gap between "what we want" and "what we built." SDD finally closes that gap through executable specifications that generate code rather than merely suggesting it.

**The result?** Developers spend more time on creativity, critical thinking, and experimentation. Less time on mechanical translation and keeping docs in sync with code.

That's the vibe. That's the future. Welcome to Spec-Driven Development. 🚀
