Skip to content

Latest commit

 

History

History
448 lines (339 loc) · 16 KB

File metadata and controls

448 lines (339 loc) · 16 KB

🌟 Spec-Driven Development with Spec Kit — Cursor Tutorial

Goal: Build a small Todos API using Spec-Driven Development (SDD), Spec Kit, and Cursor AI. Follow the workflow from spec → plan → tasks → implementation → tests → validation.


Overview: Spec-Driven Development (SDD)

SDD workflow:

  1. Constitution → define principles guiding code & AI behavior → /speckit.constitution
  2. Spec → behavior-only requirements (authoritative) → /speckit.specify
  3. Plan → technical architecture & file structure → /speckit.plan
  4. Tasks → atomic, verifiable implementation steps → /speckit.tasks
  5. Implement → code + tests strictly following tasks/spec → /speckit.implement
  6. Iterate → update spec first, then plan/tasks/code/tests → /speckit.specify/speckit.plan/speckit.tasks/speckit.implement

Why SDD: Guarantees predictable, testable behavior and clear traceability.


Step 1 — Install Spec Kit

Persistent install:

uv tool install specify-cli --from git+https://github.com/github/spec-kit.git

One-time run:

uvx --from git+https://github.com/github/spec-kit.git specify init . --ai cursor-agent

Note: Always include --ai cursor-agent when initializing a project for Cursor.

Verify:

specify --help

Step 2 — Initialize Project

specify init . --ai cursor-agent

Important: The --ai cursor-agent flag configures spec-kit specifically for Cursor AI, ensuring all commands and templates are optimized for Cursor's workflow. For information about other supported AI agents, refer to the Supported AI Agents section in the Spec Kit documentation.

Resulting .specify folder:

.
├── .cursor
│   └── commands
│       ├── speckit.analyze.md
│       ├── speckit.checklist.md
│       ├── speckit.clarify.md
│       ├── speckit.constitution.md
│       ├── speckit.implement.md
│       ├── speckit.plan.md
│       ├── speckit.specify.md
│       ├── speckit.tasks.md
│       └── speckit.taskstoissues.md
├── .specify
│   ├── memory
│   │   └── constitution.md
│   ├── scripts
│   │   └── bash
│   │       ├── check-prerequisites.sh
│   │       ├── common.sh
│   │       ├── create-new-feature.sh
│   │       ├── setup-plan.sh
│   │       └── update-agent-context.sh
│   └── templates
│       ├── agent-file-template.md
│       ├── checklist-template.md
│       ├── plan-template.md
│       ├── spec-template.md
│       └── tasks-template.md

