Specification to Implementation Guide

This document provides a framework for converting technical specifications into actionable implementation prompts for AI assistants like GitHub Copilot.

---

Contents

1. Overview - When and why to use this approach 2. Specification Clarification Cycle - Iterative ambiguity resolution 3. Specification Restructuring - Converting to detailed specs 4. Specification Analysis - Breaking down specifications 5. TODO Extraction - Creating actionable tasks 6. Prompt Structure - Writing effective prompts 7. Specification Best Practices - Writing AI-friendly specs 8. Example: Build System - Applying to workspace_build.md

---

Overview

When to Use This Approach

Use this specification-to-implementation workflow when:

  • Implementing a complex system described in specification documents
  • The specification is too large for a single implementation session
  • Multiple components need to be implemented incrementally
  • You want traceable, testable implementation steps

Benefits

BenefitDescription
Incremental progressEach TODO is independently verifiable
Reduced complexitySmall, focused tasks are easier to implement correctly
Clear boundariesEach task has defined inputs and outputs
Resumable workCan pause and resume across sessions
Quality gatesNatural checkpoints for testing and review

Complete Workflow

┌─────────────────────────────────────────────────────────────────────────────┐
│                    SPECIFICATION TO IMPLEMENTATION WORKFLOW                 │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│  1. Original    │     │  2. Clarify     │     │  3. Detailed    │
│  Specification  │ ──► │  Ambiguities    │ ──► │  Specification  │
│  (user doc)     │     │  (iterate)      │     │  (AI-friendly)  │
└─────────────────┘     └─────────────────┘     └─────────────────┘
                               │                        │
                               ▼                        ▼
                        ┌─────────────────┐     ┌─────────────────┐
                        │ Clarification   │     │  4. Clarify     │
                        │ File            │     │  Detailed Spec  │
                        │ (user answers)  │     │  (iterate)      │
                        └─────────────────┘     └─────────────────┘
                                                        │
                                                        ▼
                        ┌─────────────────┐     ┌─────────────────┐
                        │  6. Implement   │     │  5. Extract     │
                        │  TODOs          │ ◄── │  TODOs          │
                        │                 │     │                 │
                        └─────────────────┘     └─────────────────┘

---

Specification Clarification Cycle

Before implementation can begin, specifications must be clear and unambiguous. This is an iterative process that applies to both original specifications and generated detailed specifications.

The Clarification Process

┌─────────────────────────────────────────────────────────────────────────────┐
│                      CLARIFICATION CYCLE                                    │
└─────────────────────────────────────────────────────────────────────────────┘

     ┌──────────────────────────────────────────────────────────────┐
     │                                                              │
     ▼                                                              │
┌─────────────────┐                                                 │
│ Analyze         │                                                 │
│ Specification   │                                                 │
└─────────────────┘                                                 │
     │                                                              │
     ▼                                                              │
┌─────────────────┐     No      ┌─────────────────┐                │
│ Ambiguities     │ ──────────► │ Proceed to      │                │
│ Found?          │             │ Next Phase      │                │
└─────────────────┘             └─────────────────┘                │
     │ Yes                                                          │
     ▼                                                              │
┌─────────────────┐                                                 │
│ Generate        │                                                 │
│ Clarification   │                                                 │
│ File            │                                                 │
└─────────────────┘                                                 │
     │                                                              │
     ▼                                                              │
┌─────────────────┐                                                 │
│ PAUSE           │                                                 │
│ User provides   │                                                 │
│ answers         │                                                 │
└─────────────────┘                                                 │
     │                                                              │
     ▼                                                              │
┌─────────────────┐                                                 │
│ Update          │ ────────────────────────────────────────────────┘
│ Specification   │
│ with answers    │
└─────────────────┘

Step 1: Analyze Specification

Copilot reads the specification looking for:

Issue TypeExampleAction
Undefined behavior "Handle errors appropriately" Ask what "appropriately" means
Missing types"Process the data"Ask for explicit type definitions
Implicit ordering"Run all steps"Ask for explicit sequence
Conflicting rulesA says X, B implies YAsk which takes precedence
Missing defaults"Optional field X"Ask for default value
Scope unclear"Support nesting"Ask for depth limit

Step 2: Generate Clarification File

When ambiguities are found, create a clarification file:

File naming: {spec_name}_clarifications.md

See User Clarification Guidelines for the complete template.

Step 3: User Provides Answers

The process pauses until the user:

1. Reviews the clarification file 2. Provides answers to questions 3. Confirms or overrides Copilot's decisions 4. Saves the file

Step 4: Update Specification

After receiving answers:

1. Incorporate answers into the specification 2. Mark resolved questions in clarification file 3. Re-analyze for any new ambiguities introduced 4. Repeat cycle if needed

When to Apply Clarification

PhaseDocumentClarification Needed?
Phase 1Original specificationYes - before restructuring
Phase 2Detailed specificationYes - after generation
Phase 3Extracted TODOsUsually no - specs should be clear
Phase 4ImplementationRarely - only if new issues arise

Clarification File Requirement

Important: When clarification is needed (Phases 1 and 2), a clarification file MUST be created following the User Clarification Guidelines. This ensures:

  • All questions are documented in a single, reviewable file
  • User answers are preserved for reference
  • Decisions can be traced back to user input
  • The process is consistent and auditable

Even if only a few minor ambiguities are found during specification review, create a clarification file rather than asking questions inline. This maintains workflow consistency and provides a complete record of decisions.

---

Specification Restructuring

After the original specification has been clarified, restructure it into a detailed, AI-friendly specification following specification_guide.md.

Why Restructure?

Original SpecDetailed Spec
Written for humansOptimized for AI implementation
May use proseUses explicit types and schemas
Implicit knowledgeAll context explicit
Overview-levelImplementation-level detail
May skip edge casesDocuments all edge cases

Restructuring Process

┌─────────────────────────────────────────────────────────────────────────────┐
│                      RESTRUCTURING PROCESS                                  │
└─────────────────────────────────────────────────────────────────────────────┘

Input: Clarified original specification

Step 1: Extract data structures
        ──► Create explicit type definitions with fields

Step 2: Document processing flow
        ──► Number all steps with input/output

Step 3: Add error handling
        ──► List all error conditions and responses

Step 4: Create examples
        ──► Minimal, complete, invalid, edge cases

Step 5: Define test scenarios
        ──► Verification criteria for each feature

Output: Detailed specification ready for TODO extraction

Restructuring Prompt Template

I want to restructure the specification in {original_spec.md} into a detailed,
AI-implementable specification.

## Source Document
{original_spec.md} - already clarified

## Reference
Follow specification_guide.md for structure and standards.

## Tasks
1. Extract all data structures with explicit types
2. Document processing flow with numbered steps
3. Add complete error handling specification
4. Create test data for all scenarios
5. Document edge cases

## Output
Create {component}_detailed_spec.md with the restructured content.

## Clarification
If you find new ambiguities during restructuring, create a clarification file
and pause for user input.

Detailed Spec Structure

The restructured specification should follow this structure:

# {Component} Detailed Specification

## Overview
{Brief description - 2-3 sentences}

## Terminology
{All domain terms defined}

## Data Structures
{Explicit types with all fields}

## Processing Flow
{Numbered steps with I/O}

## Error Handling
{All error conditions and responses}

## Examples
{Minimal, complete, invalid inputs}

## Edge Cases
{Boundary conditions}

## Test Scenarios
{Verification data}

---

Specification Analysis

Step 1: Identify Components

Read through the specification and identify:

1. Data structures - YAML schemas, class definitions, configuration formats 2. Processing phases - Sequential operations (parse → transform → output) 3. Input/Output boundaries - File formats, APIs, command-line interfaces 4. Dependencies - What must exist before something else can work

Step 2: Create Component Hierarchy

┌─────────────────────────────────────────────────────────────────────────────┐
│                         COMPONENT HIERARCHY                                 │
└─────────────────────────────────────────────────────────────────────────────┘

Level 1: Foundation
  └── Data models, basic types, shared utilities

Level 2: Core Processing
  └── Parsers, transformers, validators

Level 3: Integration
  └── Workflows combining multiple components

Level 4: Interface
  └── CLI, API, configuration loading

Step 3: Map Dependencies

For each component, identify:

  • What it reads (inputs)
  • What it produces (outputs)
  • What other components it depends on
  • What components depend on it

---

TODO Extraction

Principles

1. Single responsibility - Each TODO does one thing 2. Testable outcome - Each TODO has verifiable results 3. Limited scope - 15-30 minutes of implementation time 4. Clear boundaries - Defined inputs and outputs 5. Sequential ordering - Dependencies are respected

TODO Categories

CategoryDescriptionExample
ModelCreate data structures"Create YamlConfig class with fields..."
ParserRead and parse input"Parse the config file into WorkspaceConfig"
TransformerConvert between formats"Convert WorkspaceConfig to MasterFile"
ValidatorCheck correctness"Validate all project paths exist"
GeneratorProduce output"Write the resolved report to out/"
IntegrationConnect components"Wire parser output to transformer input"
TestVerify behavior"Create unit tests for YamlConfig parsing"

TODO Identification: Text IDs vs Numeric IDs

TODOs can be identified using either numeric IDs or text-based IDs. Text-based IDs are recommended for large documents where TODOs may be added, removed, or reordered.

Numeric IDs

TODO 1: Create WorkspaceConfig model
TODO 2: Parse workspace YAML
TODO 3: Validate configuration

Pros: Simple, familiar Cons: Renumbering required when TODOs are added/removed, references become stale

Text-Based IDs (Recommended)

### foundation.workspace-config: Create WorkspaceConfig model
### parsing.workspace: Parse workspace YAML
### parsing.validation: Validate configuration

Naming Convention: <phase>.<component>[.<subcomponent>]

Phase TypePrefixExample
Foundation/Models foundation. foundation.workspace-config
Parsingparsing.parsing.workspace
Generationgeneration.generation.master
Executionexecution.execution.runner
CLIcli.cli.help
Integrationintegration.integration.discovery
Testingtesting.testing.unit
Validationvalidation.validation.errors

Pros:

  • No renumbering when TODOs are added/removed
  • Dependencies are semantic (integration.context instead of TODO 24)
  • IDs remain stable across document versions
  • Self-documenting (ID indicates purpose)

Cons: Slightly more verbose

When to Use Text IDs:

  • Large TODO documents (20+ TODOs)
  • Documents that will evolve over time
  • Multi-phase implementations
  • Collaborative projects where TODOs may be added by multiple people

TODO Template (Numeric)

TODO {number}: {action verb} {component}

Context:
- Input: {what this TODO receives}
- Output: {what this TODO produces}
- Dependencies: {what must be complete first}

Acceptance criteria:
- {specific, testable criterion 1}
- {specific, testable criterion 2}
- {specific, testable criterion 3}

Reference: {section of spec document}

TODO Template (Text-Based)

### {phase}.{component}: {action verb} {component name}

**Reference:** `specification.md` Section X.Y

Context:

- Input: {what this TODO receives}
- Output: {what this TODO produces}
- Dependencies: `{phase}.{other-component}`

Implementation Notes:

- {key implementation detail 1}
- {key implementation detail 2}

Acceptance criteria:

- [ ] {specific, testable criterion 1}
- [ ] {specific, testable criterion 2}
- [ ] {specific, testable criterion 3}

**Status:** ⏳ Not Started / 🔄 In Progress / ✅ Complete

Extraction Process

1. For each specification section: - Identify the discrete operations described - Break into smallest testable units - Assign TODO numbers respecting dependencies

2. Order TODOs by dependency: - Foundation components first - Processing components next - Integration components last

3. Group related TODOs: - Phase 1: Data models - Phase 2: Parsing - Phase 3: Processing - Phase 4: Output - Phase 5: Integration tests

---

Prompt Structure

Implementation Prompt Template

I want to implement {component name} from the {specification document}.

## Context
{Brief description of what this implements and its role in the system}

## Reference Documents
- {spec_document_1.md} - sections {X, Y, Z}
- {spec_document_2.md} - section {A}

## Current State
- Completed: {list of completed components}
- In progress: {current component}
- Remaining: {list of remaining components}

## TODO List
{Extracted TODOs for this implementation session}

## Constraints
- {Language/framework requirements}
- {Coding style guidelines}
- {Error handling requirements}
- {Testing requirements}

## Expected Outcome
- {Specific deliverables}
- {Test coverage expectations}
- {Documentation requirements}

Session Management

For large implementations spanning multiple sessions:

## Session {N} Summary

Completed:
- TODO 1: {description} ✓
- TODO 2: {description} ✓

In Progress:
- TODO 3: {description} - {current state}

Blocked:
- TODO 5: {description} - blocked by {reason}

Next Session:
- Continue TODO 3
- Start TODO 4

---

Specification Best Practices

Writing AI-Friendly Specifications

PracticeDescriptionExample
Explicit types Define all data types clearly "release: String (semver format)"
Complete examplesShow full, working examplesInclude complete YAML samples
Edge casesDocument boundary conditions"If no config exists, use defaults"
Error conditions Specify what should fail "Invalid YAML throws ParseException"
Processing order State sequence explicitly "1. Parse, 2. Validate, 3. Transform"

Structure Recommendations

1. Use consistent headings - AI can navigate by section names 2. Include schemas - YAML/JSON schemas are directly implementable 3. Provide examples - Real examples are better than abstract descriptions 4. Define terminology - Create a glossary for domain terms 5. Separate concerns - One document per major component

Specification Anti-Patterns

Anti-PatternProblemSolution
Implicit dependenciesAI can't infer orderState dependencies explicitly
Vague types "data" is not implementable Use specific types: "Map<String, dynamic>"
Missing examples Abstract descriptions are ambiguous Include concrete examples
Circular references Creates implementation deadlock Break cycles with interfaces
Overloaded termsSame word, different meaningsDefine terms in glossary

Testability Checklist

For each specification section, verify:

  • [ ] Can be implemented independently?
  • [ ] Has clear input/output?
  • [ ] Can be tested in isolation?
  • [ ] Has example data for tests?
  • [ ] Defines error conditions?

---

Example: Build System

Applying this framework to the Tom Build System specifications.

Source Documents

DocumentPurpose
workspace_build.md Build process phases and execution flow
workspace_metadata.md YAML file formats and configuration

Component Analysis

┌─────────────────────────────────────────────────────────────────────────────┐
│                      BUILD SYSTEM COMPONENTS                                │
└─────────────────────────────────────────────────────────────────────────────┘

Phase 1: Discovery
├── FileScanner - Find workspace files
├── ProjectDetector - Identify project types
└── ConfigLoader - Load the workspace config file

Phase 2: Generation
├── ModeResolver - Resolve mode blocks
├── ConfigMerger - Merge configuration hierarchy
├── PlaceholderProcessor - Replace ${...} placeholders
└── ReportGenerator - Write the per-action reports

Phase 3: Execution
├── ActionResolver - Determine action to run
├── TomplateProcessor - Convert .tomplate files
├── CommandExecutor - Run action commands
└── OutputHandler - Handle command output

Extracted TODOs

Phase 1: Foundation (TODOs 1-10)

TODO 1: Create WorkspaceConfig model
- Fields: name, binaries, workspace-modes, groups, project-info
- Reference: workspace_metadata.md#tom_workspaceyaml

TODO 2: Create ProjectConfig model
- Fields: name, type, path, features, actions, parts
- Reference: workspace_metadata.md#tom_projectyaml

TODO 3: Create MasterFile model
- Fields: scanTimestamp, action, workspace-modes.current, projects
- Reference: workspace_metadata.md#master-file-structure

TODO 4: Create ModeDefinition model
- Fields: name, description, implies, mode-types
- Reference: workspace_metadata.md#mode-system

TODO 5: Create GroupDefinition model
- Fields: description, projects, overrides
- Reference: workspace_metadata.md#groups

Phase 2: Parsing (TODOs 11-20)

TODO 11: Implement YAML parser for the workspace config file
- Input: File path
- Output: WorkspaceConfig
- Handle: imports, mode definitions, groups

TODO 12: Implement YAML parser for the project config file
- Input: File path + mode context
- Output: ProjectConfig
- Handle: mode blocks, imports

TODO 13: Implement tomplate file detection
- Patterns: <name>.<ext>.tomplate, <name>.tomplate.<ext>
- Input: Base filename
- Output: Tomplate path or null

Phase 3: Processing (TODOs 21-35)

TODO 21: Implement mode block resolver
- Input: YAML content + active modes
- Output: Resolved YAML content
- Reference: workspace_metadata.md#mode-block-syntax

TODO 22: Implement configuration merger
- Merge order: defaults → workspace → group → project → params
- Reference: workspace_metadata.md#configuration-resolution

TODO 23: Implement ${...} placeholder processor
- Input: String with placeholders
- Output: Resolved string
- Reference: workspace_metadata.md#value-references

Phase 4: Generation (TODOs 36-45)

TODO 36: Implement the resolved-report generator
- Input: Resolved WorkspaceConfig + projects
- Output: `out/resolved.yaml`
- Include: Generic file with default modes

TODO 37: Implement the per-action report generator
- Input: Action name + resolved config
- Output: `out/resolved_<action>.yaml`

Phase 5: Execution (TODOs 46-55)

TODO 46: Implement tomplate processor
- Input: Tomplate file + mode context
- Output: Generated target file
- Reference: workspace_build.md#tomplate-processing-at-runtime

TODO 47: Implement command executor
- Input: Command list + working directory
- Output: Execution results
- Handle: Background processes, output capture

Implementation Prompt Example

I want to implement the Mode Block Resolver from the Tom Build System.

## Context
The mode block resolver processes YAML content containing conditional blocks
(@@@ syntax) and returns content with only the matching blocks included.

## Reference Documents
- workspace_metadata.md - section "Mode Block Syntax"
- workspace_build.md - section "Phase 2: Generation"

## Current State
- Completed: WorkspaceConfig model, ProjectConfig model
- In progress: Mode block resolver
- Remaining: Config merger, placeholder processor

## TODO List
TODO 21: Implement mode block resolver
- Parse @@@ markers and block content
- Match against active mode list
- Handle @@@mode, @@@mode.<type>, @@@<type>: variants
- Handle @@@mode default fallback
- Handle @@@endmode termination
- Preserve content outside mode blocks
- Handle escaped \@@@ markers

## Constraints
- Language: Dart
- Follow coding_guidelines.md
- Handle malformed input gracefully
- Support nested mode blocks

## Expected Outcome
- ModeBlockResolver class with resolve(String content, List<String> activeModes)
- Unit tests for all three syntax variants
- Edge case tests for malformed input

---

Secondary TODO Generation

After completing initial implementation, perform a secondary TODO generation pass to catch missed requirements and placeholder implementations.

When to Perform Secondary TODO Generation

  • After marking all initial TODOs complete
  • Before declaring implementation "done"
  • After significant code reviews

Steps

1. Scan codebase for TODOs (see Codebase Scanning section) 2. Review specification for missed requirements 3. Add new TODOs to document as a new phase 4. Update status - document is not complete until secondary pass done

New Phase Creation

Add new phases for discovered work:

## Phase N: Secondary Findings

### TODO X: [Discovered from codebase scan]

**Location:** `file.dart:123`

Context:
- Current: Placeholder implementation
- Required: Full implementation

**Discovered via:** Codebase TODO scan

---

Codebase Scanning

Use these techniques to find incomplete implementations after the initial pass.

Scan for TODO Comments

Run this command to find TODOs:

grep -rn "// TODO:\|//TODO" <source_dir>

Scan for Placeholder Indicators

Search for these keywords that often indicate incomplete implementations:

grep -rn "placeholder\|skeleton\|stub\|dummy\|implement\|later\|integration" <source_dir>

Scan for Empty/Incomplete Implementations

Look for:

  • Empty method bodies: { }
  • Methods returning only default values
  • Methods with just throw UnimplementedError()
  • Methods with just return null; or return false;

Recording Findings

Add a table of findings to the TODO document:

### Codebase TODOs Found

| File | Line | TODO Description |
| ---- | ---- | ---------------- |
| `file.dart` | 123 | Integrate with actual XYZ |
| `other.dart` | 456 | Implement validation logic |

---

Verification Checkboxes

Verification checkboxes in specifications track which requirements are implemented and where the implementation code lives.

Purpose

1. Track which requirements are implemented 2. Document where implementation code lives 3. Enable easy verification during review 4. Prevent requirements from being missed

Format

Add after each implementable paragraph or section:

**Implementation Verification:**
- [ ] <requirement description>
- [ ] Code location: `<file>:<function_or_class>`
- [ ] Tests: `<test_file>`

When to Add

Add verification checkboxes during specification creation for:

  • Algorithm descriptions
  • Data structure specifications
  • Behavior requirements
  • Error handling requirements
  • Edge case descriptions

Example

### 4.3.2 Merge Algorithm

Values are merged using deep merge semantics where...

**Implementation Verification:**
- [ ] Deep merge implemented with map/list handling
- [ ] Code location: `config/config_merger.dart:deepMerge()`
- [ ] Tests: `test/config_merger_test.dart:group('deepMerge')`

Updating Checkboxes

After implementation, update the checkboxes in the specification:

**Implementation Verification:**
- [x] Deep merge implemented with map/list handling
- [x] Code location: `config/config_merger.dart:deepMerge()`
- [x] Tests: `test/config_merger_test.dart:group('deepMerge')`

---

Quick Reference

TODO Sizing Guide

SizeTimeScope
XS5-10 minSingle method or class
S10-20 minSmall class with tests
M20-30 minComponent with integration
L30-60 minMultiple related components

Target size: S or M - Large enough to be meaningful, small enough to complete.

Specification Checklist

Before extracting TODOs, verify the specification has:

  • [ ] Clear data structure definitions
  • [ ] Complete processing flow description
  • [ ] Input/output examples
  • [ ] Error handling requirements
  • [ ] Boundary conditions documented
  • [ ] Dependencies stated explicitly

Session Workflow

1. Review specification section 2. Extract 5-10 TODOs for session 3. Create implementation prompt 4. Implement each TODO 5. Test each TODO 6. Document completion status 7. Prepare for next session