Mod Logo

Execute

How coding agents implement specifications reliably with Mod's tooling

Executing Specifications with Coding Agents

Specifications are just documents until they become running code. This guide shows how Mod's tooling enables coding agents to execute your ModSpec files reliably, transforming requirements into working implementations with complete traceability.

Contents

  1. From Specification to Tasks
  2. Agent Execution Model
  3. Complete Traceability Implementation
  4. Execution Workflows
  5. Quality Assurance
  6. Best Practices

From Specification to Tasks

Automatic Task Generation

When you save a ModSpec file, Mod's parsing engine automatically extracts executable tasks from each requirement type:

Original ModSpec Requirements:

### ARCH-AUTH-1: Authentication Service Layer
**Pattern**: Clean Architecture with service separation
**Components**: AuthController, AuthService, UserRepository, SessionManager

### BEH-AUTH-1: User Registration Flow
**Input Validation**:
- BEH-AUTH-1.1: Email MUST match RFC 5322 format
- BEH-AUTH-1.2: Email MUST be unique in system
- BEH-AUTH-1.3: Password MUST be 8+ chars with uppercase, lowercase, number, special char

**Processing Steps**:
- BEH-AUTH-1.4: Convert email to lowercase before storage
- BEH-AUTH-1.5: Hash password with bcrypt cost=12
- BEH-AUTH-1.6: Generate UUID v4 for user ID
- BEH-AUTH-1.7: Create user record with email_verified=false

### DATA-USER-1: User Account Model
interface User {
  id: string;           // UUID v4 primary key
  email: string;        // RFC 5322 format, unique, lowercase
  password_hash: string; // bcrypt cost=12, never exposed
  email_verified: boolean; // default false
}

Mod automatically generates these implementation tasks:

  1. Database Schema Task (ARCH-AUTH-1 + DATA-USER-1)

    • Create users table with UUID primary key
    • Add unique constraint on email field
    • Set up bcrypt password hash storage
    • Add email_verified boolean column
  2. Service Layer Task (ARCH-AUTH-1)

    • Create AuthController for API layer
    • Implement AuthService for business logic
    • Build UserRepository for data access
    • Set up SessionManager for state
  3. Registration Logic Task (BEH-AUTH-1)

    • Implement each numbered sub-requirement (BEH-AUTH-1.1 through BEH-AUTH-1.7)
    • Ensure complete traceability from spec to code
    • Handle all validation and processing steps
  4. API Endpoint Task (Integration)

    • Wire AuthController to routes
    • Integrate with validation middleware
    • Connect to business logic services

Task Prioritization

Mod analyzes requirement dependencies to suggest optimal execution order:

Phase 1: Architecture Foundation

  • ARCH-* requirements (service structure)
  • DATA-* requirements (data models)

Phase 2: Behavior Implementation

  • BEH-* requirements (business logic)
  • Integration between components

Phase 3: Validation & Testing

  • TEST-* requirements (test cases)
  • End-to-end validation

Dependency Resolution

TASK-1: Implement DATA-USER-1 (User model)
├── Required by: TASK-3 (BEH-AUTH-1 registration logic)
├── Required by: TASK-2 (ARCH-AUTH-1 UserRepository)
└── Files: src/models/User.ts

TASK-2: Implement ARCH-AUTH-1 (Service layer)
├── Depends on: TASK-1 (User model)
├── Required by: TASK-3 (Registration logic)
└── Files: src/services/AuthService.ts, src/controllers/AuthController.ts

TASK-3: Implement BEH-AUTH-1 (Registration flow)
├── Depends on: TASK-1 (User model), TASK-2 (Service layer)
├── Sub-tasks: BEH-AUTH-1.1 through BEH-AUTH-1.7
└── Files: src/api/auth/signup.ts

Agent Execution Model

Context-Aware Agents

Agents executing ModSpec have full context about each requirement:

Complete Requirement Context:

// Context automatically provided to agent for BEH-AUTH-1:
{
  "requirement": {
    "id": "BEH-AUTH-1",
    "title": "User Registration Flow",
    "sub_requirements": [
      {
        "id": "BEH-AUTH-1.1",
        "description": "Email MUST match RFC 5322 format",
        "type": "validation",
        "implementation_hint": "Use email validation library"
      },
      {
        "id": "BEH-AUTH-1.4", 
        "description": "Convert email to lowercase before storage",
        "type": "processing",
        "implementation_hint": "Call .toLowerCase() before database save"
      }
      // ... all other sub-requirements
    ]
  },
  "architecture": {
    "pattern": "Clean Architecture",
    "components": ["AuthController", "AuthService", "UserRepository"],
    "constraints": ["Controllers MUST NOT contain business logic"]
  },
  "data_models": {
    "User": {
      "id": "string (UUID v4)",
      "email": "string (RFC 5322, unique, lowercase)",
      "password_hash": "string (bcrypt cost=12)"
    }
  },
  "codebase": {
    "existing_patterns": {
      "validation": "joi schemas in utils/validation.ts",
      "database": "TypeORM with User entity", 
      "error_handling": "try/catch with specific HTTP codes"
    }
  }
}

Granular Implementation Tracking

Agents implement each sub-requirement individually with complete traceability:

// @spec ARCH-AUTH-1: Clean Architecture service separation
export class AuthService {
  
  // @spec BEH-AUTH-1: User Registration Flow implementation
  async registerUser(email: string, password: string): Promise<RegisterResult> {
    try {
      // @spec BEH-AUTH-1.1: Email MUST match RFC 5322 format
      if (!this.validateEmailFormat(email)) {
        throw new ValidationError('Invalid email format', 'email');
      }
      
      // @spec BEH-AUTH-1.2: Email MUST be unique in system
      const existingUser = await this.userRepository.findByEmail(email);
      if (existingUser) {
        throw new ConflictError('Email already registered');
      }
      
      // @spec BEH-AUTH-1.3: Password MUST be 8+ chars with complexity
      if (!this.validatePasswordStrength(password)) {
        throw new ValidationError('Password does not meet requirements', 'password');
      }
      
      // @spec BEH-AUTH-1.4: Convert email to lowercase before storage
      const normalizedEmail = email.toLowerCase();
      
      // @spec BEH-AUTH-1.5: Hash password with bcrypt cost=12
      const passwordHash = await bcrypt.hash(password, 12);
      
      // @spec BEH-AUTH-1.6: Generate UUID v4 for user ID
      const userId = uuidv4();
      
      // @spec BEH-AUTH-1.7: Create user record with email_verified=false
      const user = await this.userRepository.create({
        id: userId,
        email: normalizedEmail,
        password_hash: passwordHash,
        email_verified: false
      });
      
      return {
        user_id: user.id,
        message: 'Registration successful'
      };
      
    } catch (error) {
      // @spec BEH-AUTH-1 error handling
      throw this.handleRegistrationError(error);
    }
  }
}

Complete Traceability Implementation

Sub-Requirement Execution

Each numbered sub-requirement becomes a discrete implementation step:

Spec → Code Mapping:

## Specification Side
BEH-AUTH-1.1: Email MUST match RFC 5322 format
BEH-AUTH-1.2: Email MUST be unique in system  
BEH-AUTH-1.3: Password MUST be 8+ chars with uppercase, lowercase, number, special char

Implementation Side:

// @spec BEH-AUTH-1.1: Email MUST match RFC 5322 format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
  return { error: 'Invalid email format', field: 'email' };
}

// @spec BEH-AUTH-1.2: Email MUST be unique in system
const existingUser = await User.findOne({ email: email.toLowerCase() });
if (existingUser) {
  return { error: 'Email already registered', field: 'email' };
}

// @spec BEH-AUTH-1.3: Password strength validation
const passwordRequirements = {
  minLength: 8,
  hasUppercase: /[A-Z]/.test(password),
  hasLowercase: /[a-z]/.test(password), 
  hasNumber: /\d/.test(password),
  hasSpecial: /[!@#$%^&*(),.?":{}|<>]/.test(password)
};

if (!Object.values(passwordRequirements).every(Boolean)) {
  return { error: 'Password does not meet complexity requirements', field: 'password' };
}

Traceability Validation

Agents automatically verify complete traceability:

// Automatic validation for BEH-AUTH-1:
const traceabilityCheck = {
  "BEH-AUTH-1.1": "✅ Email validation implemented at line 15",
  "BEH-AUTH-1.2": "✅ Uniqueness check implemented at line 20", 
  "BEH-AUTH-1.3": "✅ Password strength validation at line 25",
  "BEH-AUTH-1.4": "✅ Email normalization at line 35",
  "BEH-AUTH-1.5": "✅ Bcrypt hashing at line 38",
  "BEH-AUTH-1.6": "✅ UUID generation at line 41",
  "BEH-AUTH-1.7": "✅ User creation at line 44"
};

// Coverage: 7/7 sub-requirements implemented (100%)
// Status: ✅ Complete traceability achieved

Missing Implementation Detection

When agents miss sub-requirements, Mod automatically detects gaps:

// Incomplete implementation example:
// Missing: BEH-AUTH-1.3 (password strength validation)
// Missing: BEH-AUTH-1.6 (UUID generation)

const gapAnalysis = {
  implemented: ["BEH-AUTH-1.1", "BEH-AUTH-1.2", "BEH-AUTH-1.4", "BEH-AUTH-1.5", "BEH-AUTH-1.7"],
  missing: ["BEH-AUTH-1.3", "BEH-AUTH-1.6"],
  coverage: "71% (5/7 sub-requirements)",
  status: "❌ Incomplete - requires additional implementation"
};

// Auto-generated follow-up tasks:
// TASK-3a: Implement BEH-AUTH-1.3 password strength validation
// TASK-3b: Implement BEH-AUTH-1.6 UUID generation for user ID

Execution Workflows

Single Agent Workflow

Best for: Simple features with clear dependencies

  1. Requirement Analysis

    • Parse all ARCH-, BEH-, DATA-, TEST- requirements
    • Identify numbered sub-requirements
    • Build implementation plan
  2. Architecture Setup

    • Implement ARCH-* requirements first
    • Set up service layer structure
    • Create component interfaces
  3. Data Layer Implementation

    • Implement DATA-* requirements
    • Create models and schemas
    • Set up validation rules
  4. Behavior Implementation

    • Implement each BEH-* sub-requirement individually
    • Add @spec comments for every line
    • Validate traceability continuously
  5. Testing Implementation

    • Implement TEST-* requirements
    • Verify all sub-requirements are tested
    • Run complete validation

Multi-Agent Orchestration

Agent Specialization:

Parallel execution of SPEC-AUTH-001:

Agent-Architecture (ARCH-* specialist):
├── ✅ ARCH-AUTH-1: Service layer structure
├── ✅ Component separation and interfaces
└── ✅ Dependency injection setup

Agent-Data (DATA-* specialist):
├── ✅ DATA-USER-1: User model and validation
├── ✅ Database schema and migrations
└── ✅ Repository pattern implementation

Agent-Behavior (BEH-* specialist):
├── 🔄 BEH-AUTH-1.1: Email validation (in progress)
├── ⏳ BEH-AUTH-1.2: Uniqueness checking (waiting)
├── ⏳ BEH-AUTH-1.3-1.7: Processing steps (queued)
└── Dependencies: Agent-Data, Agent-Architecture

Agent-Testing (TEST-* specialist):
├── ⏳ TEST-AUTH-1: Unit tests (waiting for BEH-*)
├── ⏳ Integration tests for complete flow
└── ⏳ Performance and security testing

Human-Agent Collaboration

Review Points:

  • After architecture implementation (ARCH-* complete)
  • During behavior implementation (BEH-* sub-requirements)
  • Before testing phase (TEST-* requirements)
  • Final traceability verification

Quality Assurance

Automated Requirement Coverage

// Real-time coverage tracking for SPEC-AUTH-001:
const implementationStatus = {
  "ARCH-AUTH-1": {
    coverage: "100%",
    sub_requirements: {
      "service_separation": "✅ Implemented",
      "clean_architecture": "✅ Implemented", 
      "component_interfaces": "✅ Implemented"
    }
  },
  "BEH-AUTH-1": {
    coverage: "86%", 
    sub_requirements: {
      "BEH-AUTH-1.1": "✅ Email validation implemented",
      "BEH-AUTH-1.2": "✅ Uniqueness check implemented",
      "BEH-AUTH-1.3": "❌ Password validation missing",
      "BEH-AUTH-1.4": "✅ Email normalization implemented",
      "BEH-AUTH-1.5": "✅ Password hashing implemented",
      "BEH-AUTH-1.6": "✅ UUID generation implemented", 
      "BEH-AUTH-1.7": "✅ User creation implemented"
    }
  },
  "DATA-USER-1": {
    coverage: "100%",
    model_complete: "✅ All fields and constraints implemented"
  },
  "TEST-AUTH-1": {
    coverage: "0%", 
    status: "⏳ Waiting for BEH-AUTH-1 completion"
  }
};

// Overall: 6/7 sub-requirements complete (86%)
// Action required: Implement BEH-AUTH-1.3 password validation

Specification Compliance Checking

// Continuous validation during implementation:
const complianceCheck = {
  "email_validation": {
    requirement: "BEH-AUTH-1.1",
    implemented: true,
    code_location: "src/services/AuthService.ts:15",
    validation: "✅ RFC 5322 email regex implemented"
  },
  "password_hashing": {
    requirement: "BEH-AUTH-1.5", 
    implemented: true,
    code_location: "src/services/AuthService.ts:38",
    validation: "✅ bcrypt cost=12 confirmed"
  },
  "password_validation": {
    requirement: "BEH-AUTH-1.3",
    implemented: false, 
    validation: "❌ Missing complexity requirements check"
  }
};

Best Practices for Agent Execution

Writing Agent-Executable Requirements

Use Numbered Sub-Requirements:

✅ Good: Granular sub-requirements
### BEH-AUTH-1: User Registration Flow
- BEH-AUTH-1.1: Email MUST match RFC 5322 format
- BEH-AUTH-1.2: Email MUST be unique in system
- BEH-AUTH-1.3: Password MUST be 8+ chars with complexity

❌ Poor: High-level requirement  
### BEH-AUTH-1: User Registration
Users can register with email and password

Specify Exact Implementation Details:

✅ Good: Specific technical requirements
- BEH-AUTH-1.5: Hash password with bcrypt cost=12
- BEH-AUTH-1.6: Generate UUID v4 for user ID  
- BEH-AUTH-1.7: Create user record with email_verified=false

❌ Poor: Vague requirements
- Hash passwords securely
- Generate unique user IDs
- Create user accounts

Monitoring Complete Traceability

Real-Time Traceability Dashboard:

┌─────────────────────────────────────────────────────────┐
│ SPEC-AUTH-001 Implementation Traceability              │
├─────────────────────────────────────────────────────────│
│ Total Sub-Requirements: 23                              │
│ Implemented: 20 (87%)                                   │
│ Missing: 3 (13%)                                        │
│                                                         │
│ By Requirement Type:                                    │
│ ├── ARCH-AUTH-1: 3/3 sub-reqs (100%) ✅               │
│ ├── BEH-AUTH-1: 6/7 sub-reqs (86%) 🟡                 │
│ ├── DATA-USER-1: 4/4 sub-reqs (100%) ✅               │
│ └── TEST-AUTH-1: 7/9 sub-reqs (78%) 🟡                │
│                                                         │
│ Missing Implementation:                                 │
│ • BEH-AUTH-1.3: Password validation                    │
│ • TEST-AUTH-1.8: Load testing                          │
│ • TEST-AUTH-1.9: Security testing                      │
└─────────────────────────────────────────────────────────┘

Traceability Quality Metrics:

  • Coverage: Percentage of sub-requirements implemented
  • Accuracy: Percentage of @spec comments referencing valid requirements
  • Completeness: All requirement types (ARCH, BEH, DATA, TEST) covered
  • Granularity: Average lines of code per sub-requirement

With Mod's execution tooling, coding agents implement specifications with complete traceability, ensuring every line of code traces back to a specific numbered requirement. This creates reliable, maintainable implementations that perfectly match your specifications.