Notes:

  • .cursor/commands/ → Cursor-specific command definitions for all spec-kit commands (these enable /speckit.* commands in Cursor's chat)
  • .specify/memory/ → stores constitution & project memory
  • .specify/scripts/bash/ → automation scripts
  • .specify/templates/ → AI templates for spec, plan, tasks

Step 3 — Define Constitution

Use Cursor's AI chat:

/speckit.constitution
Define principles:
- Spec-driven development: no behavior outside spec
- Tests must map directly to spec
- Code readability & maintainability
- Validation rules strictly enforced

This updates .specify/memory/constitution.md.

What gets created:

  • .specify/memory/constitution.md - Project constitution with 4 core principles:
    1. Spec-Driven Development (NON-NEGOTIABLE)
    2. Test-Spec Alignment (NON-NEGOTIABLE)
    3. Code Readability & Maintainability
    4. Strict Validation Enforcement
  • Governance section with amendment process and compliance review

Note: The /speckit.constitution command is available because of the .cursor/commands/speckit.constitution.md file created during initialization. All spec-kit commands are now available in Cursor's chat interface. The AI agent will help you define and refine your constitution based on your project needs.


Step 4 — Write the SPEC

Use Cursor's AI chat:

/speckit.specify
Define behavior-only spec for Todos API:
- Endpoints: POST /todos, GET /todos, GET /todos/:id, PUT /todos/:id, DELETE /todos/:id
- Data model: title (required, unique case-insensitive), description optional, dueDate optional (ISO8601, not past), done boolean default false, timestamps
- Filtering: done=true/false, dueBefore=ISO8601
- Validation: title uniqueness, dueDate constraints
- Error handling: standardized
- Non-functional: in-memory store, structure ready for DB

Output: specs/001-todos-api/spec.md

What gets created:

  • specs/001-todos-api/spec.md - Complete feature specification with user stories, requirements, and success criteria
  • specs/001-todos-api/checklists/requirements.md - Quality checklist for spec validation
  • A new git branch 001-todos-api is created and checked out

Note: The spec should be behavior-only and authoritative. All implementation must follow the spec exactly. The command automatically creates a numbered feature branch and directory structure.


Step 5 — Generate the PLAN

Use Cursor's AI chat:

/speckit.plan
From the spec, propose Node+Express backend:
- Service layer: todoService with in-memory store
- File layout: src/app.js, src/index.js, src/routes/todos.js, src/services/todoService.js
- Tests: jest + supertest
- Include validation, filters, sorting, CI setup

Output: Multiple design artifacts are created:

  • specs/001-todos-api/plan.md - Technical implementation plan with project structure
  • specs/001-todos-api/research.md - Technology decisions and rationale
  • specs/001-todos-api/data-model.md - Entity definitions and validation rules
  • specs/001-todos-api/contracts/api-spec.json - OpenAPI specification for all endpoints
  • specs/001-todos-api/quickstart.md - API usage guide with examples
  • .cursor/rules/specify-rules.mdc - Updated Cursor context with tech stack info

What the plan includes:

  • Technical context (language, dependencies, testing framework)
  • Project structure (file layout, directory organization)
  • Constitution check (validates against project principles)
  • Data model extracted from spec
  • API contracts matching all endpoints
  • Research decisions for technology choices

Note: The /speckit.plan command automatically generates all design artifacts. The research step is built-in and documents technology decisions. The plan validates against your constitution automatically.


Step 6 — Generate TASKS

Use Cursor's AI chat:

/speckit.tasks

Output: specs/001-todos-api/tasks.md

The generated tasks.md file contains:

  • Task breakdown organized by user story - Each user story becomes a separate implementation phase
  • Dependency management - Tasks are ordered to respect dependencies between components
  • Parallel execution markers - Tasks that can run in parallel are marked with [P]
  • File path specifications - Each task includes the exact file paths where implementation should occur
  • Test-driven development structure - Test tasks are included and ordered to be written before implementation
  • Checkpoint validation - Each user story phase includes checkpoints to validate independent functionality

Example from our Todos API (59 tasks total):

  • Phase 1: Setup (4 tasks) - Project initialization
  • Phase 2: Foundational (5 tasks) - Express app, error handling, storage structure
  • Phase 3: User Story 1 - Create Todo (12 tasks: 6 tests + 6 implementation)
  • Phase 4: User Story 2 - Retrieve Todos (14 tasks: 9 tests + 5 implementation)
  • Phase 5: User Story 3 - Update Todo (10 tasks: 6 tests + 4 implementation)
  • Phase 6: User Story 4 - Delete Todo (6 tasks: 4 tests + 2 implementation)
  • Phase 7: Polish & Cross-Cutting (8 tasks) - CI, edge cases, documentation

Task format example:

- [ ] T010 [P] [US1] Write integration test for POST /todos with only title in tests/integration/todos.test.js
- [ ] T016 [US1] Implement createTodo method in src/services/todoService.js with title validation

Step 7 — Implement Code & Tests

Use the /speckit.implement command in Cursor's AI chat:

/speckit.implement

This command will:

  • Validate that all prerequisites are in place (constitution, spec, plan, and tasks)
  • Parse the task breakdown from tasks.md
  • Execute tasks in the correct order, respecting dependencies and parallel execution markers
  • Follow the TDD approach defined in your task plan
  • Provide progress updates and handle errors appropriately

Note: The AI agent will execute local CLI commands (such as npm, node, etc.) - make sure you have the required tools installed on your machine.

After implementation, run tests:

npm test

Purpose: Ensures strict adherence to spec through automated task execution.

Troubleshooting: Once the implementation is complete, test the application and resolve any runtime errors that may not be visible in CLI logs (e.g., browser console errors). You can copy and paste such errors back to Cursor's AI chat for resolution.

Alternative Manual Approach: If you prefer to implement tasks manually, you can ask Cursor's AI:

Implement Task T016 from specs/001-todos-api/tasks.md.
Reference authoritative spec in specs/001-todos-api/spec.md.
Implement only the requested file.
Enforce all behaviors & invariants.
Write code + tests if applicable.

Step 8 — Validate

specify check
  • Verifies spec → plan → tasks → code consistency
  • Checks test coverage
  • Flags missing or inconsistent items

Step 9 — Continuous Integration

Create .github/workflows/ci.yml:

name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm test

Step 10 — Iterate

  • Always update the spec first for behavior changes
  • Regenerate or adjust plan/tasks
  • Implement code/tests
  • Validate with specify check & npm test

Workflow:

spec → plan → tasks → code → tests → specify check

Example iteration:

  1. Update specs/001-todos-api/spec.md with new requirements
  2. Run /speckit.plan to update technical design (Step 5)
  3. Run /speckit.tasks to regenerate task breakdown (Step 6)
  4. Implement new tasks or update existing code (Step 7)
  5. Run tests and specify check to validate (Step 8)

Progress Summary: Steps Completed

Step 1 - Installed Spec Kit
Step 2 - Initialized project with --ai cursor-agent
Step 3 - Defined constitution (4 principles)
Step 4 - Created specification (4 user stories, 18 requirements)
Step 5 - Generated implementation plan (research, data model, contracts, quickstart)
Step 6 - Generated task breakdown (59 tasks organized by user story)

Step 7 - Implementation (ready to start with /speckit.implement)
Step 8 - Validation
Step 9 - Continuous Integration
Step 10 - Iteration (as needed)


Step 11 — Actual Project Structure (After Steps 1-6)

This is the structure we've created so far following the tutorial:

todo-spec-sdd/
  .cursor/
    commands/
      speckit.analyze.md
      speckit.checklist.md
      speckit.clarify.md
      speckit.constitution.md
      speckit.implement.md
      speckit.plan.md
      speckit.specify.md
      speckit.tasks.md
      speckit.taskstoissues.md
    rules/
      specify-rules.mdc          # Auto-generated Cursor context
  .specify/
    memory/
      constitution.md             # Created in Step 3
    scripts/
      bash/
        check-prerequisites.sh
        common.sh
        create-new-feature.sh
        setup-plan.sh
        update-agent-context.sh
    templates/
      agent-file-template.md
      checklist-template.md
      plan-template.md
      spec-template.md
      tasks-template.md
  specs/
    001-todos-api/                # Created by /speckit.specify
      checklists/
        requirements.md            # Spec quality checklist
      contracts/
        api-spec.json             # OpenAPI spec (from /speckit.plan)
      data-model.md                # Entity definitions (from /speckit.plan)
      plan.md                      # Implementation plan (from /speckit.plan)
      quickstart.md                # API usage guide (from /speckit.plan)
      research.md                  # Tech decisions (from /speckit.plan)
      spec.md                      # Feature specification (from /speckit.specify)
      tasks.md                     # Task breakdown (from /speckit.tasks)
  Tutorial.md

Note: The src/ and tests/ directories will be created during Step 7 (Implementation) when you run /speckit.implement or start implementing tasks manually.


Key Takeaways

  • Spec is authoritative — never code outside spec
  • Plan & Tasks ensure traceability and proper architecture
  • Cursor AI + Spec Kit streamline implementation and task generation
  • Validation ensures spec → code → tests alignment
  • Iteration keeps development flexible & predictable
  • Automated Implementation/speckit.implement executes tasks in the correct order with dependency management

This tutorial is fully aligned with:

  • Your .cursor/commands/ and .specify/ directory structure
  • Latest Spec Kit CLI & AI commands
  • SDD workflow from spec → implementation → validation
  • Cursor AI integration and best practices

Cursor-Specific Tips

Using Spec Kit Commands in Cursor

All spec-kit commands work seamlessly in Cursor's AI chat. These commands are available because of the .cursor/commands/ directory created during initialization with --ai cursor-agent:

  • /speckit.constitution - Define or update your project constitution
  • /speckit.specify - Generate behavior-only specifications
  • /speckit.plan - Create technical implementation plans
  • /speckit.tasks - Generate detailed task breakdowns
  • /speckit.implement - Automatically implement tasks in order
  • /speckit.analyze - Analyze code against specifications
  • /speckit.checklist - Generate implementation checklists
  • /speckit.clarify - Clarify ambiguous requirements
  • /speckit.taskstoissues - Convert tasks to GitHub issues

How it works: The .cursor/commands/ directory contains markdown files that define each command. When you type /speckit.* in Cursor's chat, it automatically loads the corresponding command definition and executes it with the AI agent.

Cursor AI Chat Shortcuts

  • Open Chat: Cmd+L (Mac) or Ctrl+L (Windows/Linux)
  • Composer Mode: Cmd+I (Mac) or Ctrl+I (Windows/Linux) for multi-file editing
  • Inline Edit: Select code and use Cmd+K (Mac) or Ctrl+K (Windows/Linux)

Best Practices with Cursor

  1. Reference Files: When asking Cursor to implement tasks, reference the spec file:

    Implement this task following specs/001-todos-api/spec.md
    
  2. Validate Incrementally: After each major step, run specify check to ensure consistency

  3. Use Composer Mode: For complex multi-file implementations, use Composer mode (Cmd+I) to edit multiple files simultaneously

  4. Check Prerequisites: Before running /speckit.implement, ensure all required tools are installed (Node.js, npm, etc.)


Additional Resources

For more information about Spec-Driven Development and Spec Kit, visit:

For Cursor-specific help: