Spec Coding Workflow
Write specs first, then generate code. 5 phases, each producing artifacts that feed the next.
When to Use
Trigger conditions:
- User mentions "spec coding", "spec-first", "spec-driven development"
- User asks to write specs / requirements / design docs before implementation
- User mentions phase keywords: "clarify requirements", "write a spec", "generate from spec"
Complexity triage — choose the right track:
| Track | When | Phases | Artifacts |
|---|---|---|---|
| Small | Single endpoint, field addition, < 1 hr | Spec (lite) → Generate → Verify | spec_xxx.md only |
| Medium | Single feature, 1–4 hrs, 1–3 modules | Clarify (brief) → Spec → Generate → Verify | spec_xxx.md + tasks.md |
| Large | Multi-module, > 4 hrs, or new system | Full 5-phase workflow | All spec files |
Ask the user which track fits, or infer from the scope of their request.
Full workflow phases (Large track):
- Clarify & Scope — requirements clarification + structured decomposition
- Spec — author spec documents (requirements.md / design.md / tasks.md / spec_xxx.md)
- Generate — produce code and tests from spec
- Verify — static review + run tests against spec
- Iterate — evolve spec and code together
Small track shortcut:
Skip Phase 1. Write a single spec_xxx.md (Interface + Business Rules + Test Points only), then go straight to Generate → Verify.
Medium track shortcut:
Phase 1 is a brief bullet-point confirmation (no full requirements.md). Phase 2 produces tasks.md + spec_xxx.md only (skip design.md unless architecture decisions are needed).
Mid-project entry: If the user already has spec files or an existing codebase, read them first. Validate existing artifacts against the expected format, then confirm which phase to start from.
File Organization
All spec artifacts go in a specs/ directory at the project root:
specs/
├── requirements.md
├── design.md
├── tasks.md
└── spec_<feature_name>.md (one per feature)
Phase 0 (Optional): Codebase Scan
For existing codebases, run before Phase 1:
- Read dependency files (
package.json,requirements.txt,go.mod, etc.) to detect tech stack. - List directory tree to understand project structure.
- Identify existing interfaces, data models, and conventions.
- Summarize findings — this becomes context for all subsequent phases.
Phase 1: Clarify & Scope
Goal: Turn informal requirements into a confirmed, structured requirements.md.
Constraints: Do NOT write any code. Only ask questions and produce documents.
Step 1: Interactive Clarification
Ask the user to dump raw requirements. Then engage in Q&A:
- Summarize understood goals (3–5 bullet points).
- List ambiguities with suggested options for each.
- Suggest constraints the user may not have considered.
Iterate until the user confirms understanding is accurate.
Step 2: Structured Requirements
Once clarified, produce specs/requirements.md containing:
- Background & Objectives
- User Roles & Use Cases
- Functional Requirements (grouped by module, numbered FR-001, FR-002, ...)
- Non-Functional Requirements (performance, availability, security, observability)
- Out of Scope (explicitly list what will NOT be built)
- Existing Architecture (if Phase 0 was run — what exists, what's new, what's modified)
Exit condition: User approves requirements.md.
Phase 2: Spec
Goal: Produce spec documents that directly drive code generation.
The "spec trio" + per-feature specs:
2a: Technical Design → specs/design.md
Based on requirements.md, produce:
- Architecture overview (tech stack, layers, services)
- Core module breakdown with responsibilities and dependency directions
- Key data models (domain objects only)
- Key interfaces & interaction flows
- Cross-cutting concerns:
- Error handling strategy (classification, propagation, retry)
- Authentication & authorization model
- Observability (logging, metrics, tracing)
- Deployment & configuration (topology, env management, data migration)
- NFR fulfillment matrix — how each NFR from requirements is satisfied by design
- Key architecture decisions (ADR format: context → options → decision → consequences)
For existing codebases: include an "Existing Architecture" section marking what's new vs. modified.
Skip items 5–7 on the Small track. On Medium track, include only the items relevant to the feature.
Exit condition: User approves design.md.
2b: Task Breakdown → specs/tasks.md
Based on design.md, produce a task table:
| Task ID | Name | Module | Dependencies | Related Spec | Acceptance Criteria | AI-Automatable |
|---|---|---|---|---|---|---|
| TASK-001 | ... | ... | — | spec_xxx.md | ... | Yes/No |
- Target granularity: 30–90 minutes per task.
- Related Spec column links each task to its
spec_xxx.md.
Exit condition: User approves tasks.md.
2c: Feature Spec → specs/spec_<feature>.md
For each feature or module, produce a feature spec:
- Feature Description & Use Cases
- Interface Definition — path, method, params (with types & constraints), response structure, error codes
- Data Model & Persistence — tables / collections / fields
- Business Rules & Edge Cases — including error scenarios
- Test Points — use this format:
| TP-ID | Category | Input | Expected Output | Notes |
|---|---|---|---|---|
| TP-001 | Normal | valid input example | expected result | |
| TP-002 | Error | invalid input example | error response | |
| TP-003 | Boundary | edge case input | expected behavior |
Aim for 5–10 test points per feature covering normal / error / boundary.
Exit condition: User approves all spec files.
Phase 3: Generate
Goal: Produce implementation code + tests strictly based on the spec.
Spec adherence — tiered rules:
| Tier | Scope | Rule |
|---|---|---|
| Strict | Interfaces, data models, business rules | Follow spec exactly. Do not change signatures, field names, or behavior. |
| Flexible | Internal implementation (function names, code organization, logging, error messages) | AI decides, but must note deviations in Human-review points. |
| SPEC-GAP | Scenarios the spec doesn't cover (discovered during coding) | Implement a reasonable solution, tag it [SPEC-GAP], and continue. Collect all gaps for batch review in Phase 4. |
Never silently deviate from Strict-tier items. If a Strict item is wrong or incomplete, flag it and ask the user — but do not block on every minor gap.
Steps
- Scan project structure and tech stack (or use Phase 0 results).
- For each task in
tasks.md, take its linkedspec_xxx.mdas input. - Output per task:
- File list (create vs. modify, with paths)
- Implementation code
- Tests derived from spec Test Points (TP-001 → test function)
- Human-review points — Flexible-tier deviations + all
[SPEC-GAP]items
- Tag generated code with task IDs in commit messages:
feat(TASK-001): ...
For existing codebases: clearly distinguish "new file" vs. "modify existing file" and show diffs for modifications.
Phase 4: Verify
Goal: Confirm generated code satisfies the spec through both review and execution.
4a: Static Verification
Compare code against spec_xxx.md:
- All business rules and edge cases covered?
- Input/output matches spec interface definition?
- Unhandled exception scenarios?
4b: Dynamic Verification
Run actual tests and checks:
- Execute test suite (e.g.,
pytest,npm test,go test) - Run linter / type checker if available
- Compare test results against spec Test Points
4c: SPEC-GAP Review
Collect all [SPEC-GAP] items from Phase 3. For each gap:
- Accept — the implementation is correct; update the spec to match.
- Reject — the implementation is wrong; fix the code.
- Defer — not critical now; add to backlog.
Output
- Passed — items that satisfy the spec
- Failed — items that deviate, with recommendation: fix spec or fix code
- SPEC-GAP resolutions — accepted / rejected / deferred for each gap
Phase Transitions
- All passed → proceed to next task or Phase 5 for iteration
- Failed items → update spec (Phase 2) or fix code (Phase 3) → re-verify
Exit condition: All items pass, or user acknowledges remaining gaps.
Phase 5: Iterate / Refactor
Goal: Evolve the feature while keeping spec and code in sync.
Key rule: Always update the spec BEFORE updating the code.
Steps
- Take current spec, code overview, and new change request as input.
- Output:
- Impact Analysis — which interfaces / data structures / modules are affected
- Updated Spec — mark additions (
[NEW]), modifications ([MODIFIED]), deprecations ([DEPRECATED]) - Code Change List — files and locations to modify, with suggestions
- Refactoring Advice — if original design cannot support the new requirement
- After spec update is approved, execute code changes (→ Phase 3) and verify (→ Phase 4).
Maintain a changelog at the top of each spec file:
## Changelog
| Date | Change | Reason |
|------|--------|--------|
| YYYY-MM-DD | Added field X to User model | FR-012 |
Cross-Phase Guidelines
- No phase skipping: Do not generate code without a confirmed spec. Ask user for confirmation before advancing phases.
- Spec-code traceability: Every code change traces to a spec item (TASK-ID + TP-ID); every spec item has corresponding code and tests.
- Phase status: At each phase end, summarize completion and suggest next entry point.
- Context management: Keep each spec file under ~300 lines. In Phase 3, feed only the relevant
spec_xxx.md+ relateddesign.mdsections — not all spec files at once. For large projects, start each new session with a brief context summary of completed phases.
Spec Quality Checklist
Before leaving Phase 2, verify specs meet "good enough" standard:
- Every interface has explicit input/output types
- Every business rule has at least one corresponding test point
- Specs describe what, not how (no implementation details)
- Each spec file is self-contained enough to drive code generation independently
- Edge cases and error scenarios are explicitly listed, not implied
Templates
For spec file templates and example outputs, see templates.md.
