Mod Logo

Specing

Learn to write specifications that agents can reliably execute

When AI writes code, specifications become your source code. ModSpec is a structured specification language that pairs human creativity with agent design and execution - readable by humans, parseable by machines, and executable by AI.

Contents

  1. What is ModSpec?
  2. Spec Structure
  3. Requirement Types
  4. ModSpec Language Reference

What is ModSpec?

ModSpec is a specification programming language for AI agents. Instead of scattered documentation, you get structured requirements, architecture, behaviors, and tests that agents can reliably execute.

AI agents fail when they have ambiguous requirements, missing context, poor architecture guidance, or incomplete edge case handling. ModSpec's primitives directly solve these problems by giving agents exactly what they need to generate reliable code.

Spec Structure

Every ModSpec file starts with framing sections that provide context before diving into technical requirements.

Abstract & Motivation

Frame the problem and solution before specifying technical details:

# User Authentication System

## Abstract
Secure user authentication system with email/password login, session management, 
and password reset functionality. Supports 10,000+ concurrent users with 
enterprise security standards.

## Motivation

### Problem
Our application currently has no user authentication, blocking us from:
- Launching multi-user features
- Personalizing user experiences  
- Protecting sensitive user data
- Meeting enterprise security requirements

### Business Impact
- **Revenue**: Blocking $50K MRR from enterprise customers requiring auth
- **Growth**: Cannot launch social features that drive 40% user retention
- **Risk**: Regulatory compliance issues without proper user data protection

### Success Criteria
- Support 10,000 concurrent authenticated users
- 99.9% authentication service uptime
- Enterprise-grade security compliance
- <500ms login response time (p95)

Scope Definition

Clearly define what's included and excluded:

## Scope

### In Scope
- Email/password registration and login
- Session management with secure tokens
- Password reset via email verification
- Account email verification
- Basic user profile management

### Out of Scope
- OAuth/SSO integration (future iteration)
- Multi-factor authentication (future iteration)  
- User roles and permissions (separate spec)
- Account deletion/GDPR compliance (separate spec)

### Dependencies
- Email service integration (SendGrid)
- Database schema updates (User and Session tables)
- Frontend authentication UI components

Requirement Types

ModSpec organizes requirements into four core types that AI agents need to generate reliable code. Each type has a specific format and serves a distinct purpose.

Architecture Requirements (ARCH-*)

Define system structure, component relationships, and technical constraints.

### ARCH-AUTH-1: Authentication Service Layer
**Pattern**: Clean Architecture with service separation
**Components**:
- AuthController (API layer)
- AuthService (business logic)
- UserRepository (data layer)
- SessionManager (state management)

**Dependencies**:
- Database connection pool
- Email service integration
- Redis for session storage

**Constraints**:
- Controllers MUST NOT contain business logic
- Services MUST be stateless
- Repositories MUST use prepared statements

Behavior Requirements (BEH-*)

Specify what the system does from a user perspective.

### BEH-AUTH-1: User Registration Flow
**Trigger**: User submits registration form
**Normal Flow**:
1. Validate email format and uniqueness
2. Hash password with bcrypt
3. Create user record in database
4. Send verification email
5. Return success response

**Error Flows**:
- Invalid email → Show format error
- Duplicate email → Suggest login instead
- Email service down → Queue for retry, show success

**Success Criteria**:
- Registration completes within 2 seconds
- Verification email delivered within 30 seconds

Data Requirements (DATA-*)

Define data structures, validation rules, and storage constraints.

### DATA-USER-1: User Account Model
```typescript
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
  created_at: Date;
  last_login: Date | null;
}

Validation Rules:

  • Email MUST match RFC 5322 format
  • Password MUST include: 8+ chars, uppercase, number, special char
  • Email MUST be stored in lowercase for case-insensitive lookups

Storage:

  • Primary key indexed automatically
  • Unique constraint on email field
  • Index on email for fast lookups

### Test Requirements (TEST-*)

Specify how to verify correctness and handle edge cases.

```markdown
### TEST-AUTH-1: Registration Endpoint Tests
**Unit Tests**:
- Valid registration → Returns 201 with user_id
- Duplicate email → Returns 409 with error message
- Invalid email format → Returns 400 with validation error
- Weak password → Returns 422 with strength requirements

**Integration Tests**:
- End-to-end registration flow with email verification
- Rate limiting enforcement (6th attempt returns 429)
- Database rollback on email service failure

**Performance Tests**:
- 1000 concurrent registrations complete within SLA
- Password hashing latency under 100ms (p95)

ModSpec Language Reference

Hierarchical IDs

Every element is uniquely addressable:

  • SPEC-AUTH-001 → Top-level specification
  • SPEC-AUTH-001/ARCH-AUTH-1 → Architecture requirement
  • SPEC-AUTH-001/BEH-AUTH-1 → Behavior requirement
  • SPEC-AUTH-001/DATA-USER-1 → Data requirement
  • SPEC-AUTH-001/TEST-AUTH-1 → Test requirement

Formal Keywords

Based on RFC 2119 for precise requirement specification:

  • MUST: Mandatory requirement (implementation required)
  • MUST NOT: Prohibited behavior (implementation forbidden)
  • SHOULD: Recommended but not mandatory
  • SHOULD NOT: Not recommended but not forbidden
  • MAY: Optional behavior
  • SHALL: Same as MUST (legal/contractual contexts)

Writing for Complete Traceability

To achieve 100% code-to-spec traceability, requirements must be granular enough that every implementation decision has a clear specification backing.

Too High-Level (leaves implementation gaps):

### BEH-AUTH-1: User Registration
Users can register with email and password

Appropriately Granular (every code decision specified):

### 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+ characters 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
- BEH-AUTH-1.8: Generate email verification token (UUID v4)
- BEH-AUTH-1.9: Queue verification email for delivery
- BEH-AUTH-1.10: Return 201 with user_id (do not wait for email)

**Error Handling**:
- BEH-AUTH-1.11: Invalid email format → 400 with specific field error
- BEH-AUTH-1.12: Duplicate email → 409 with suggestion to login
- BEH-AUTH-1.13: Weak password → 422 with strength requirements
- BEH-AUTH-1.14: Database error → 500 with request ID for debugging

The Traceability Test: Can you read any line of implementation code and immediately identify which requirement it fulfills? If not, add more specific requirements.

Example traceable implementation:

// @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 User.create({
  id: userId,
  email: normalizedEmail,
  password_hash: passwordHash,
  email_verified: false
});

Next Steps

Once you've mastered writing ModSpec files, learn how to:

  1. Execute specifications — How coding agents implement your specs with Mod's tooling
  2. Trace implementation — Understand bidirectional traceability from requirements to code
  3. Review agent code — Review agent-generated code with full spec context

ModSpec gives you a true specification programming language - write once in natural language, execute everywhere with AI agents.