Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

Chapter 09: Spec-Driven Development with GitHub Spec Kit

What if you could go from a feature idea to a fully implemented, tested solution — guided by a structured specification every step of the way?

In the previous chapters, you learned to use GitHub Copilot CLI for individual tasks: generating code, reviewing changes, writing tests, and orchestrating workflows. But how do you tackle a brand-new feature that requires planning, architecture decisions, and coordinated implementation across multiple files?

That's where Spec-Driven Development (SDD) comes in. GitHub Spec Kit is an open-source toolkit that bridges the gap between "I have an idea" and "Here's the working code." It provides a structured workflow — constitution → specification → plan → tasks → implementation — that keeps AI-assisted development aligned with your project's goals and standards.

🎯 Learning Objectives

By the end of this chapter, you'll be able to:

  • Understand the Spec-Driven Development methodology and its benefits
  • Initialize GitHub Spec Kit in an existing project (brownfield)
  • Create a project constitution that defines governance principles
  • Generate a feature specification from natural language requirements
  • Produce a technical implementation plan from your spec
  • Break the plan into actionable, ordered tasks
  • Use the implement workflow to build the feature

⏱️ Estimated Time: ~75 minutes (20 min reading + 55 min hands-on lab)


🧩 Real-World Analogy: Building a House

You wouldn't start building a house by grabbing lumber and nailing boards together. You'd follow a structured process:

Phase House Building Spec-Driven Development
Governance Building codes & zoning laws Constitution (project principles & standards)
Blueprint Architectural drawings Specification (what you're building)
Engineering Structural plans & materials list Plan (how you'll build it)
Schedule Construction timeline & work orders Tasks (ordered implementation steps)
Construction Building the house Implementation (writing the code)

Each phase informs the next. Skip a phase and you risk building something that doesn't meet code, doesn't fit the lot, or collapses under its own weight.

GitHub Spec Kit is your AI-powered general contractor — it helps you produce each document, ensures consistency between them, and then executes the build according to plan.


🔑 Core Concepts

What is Spec-Driven Development?

Spec-Driven Development (SDD) is a methodology where you define what you're building before how you build it. Instead of jumping straight into code, you create structured documents that capture requirements, architecture, and implementation steps. AI assistants like GitHub Copilot then use these documents as context to produce higher-quality, more consistent code.

The SDD Workflow

graph LR
    A[Constitution] --> B[Specification]
    B --> C[Plan]
    C --> D[Tasks]
    D --> E[Implementation]
    E --> F[Verification]
Loading
Document Purpose Key Question
constitution.md Project-wide principles, standards, and governance rules "What rules must ALL features follow?"
spec.md Feature requirements, user stories, and acceptance criteria "What are we building and for whom?"
plan.md Technical architecture, data models, and implementation approach "How will we build it?"
tasks.md Ordered, actionable implementation steps organized by phase "What do we do first, second, third?"

Why SDD with AI?

Without structure, AI assistants can drift — producing code that works in isolation but doesn't align with your project's patterns, standards, or goals. SDD solves this by giving the AI:

  • Constraints (constitution) — "Always use dataclasses, write pytest tests, follow PEP 8"
  • Context (spec) — "The user wants to track reading progress with page numbers"
  • Direction (plan) — "Use the existing BookCollection class, extend data.json schema"
  • Focus (tasks) — "First add the field, then update save/load, then add the CLI command"

GitHub Spec Kit Commands

GitHub Spec Kit integrates with VS Code's Chat view through /speckit.* commands:

Command What It Does
/speckit.constitution Define or update project governance principles
/speckit.specify Create a feature specification from requirements
/speckit.clarify Identify gaps and ambiguities in your spec
/speckit.plan Generate a technical implementation plan
/speckit.tasks Break the plan into ordered, actionable tasks
/speckit.implement Execute tasks to build the feature
/speckit.analyze Audit consistency across spec, plan, and tasks
/speckit.converge Assess codebase against spec and append remaining work

🔧 Prerequisites

Before starting the lab, ensure you have:

  • Specify CLI installed (specify version to verify)
  • VS Code with GitHub Copilot Chat extension
  • Python 3.10+ (for the book app)
  • Git configured and available

💡 Installing Specify CLI: If you don't have it yet, follow the official installation guide. The CLI is required to initialize Spec Kit in your project.


🧪 Lab: Add Reading Progress Tracking to the Book App

In this lab, you'll use GitHub Spec Kit to plan and implement a reading progress tracking feature for the book collection app. Currently, books only have a simple read: true/false flag. You'll extend this to track page progress (current page, total pages, percentage complete) — a meaningful enhancement that touches the data model, business logic, CLI interface, and tests.

📋 Scenario: You're a developer on the book app team. A stakeholder has requested that users be able to track how far they've gotten in each book — not just whether they've finished it. You'll use Spec-Driven Development to plan and implement this feature methodically.


Task 1: Initialize GitHub Spec Kit in the Book App Project

GitHub Spec Kit needs to be initialized in your project before you can use the /speckit.* commands. Since the book app already exists (a "brownfield" project), Spec Kit will preserve your existing files and add its configuration alongside them.

Steps

  1. Open a terminal and navigate to the book app project:

    cd samples/book-app-project
  2. Initialize GitHub Spec Kit:

    specify init --here --integration copilot --script sh

    💡 On Windows? Use --script ps instead of --script sh for PowerShell scripts.

    This command:

    • --here — Initializes in the current directory (preserving existing files)
    • --integration copilot — Configures GitHub Copilot as the AI assistant
    • --script sh — Uses bash scripts for automation
  3. Verify the initialization by checking the new folder structure:

    tree -L 2 .github .specify .vscode

    You should see:

    .github/
    ├── agents/          (Spec Kit agent workflows)
    └── prompts/         (Prompt files for /speckit.* commands)
    .specify/
    ├── memory/          (Constitution and project memory)
    ├── scripts/         (Automation scripts)
    └── templates/       (Document templates for spec, plan, tasks)
    .vscode/
    └── settings.json    (VS Code configuration)
    
  4. Open the project in VS Code (if not already open):

    code .
  5. Verify Spec Kit commands are available by typing /speckit in the Chat view. You should see autocomplete suggestions for all available commands.

⚠️ Troubleshooting: If commands don't appear, try reloading VS Code (Ctrl+Shift+P → "Developer: Reload Window"). Ensure .github/prompts/ exists in your workspace root.


Task 2: Generate the Constitution

The constitution defines the principles and standards that govern your entire project. For the book app, this includes coding standards, testing requirements, and architectural constraints that any new feature must follow.

Steps

  1. In VS Code's Chat view, generate the constitution using context about your project:

    /speckit.constitution --text "This is a Python CLI application that manages a personal book collection. Core principles: use dataclasses for models, pytest for testing, JSON file storage, PEP 8 compliance, type hints required, all public functions must have docstrings. The app prioritizes simplicity, readability, and maintainability over performance. Security: validate all user inputs. Testing: maintain >80% code coverage." --files book_app.py books.py
    
  2. Monitor GitHub Copilot's response. It will analyze your existing code and the principles you provided to generate a constitution.md file.

  3. Once complete, review the generated constitution. It should include:

    • Core Principles — Specific, actionable rules (e.g., "All data models MUST use Python dataclasses")
    • Technical Standards — Language version, testing framework, code style
    • Governance — How principles are applied and enforced
  4. Verify that principles are specific and actionable:

    • ✅ Good: "All CLI commands MUST validate input before processing (type checking, empty string checks, range validation)"
    • ❌ Vague: "Follow best practices for input handling"
  5. Accept the changes by selecting Keep in the Chat view.

  6. Save the files and commit:

    git add -A
    git commit -m "Add project constitution via GitHub Spec Kit"

Task 3: Generate the Feature Specification

The specification defines what you're building from the user's perspective — features, user stories, and acceptance criteria — without prescribing how to implement them.

Steps

  1. In the Chat view, generate the spec for the reading progress feature:

    /speckit.specify --text "Reading progress tracking: Users should be able to track how far they've read in each book. They need to set the total number of pages for a book, update their current page as they read, and see a percentage completion. The CLI should have commands to set pages, update progress, and display progress alongside the book list. Books without page info should still show the simple read/unread status." --files books.py book_app.py data.json
    
  2. Grant permission when GitHub Copilot requests to create a new branch. The specify workflow creates a feature branch for your specification work.

  3. Wait for the specification to be generated (this may take 3–5 minutes).

  4. Review the generated spec.md file. Verify it includes:

    • User Scenarios & Testing — Given/When/Then acceptance scenarios:

      • ✅ "Given a book exists in the collection, When the user sets total pages to 350, Then the book's total pages field is updated and saved"
      • ✅ "Given a book has current_page=175 and total_pages=350, When the user views the book list, Then the progress shows as 50%"
    • Requirements — Specific, testable requirements:

      • "System MUST allow users to set total page count for any book"
      • "System MUST allow users to update their current page number"
      • "System MUST calculate and display reading progress as a percentage"
      • "System MUST validate that current page does not exceed total pages"
    • Success Criteria — Measurable outcomes for the feature

  5. Accept the specification and commit:

    git add -A
    git commit -m "Add reading progress tracking specification"

💡 Want to refine the spec? Run /speckit.clarify to identify ambiguities and gaps. The clarify workflow asks targeted questions and encodes your answers back into the spec.


Task 4: Generate the Technical Plan

The plan bridges "what" (specification) and "how" (implementation). It defines architecture decisions, data model changes, and the technical approach — all while respecting the constitution's constraints.

Steps

  1. In the Chat view, generate the implementation plan:

    /speckit.plan --files books.py data.json pyproject.toml
    
  2. Monitor GitHub Copilot's response and grant permissions as needed. The plan workflow reads your constitution, spec, and referenced files to produce the technical design.

  3. Wait for plan generation (this may take 5–8 minutes).

  4. Review the generated files:

    File Purpose
    plan.md Technical implementation strategy and architecture decisions
    data-model.md Schema changes (e.g., adding current_page and total_pages fields to the Book dataclass)
    research.md Technology decisions and rationale
    quickstart.md Setup instructions for implementing the feature
  5. Verify the plan aligns with your existing architecture:

    • Uses the existing Book dataclass (not a new class)
    • Extends data.json schema (backward-compatible with existing data)
    • Adds methods to BookCollection (not a separate service)
    • Includes pytest test specifications
  6. Accept the plan and commit:

    git add -A
    git commit -m "Add technical plan for reading progress tracking"

Task 5: Generate Implementation Tasks

The tasks document breaks the plan into specific, ordered implementation steps. Each task should be small enough to complete in a focused session and have clear acceptance criteria.

Steps

  1. In the Chat view, generate the tasks:

    /speckit.tasks
    
  2. Wait for task generation (3–5 minutes). The workflow analyzes your spec and plan to produce an ordered task list.

  3. Review the tasks.md file. Verify that tasks are ordered logically:

    Phase Example Tasks
    Setup Update Book dataclass with current_page and total_pages fields
    Data Layer Update load_books() for backward compatibility, update save_books()
    Business Logic Add set_pages(), update_progress(), get_progress() methods
    CLI Interface Add progress and set-pages commands to book_app.py
    Display Update show_books() to display progress percentage
    Testing Write pytest tests for all new functionality
    Validation Add input validation (pages > 0, current ≤ total)
  4. Verify coverage — every requirement from spec.md and every design decision from plan.md should map to at least one task.

  5. Accept the tasks and commit:

    git add -A
    git commit -m "Add implementation tasks for reading progress tracking"

Task 6: Implement the Feature

With a clear specification, technical plan, and ordered tasks, you're ready to implement. The /speckit.implement workflow processes tasks sequentially, writing code that adheres to your constitution and plan.

Steps

  1. Review the Implementation Strategy section in tasks.md to identify the MVP task range. For example, if Setup through CLI Interface tasks are T001–T020:

    /speckit.implement Implement all tasks for the reading progress tracking feature (Tasks: T001 - T020)
    

    ⚠️ Important: Use the actual task range from YOUR tasks.md file. The numbers above are examples.

  2. Monitor GitHub Copilot's progress and grant permissions as requested. The agent builds incrementally, task by task, following the order defined in tasks.md.

  3. Once implementation is complete, verify the changes:

    # Check what files were modified/created
    git status
    
    # Run the existing tests to ensure nothing is broken
    python -m pytest tests/ -v
    
    # Try the new CLI commands
    python book_app.py list
    python book_app.py set-pages "The Hobbit" 310
    python book_app.py progress "The Hobbit" 150
    python book_app.py list
  4. Verify acceptance scenarios from the spec:

    Scenario How to Test
    Set total pages python book_app.py set-pages "1984" 328 → success message
    Update current page python book_app.py progress "1984" 164 → shows 50%
    View progress in list python book_app.py list → shows "[50%]" next to 1984
    Invalid: current > total python book_app.py progress "1984" 999 → error message
    No pages set python book_app.py list → shows "[✓]" or "[ ]" as before
  5. If tests fail or the app doesn't behave as expected, report the issue to GitHub Copilot in the Chat view with the error message. Continue iterating until all acceptance scenarios pass.

  6. Accept all changes, save, and commit:

    git add -A
    git commit -m "Implement reading progress tracking feature"

Task 7: Verify and Clean Up

After implementation, verify the complete feature works end-to-end and ensure backward compatibility.

Steps

  1. Run the full test suite:

    python -m pytest tests/ -v --tb=short
  2. Verify backward compatibility — existing books in data.json that don't have page information should still display correctly:

    python book_app.py list
  3. Test the complete workflow:

    # Add a new book
    python book_app.py add
    # (Enter: "Clean Code", "Robert C. Martin", "2008")
    
    # Set pages for it
    python book_app.py set-pages "Clean Code" 464
    
    # Track progress
    python book_app.py progress "Clean Code" 100
    python book_app.py list
    # Should show: [ 22%] Clean Code by Robert C. Martin (2008)
  4. Review what Spec Kit produced — open and browse the spec documents to understand the full audit trail:

    ls specs/
    # spec.md, plan.md, tasks.md, data-model.md, etc.

🎉 Congratulations! You've completed a full Spec-Driven Development cycle — from feature idea through structured planning to working implementation.


📝 Assignment: Add a New Feature Using SDD

Now practice the full SDD workflow independently. Choose one of the following features to add to the book app:

Option A: Book Ratings and Reviews

Users can rate books (1–5 stars) and write short text reviews. The CLI should have commands to rate a book, add a review, and list books sorted by rating.

Option B: Reading Goals

Users can set monthly/yearly reading goals (e.g., "read 12 books this year"). The CLI tracks progress toward the goal and shows a summary.

Option C: Book Tags and Categories

Users can tag books with categories (fiction, sci-fi, history, etc.) and filter the book list by tag.

Your Task

  1. Use /speckit.specify to create the specification for your chosen feature
  2. Use /speckit.clarify to refine any ambiguities
  3. Use /speckit.plan to generate the technical plan
  4. Use /speckit.tasks to create the implementation task list
  5. Use /speckit.implement to build the feature
  6. Verify all acceptance scenarios pass

💡 Challenge: Before running /speckit.implement, try implementing the first 2–3 tasks manually using what you've learned in earlier chapters. Compare your approach with what Spec Kit generates.


Summary

🔑 Key Takeaways

  1. Structure before code: SDD ensures you understand what you're building before jumping into how
  2. Constitution = governance: Project-wide rules that keep every feature consistent
  3. Spec = requirements: User-facing description of the feature without implementation details
  4. Plan = architecture: Technical decisions that respect the constitution's constraints
  5. Tasks = execution: Ordered steps that map directly to spec requirements and plan decisions
  6. AI alignment: Each document gives the AI more context, producing better code with fewer iterations
  7. Brownfield-friendly: Spec Kit works with existing projects — it preserves your code and builds alongside it

When to Use SDD

Scenario Use SDD? Why
Adding a significant new feature ✅ Yes Multiple files, data model changes, needs planning
Quick bug fix ❌ No Use /review or direct Copilot prompts
Refactoring existing code 🤔 Maybe If the refactor is large and cross-cutting
New greenfield project ✅ Yes Perfect for establishing architecture from scratch
Adding a single utility function ❌ No Overhead doesn't justify the benefit

➡️ What's Next

You've now experienced the full spectrum of GitHub Copilot development — from quick CLI commands to structured, specification-driven feature development. Spec-Driven Development gives you a repeatable methodology for tackling complex features with confidence.

Review earlier chapters to solidify your understanding:

Explore further:


← Back to Chapter 08 | Return to Course Home →