# OpenSpec Format Reference

This document describes the OpenSpec specification format that openlore generates.

## Directory Structure

```
openspec/
├── config.yaml                 # Project configuration
└── specs/                      # Specification files
    ├── overview/
    │   └── spec.md            # System overview
    ├── {domain}/
    │   └── spec.md            # Domain specification
    └── architecture/
        └── spec.md            # Architecture specification
```

## config.yaml

The project configuration file:

```yaml
# Workflow schema (default: spec-driven)
schema: spec-driven

# Project context injected into AI prompts
context: |
  Brief project description.

  Tech stack: Node.js, TypeScript, Express
  Architecture: Layered (routes → services → repositories)

# Optional: Custom rules per artifact type
rules:
  specs:
    - Include Given/When/Then scenarios
    - Reference source files in technical notes

# Auto-detected by openlore (added during generation)
openlore:
  generatedAt: "2025-01-30T12:00:00Z"
  domains:
    - user
    - order
    - auth
```

## Spec File Format

Each `spec.md` file follows this structure:

```markdown
# {Domain} Specification

> Generated by openlore on {date}
> Source files: {comma-separated list of files}

## Purpose

{2-3 sentences describing what this domain handles}

## Requirements

### Requirement: {RequirementName}

{Description using RFC 2119 keywords}

#### Scenario: {ScenarioName}
- **GIVEN** {precondition}
- **WHEN** {action}
- **THEN** {expected outcome}
- **AND** {additional assertion} (optional)

## Technical Notes

- **Implementation**: `{file paths}`
- **Dependencies**: {related domains/services}
```

## RFC 2119 Keywords

Requirements use these keywords to indicate strength:

| Keyword | Meaning |
|---------|---------|
| **SHALL** / **MUST** | Absolute requirement |
| **SHALL NOT** / **MUST NOT** | Absolute prohibition |
| **SHOULD** | Recommended |
| **SHOULD NOT** | Not recommended |
| **MAY** | Optional |

### Examples

```markdown
The system SHALL validate email format before creating users.
The system MUST NOT store passwords in plain text.
The system SHOULD log failed authentication attempts.
The system MAY cache user profiles for performance.
```

## Scenarios

Scenarios use the Given/When/Then format with exactly 4 hashtags (`####`):

```markdown
#### Scenario: ValidUserCreation
- **GIVEN** a registration request with valid email and password
- **WHEN** the user creation endpoint is called
- **THEN** a new user record is created
- **AND** a confirmation email is sent
```

### Scenario Guidelines

1. **GIVEN** — Preconditions and context
   - Initial state
   - Required data
   - User roles/permissions

2. **WHEN** — The action being tested
   - Single action per scenario
   - Clear trigger

3. **THEN** — Expected outcomes
   - Observable results
   - State changes
   - Side effects

4. **AND** — Additional assertions (optional)
   - Multiple outcomes
   - Secondary effects

## Domain Types

### Overview Spec (`overview/spec.md`)

System-wide overview:

```markdown
# System Overview

> Generated by openlore on 2025-01-30
> Source files: package.json, src/index.ts, src/app.ts

## Purpose

{Project name} is a {type of system} that {primary function}.

## Domains

| Domain | Description | Spec |
|--------|-------------|------|
| user | User management | [spec.md](../user/spec.md) |
| order | Order processing | [spec.md](../order/spec.md) |

## Requirements

### Requirement: SystemAvailability

The system SHALL be available for API requests during normal operation.

#### Scenario: HealthCheck
- **GIVEN** the system is running
- **WHEN** the health endpoint is called
- **THEN** a 200 response is returned

## Technical Notes

- **Type**: Node.js/TypeScript API
- **Framework**: Express.js
- **Database**: PostgreSQL
```

### Domain Spec (`{domain}/spec.md`)

Domain-specific specification:

```markdown
# User Specification

> Generated by openlore on 2025-01-30
> Source files: src/models/user.ts, src/services/user-service.ts

## Purpose

Manages user accounts, authentication credentials, and profile information.

## Entities

### User

| Property | Type | Description |
|----------|------|-------------|
| id | UUID | Unique identifier |
| email | string | User's email (unique) |
| passwordHash | string | Bcrypt-hashed password |
| createdAt | DateTime | Account creation time |

## Requirements

### Requirement: UserCreation

The system SHALL create new user accounts with validated email and hashed password.

#### Scenario: ValidUserCreation
- **GIVEN** a registration request with valid email "user@example.com"
- **WHEN** the user creation endpoint is called
- **THEN** a new user record is created with hashed password

### Requirement: EmailUniqueness

The system SHALL enforce unique email addresses across all users.

#### Scenario: DuplicateEmailRejected
- **GIVEN** an existing user with email "test@example.com"
- **WHEN** a new registration is attempted with the same email
- **THEN** the registration fails with error "Email already exists"

## Technical Notes

- **Implementation**: `src/models/user.ts`, `src/services/user-service.ts`
- **Dependencies**: auth, notification
```

### Architecture Spec (`architecture/spec.md`)

System architecture documentation:

```markdown
# Architecture Specification

> Generated by openlore on 2025-01-30
> Source files: src/*, package.json

## Purpose

Documents the architectural patterns and structure of the system.

## Architecture Style

This system follows a **layered architecture** pattern:

```
┌─────────────────────────────────────┐
│         Presentation Layer          │
│    (Routes, Controllers, DTOs)      │
├─────────────────────────────────────┤
│          Business Layer             │
│     (Services, Domain Logic)        │
├─────────────────────────────────────┤
│           Data Layer                │
│   (Repositories, Models, ORM)       │
└─────────────────────────────────────┘
```

## Requirements

### Requirement: LayerSeparation

The system SHALL maintain separation between presentation, business, and data layers.

#### Scenario: NoDirectDatabaseAccess
- **GIVEN** a route handler in the presentation layer
- **WHEN** data persistence is needed
- **THEN** the handler calls a service, not the database directly

## Layers

### Presentation Layer

**Purpose**: HTTP request handling and response formatting
**Location**: `src/routes/`, `src/controllers/`

### Business Layer

**Purpose**: Domain logic and business rules
**Location**: `src/services/`

### Data Layer

**Purpose**: Data persistence and retrieval
**Location**: `src/models/`, `src/repositories/`

## Technical Notes

- **Pattern**: Layered Architecture
- **Dependency Direction**: Presentation → Business → Data
```

## Validation

Generated specs should pass:

```bash
openspec validate --all
```

Common validation issues:
- Missing RFC 2119 keywords in requirements
- Scenarios not using `####` heading level
- Missing Given/When/Then format
- Broken internal links
