# CURVED Interface Standard

## Overview

**CURVED** is the standard interface that all SpecVerse business logic controllers must implement. It defines the complete set of operations for managing domain models.

## CURVED Operations

| Letter | Operation | Description | Required |
|--------|-----------|-------------|----------|
| **C** | Create | Create a new entity | Yes |
| **U** | Update | Update an existing entity | Yes |
| **R** | Retrieve | Retrieve entity (single + list) | Yes |
| **V** | Validate | Validate data before operations | Yes |
| **E** | Evolve | Lifecycle-aware state transitions | Yes |
| **D** | Delete | Delete an entity | Yes |

## TypeScript Interface

```typescript
/**
 * Standard CURVED interface for all service controllers
 * All business logic controllers must implement this interface
 */
interface CurvedController<T> {
  // C - Create
  create(data: any): Promise<T>;

  // U - Update
  update(id: string, data: any): Promise<T>;

  // R - Retrieve (single)
  retrieve(id: string): Promise<T>;

  // R - Retrieve (list)
  retrieveAll(options?: RetrieveOptions): Promise<T[]>;

  // V - Validate
  validate(
    data: any,
    context: { operation: 'create' | 'update' | 'evolve' }
  ): ValidationResult;

  // E - Evolve (lifecycle-aware updates)
  evolve(id: string, data: any): Promise<T>;

  // D - Delete
  delete(id: string): Promise<void>;
}

interface RetrieveOptions {
  skip?: number;
  take?: number;
  where?: Record<string, any>;
  orderBy?: Record<string, 'asc' | 'desc'>;
  include?: string[];
}

interface ValidationResult {
  valid: boolean;
  errors: string[];
}
```

## Architecture Layers

### 1. Controllers (Model-specific)
- **Must implement**: Full CURVED interface
- **Examples**: `UserController`, `ProjectController`, `TaskController`
- **Location**: `src/controllers/`
- **Generated by**: Service factories (PrismaServices, TypeORMServices, etc.)
- **Additional**: Can have custom actions beyond CURVED

```yaml
# In SpecVerse spec
controllers:
  UserController:
    model: User
    curved:               # ← CURVED operations
      create: {}
      update: {}
      retrieve: {}
      validate: {}
      evolve: {}
      delete: {}
    actions:              # ← Custom actions (beyond CURVED)
      resetPassword: {}
      verifyEmail: {}
```

### 2. Services (Abstract business logic)
- **Must implement**: Custom operations (NOT CURVED)
- **Examples**: `NotificationService`, `TaskAssignmentService`
- **Location**: `src/services/`
- **Generated by**: Service factories (PrismaServices, etc.)
- **Operations**: Custom business logic operations

```yaml
# In SpecVerse spec
services:
  NotificationService:
    operations:           # ← Custom operations (NOT CURVED)
      sendWelcomeEmail: {}
      sendPasswordReset: {}
```

### 3. Storage/ORM Layer
- **Must support**: CURVED primitives
- **Examples**: Prisma client, TypeORM repositories, Mongoose models
- **Location**: ORM-specific (e.g., `prisma/schema.prisma`)
- **Generated by**: ORM factories (PrismaORM, TypeORM, Mongoose)
- **Provides**: Database access methods that enable CURVED operations

## Implementation Requirements

### All Service Factories Must:

1. **Generate controllers** that implement the full CURVED interface
2. **Support all CURVED operations** for every model
3. **Provide consistent signatures** across different ORMs
4. **Include validation** as part of the CURVED interface
5. **Support evolve** for lifecycle-aware updates

### Example Implementations:

#### PrismaServices
- Uses: `@prisma/client`
- Controllers: `src/controllers/{Model}Controller.ts`
- Pattern: Class-based with Prisma client calls

#### TypeORMServices (future)
- Uses: `typeorm` repositories
- Controllers: `src/controllers/{Model}Controller.ts`
- Pattern: Class-based with TypeORM repository calls

#### MongooseServices (future)
- Uses: `mongoose` models
- Controllers: `src/controllers/{Model}Controller.ts`
- Pattern: Class-based with Mongoose model calls

## Data Flow

```
API Layer (Fastify/SOAP/GraphQL)
    ↓ calls
    ├─→ Controllers (CURVED + actions)
    │       ↓ calls
    │   Storage/ORM (CURVED primitives)
    │       ↓
    │   Database
    │
    └─→ Services (custom operations)
            ↓ can call
            ├─→ Controllers (CURVED)
            └─→ Storage/ORM (directly)
```

**Key points:**
- API layer can call **both** Controllers and Services
- Services can call Controllers OR ORM directly
- Controllers always call ORM/Storage layer

## Validation in CURVED

The **V** (Validate) operation is special:

### Internal Validation
All CURVED operations internally call `validate()` before execution:

```typescript
async create(data: any): Promise<T> {
  // Internal validation
  const validation = this.validate(data, { operation: 'create' });
  if (!validation.valid) {
    throw new Error(`Validation failed: ${validation.errors.join(', ')}`);
  }

  // Proceed with creation
  return await this.orm.create(data);
}
```

### External Validation
The validate operation can also be exposed as an API endpoint for dry-run validation:

```typescript
// POST /api/users/validate
{
  "data": { "email": "invalid", "name": "John" },
  "operation": "create"
}

// Response
{
  "valid": false,
  "errors": ["email must be a valid email address"]
}
```

## Evolve vs Update

### Update
Standard field updates without lifecycle validation:
```typescript
// Update any field
await userController.update(userId, { name: 'New Name', email: 'new@email.com' });
```

### Evolve
Lifecycle-aware state transitions with validation:
```typescript
// Evolve through lifecycle states
await taskController.evolve(taskId, {
  status: 'in_progress'  // Must follow lifecycle: todo → in_progress
});
```

## Extension Points

While CURVED defines the core interface, controllers can extend it with:

1. **Custom Actions** - Additional operations specific to the model
2. **Event Publishing** - Emit events after CURVED operations
3. **Hooks** - Before/after hooks for operations
4. **Caching** - Add caching layer for retrieve operations
5. **Authorization** - Add permission checks before operations

## Testing CURVED Implementations

All service factories should provide tests verifying:

```typescript
describe('CurvedController', () => {
  it('implements create operation', async () => {
    const result = await controller.create(validData);
    expect(result).toBeDefined();
  });

  it('implements update operation', async () => {
    const result = await controller.update(id, updateData);
    expect(result).toBeDefined();
  });

  it('implements retrieve operation', async () => {
    const result = await controller.retrieve(id);
    expect(result).toBeDefined();
  });

  it('implements retrieveAll operation', async () => {
    const result = await controller.retrieveAll();
    expect(Array.isArray(result)).toBe(true);
  });

  it('implements validate operation', async () => {
    const result = controller.validate(data, { operation: 'create' });
    expect(result).toHaveProperty('valid');
    expect(result).toHaveProperty('errors');
  });

  it('implements evolve operation', async () => {
    const result = await controller.evolve(id, evolveData);
    expect(result).toBeDefined();
  });

  it('implements delete operation', async () => {
    await expect(controller.delete(id)).resolves.not.toThrow();
  });
});
```

## Summary

**CURVED is the universal interface for all SpecVerse business logic controllers:**
- Ensures consistency across different ORMs (Prisma, TypeORM, Mongoose)
- Enables protocol-agnostic API layers (REST, SOAP, GraphQL, gRPC)
- Provides complete lifecycle management (Create, Update, Retrieve, Validate, Evolve, Delete)
- Separates concerns between Controllers (model-specific) and Services (abstract)
- Supports extension while maintaining core interface compatibility
