# Architecture Specification

> Generated by openlore on 2025-01-30
> Source files: src/core/*, src/commands/*, src/cli/index.ts

## Purpose

Documents the architectural patterns and structure of the OpenSpec CLI tool, including its layered design, dependency flow, and key design decisions.

## Architecture Style

OpenSpec follows a **layered architecture** with clear separation between CLI, Commands, and Core:

```
┌─────────────────────────────────────────────────────────┐
│                    CLI Layer                             │
│              (src/cli/index.ts)                          │
│         Entry point, Commander.js setup                  │
├─────────────────────────────────────────────────────────┤
│                  Commands Layer                          │
│               (src/commands/*.ts)                        │
│    Spec, Change, Validate, Schema, Config, Init          │
├─────────────────────────────────────────────────────────┤
│                    Core Layer                            │
│                  (src/core/*.ts)                         │
│   Validation, Parsing, Artifact Graph, Schemas           │
├─────────────────────────────────────────────────────────┤
│                   Utils Layer                            │
│                  (src/utils/*.ts)                        │
│      File I/O, Interactive prompts, Formatting           │
└─────────────────────────────────────────────────────────┘
```

## Requirements

### Requirement: LayerSeparation

The system SHALL maintain separation between CLI, Commands, Core, and Utils layers.

#### Scenario: CoreIndependence
- **GIVEN** a core module like validation
- **WHEN** its imports are analyzed
- **THEN** it does not import from commands or CLI layers

#### Scenario: CommandsUseCore
- **GIVEN** a command module like spec.ts
- **WHEN** it needs validation logic
- **THEN** it imports from core/validation, not implementing its own

### Requirement: SchemaFirstDesign

The system SHALL use Zod schemas as the single source of truth for data structures.

#### Scenario: TypeInference
- **GIVEN** a Zod schema for Spec
- **WHEN** TypeScript types are needed
- **THEN** types are inferred from schema using z.infer<>

#### Scenario: RuntimeValidation
- **GIVEN** user input that should match a schema
- **WHEN** the data is processed
- **THEN** Zod schema validates at runtime

### Requirement: AdapterPattern

The system SHALL use adapters to support multiple AI tools with a single codebase.

#### Scenario: CommandGeneration
- **GIVEN** a skill definition for "new change"
- **WHEN** commands are generated for different tools
- **THEN** each tool's adapter produces tool-specific format

#### Scenario: AddingNewTool
- **GIVEN** a new AI tool needs support
- **WHEN** a developer creates an adapter
- **THEN** all existing skills work with the new tool

### Requirement: MultiLocationResolution

The system SHALL support configuration and schemas from multiple locations with clear precedence.

#### Scenario: ProjectOverridesUser
- **GIVEN** config exists in both project and user locations
- **WHEN** configuration is loaded
- **THEN** project config takes precedence

#### Scenario: PackageFallback
- **GIVEN** a schema only exists in the package
- **WHEN** the schema is requested
- **THEN** the package schema is used as fallback

### Requirement: InteractiveByDefault

The system SHALL default to interactive mode with graceful fallback for non-TTY environments.

#### Scenario: TTYPrompts
- **GIVEN** a command missing required arguments
- **WHEN** running in a TTY terminal
- **THEN** interactive prompts are shown

#### Scenario: NonTTYErrors
- **GIVEN** a command missing required arguments
- **WHEN** running in a non-TTY environment (CI/CD)
- **THEN** clear error messages are returned instead of prompts

### Requirement: ProgressiveDisclosure

The system SHOULD present information progressively, showing summaries first with detail on demand.

#### Scenario: ValidationSummary
- **GIVEN** validation of 10 specs
- **WHEN** validation completes
- **THEN** a summary (8 passed, 2 failed) is shown first
- **AND** details are available with --verbose flag

## Layers

### CLI Layer

**Purpose**: Entry point and Commander.js program setup
**Location**: `src/cli/index.ts`
**Responsibilities**:
- Parse command-line arguments
- Route to appropriate command handlers
- Handle global options (--version, --help)

### Commands Layer

**Purpose**: Individual command implementations
**Location**: `src/commands/*.ts`
**Key Files**:
- `spec.ts` - Spec viewing and listing
- `change.ts` - Change management
- `validate.ts` - Validation operations
- `schema.ts` - Schema inspection
- `config.ts` - Configuration management
- `init.ts` - Project initialization

### Core Layer

**Purpose**: Business logic independent of CLI
**Location**: `src/core/*.ts`
**Key Modules**:
- `validation/` - Schema and rule validation
- `parsers/` - Markdown parsing
- `artifact-graph/` - Dependency resolution
- `schemas/` - Zod schema definitions

### Utils Layer

**Purpose**: Shared utilities
**Location**: `src/utils/*.ts`
**Key Files**:
- `file-system.ts` - File operations
- `interactive.ts` - Prompt utilities
- `formatting.ts` - Output formatting

## Data Flow

1. **User Input** → CLI parses arguments
2. **Command Handler** → Validates options, prompts if needed
3. **Core Logic** → Processes request using schemas and parsers
4. **Output** → Formats and displays results

## External Integrations

| System | Purpose | Location |
|--------|---------|----------|
| PostHog | Optional telemetry | `src/telemetry/` |
| YAML Parser | Schema/config files | Throughout |
| Inquirer | Interactive prompts | `src/utils/interactive.ts` |

## Technical Notes

- **Pattern**: Layered Architecture with Dependency Injection
- **Build**: esbuild for fast compilation
- **Testing**: Vitest with fixtures
- **Distribution**: npm package with bin entry
