# API Versioning

This document describes the Lilith API versioning strategy, deprecation
policies, and migration guidance.

## Overview

The Lilith API uses **semantic versioning** with **URL path-based versioning**
as the primary mechanism. All API endpoints are prefixed with a version
identifier (e.g., `/v1/`) to ensure backward compatibility and clear version
management.

**Current API Version**: v1 (1.0.0)

## Versioning Scheme

### Semantic Versioning

We follow [Semantic Versioning 2.0.0](https://semver.org/) with the format
`MAJOR.MINOR.PATCH`:

| Version Component | Description                                  | Example       |
| ----------------- | -------------------------------------------- | ------------- |
| **MAJOR**         | Breaking changes that require client updates | 1.0.0 → 2.0.0 |
| **MINOR**         | New features, backward compatible            | 1.0.0 → 1.1.0 |
| **PATCH**         | Bug fixes and non-breaking improvements      | 1.0.0 → 1.0.1 |

### URL Path Versioning

All API endpoints include the major version in the URL path:

```
https://api.lilith.app/v1/chat
https://api.lilith.app/v1/auth/login
https://api.lilith.app/v1/content/courses
```

**Pattern**: `/v{MAJOR_VERSION}/...`

### Header-Based Versioning (Optional)

For finer-grained version control, you can optionally specify the exact version
via headers:

| Header              | Description                            | Example                    |
| ------------------- | -------------------------------------- | -------------------------- |
| `Accept-Version`    | Request specific API version           | `Accept-Version: 1.0`      |
| `X-API-Version`     | Response header indicating API version | `X-API-Version: 1.0.0`     |
| `X-Min-API-Version` | Minimum supported version              | `X-Min-API-Version: 1.0.0` |

**Example Request with Version Header**:

```bash
curl -X GET "https://api.lilith.app/v1/chat" \
  -H "Accept-Version: 1.0" \
  -H "Authorization: Bearer <token>"
```

## Version Support Lifecycle

### Support Tiers

| Tier               | Description                                | Duration                           |
| ------------------ | ------------------------------------------ | ---------------------------------- |
| **Current**        | Full support with all features and fixes   | Ongoing                            |
| **Previous Major** | Security updates only                      | 12 months after next major release |
| **Beta**           | Limited support, may change without notice | Until stable release               |
| **Deprecated**     | No support, scheduled for removal          | 90 days notice before removal      |

### Current Supported Versions

| Version | API Version | Status     | End of Support |
| ------- | ----------- | ---------- | -------------- |
| 1.0.0   | v1          | Current    | N/A            |
| 0.9.0   | v1-beta     | Deprecated | 2024-03-01     |

## Deprecation Policy

### Timeline

When deprecating an API feature, endpoint, or version, we follow this timeline:

| Phase              | Timing                 | Actions                                      |
| ------------------ | ---------------------- | -------------------------------------------- |
| **Announcement**   | 90 days before removal | Public announcement, documentation updates   |
| **Feature Freeze** | 60 days before removal | No new features, bug fixes only              |
| **Final Warning**  | 30 days before removal | Aggressive deprecation warnings in responses |
| **Removal**        | End of support date    | Feature/endpoint removed                     |

### Deprecation Headers

When an endpoint or feature is deprecated, responses include these headers:

| Header        | Format                 | Description                            |
| ------------- | ---------------------- | -------------------------------------- |
| `Deprecation` | RFC 9512 date format   | Indicates deprecation status           |
| `Sunset`      | RFC 9512 date format   | Date when feature will be removed      |
| `Link`        | URL to migration guide | Link to documentation for alternatives |

**Example Deprecated Response Headers**:

```http
HTTP/1.1 200 OK
Content-Type: application/json
Deprecation: @1704067200
Sunset: Sat, 01 Jun 2024 00:00:00 GMT
Link: <https://docs.lilith.app/migration/deprecated-endpoint>; rel="deprecation"
```

### Deprecation Warnings in Response Body

Deprecated endpoints may include warnings in the response:

```json
{
  "data": { ... },
  "warnings": [
    {
      "code": "DEPRECATED_ENDPOINT",
      "message": "This endpoint is deprecated and will be removed on 2024-06-01. Use /v1/chat instead.",
      "documentation": "https://docs.lilith.app/migration/chat-legacy"
    }
  ]
}
```

## Breaking Changes

### Definition

A **breaking change** is any modification that requires clients to update their
code. This includes:

- Removing an endpoint
- Removing or renaming a required request parameter
- Removing or renaming a response field
- Changing a field's data type
- Changing authentication requirements
- Changing error response structure
- Modifying rate limits significantly

### Non-Breaking Changes

The following changes are considered **non-breaking** and may occur in
minor/patch releases:

- Adding new endpoints
- Adding optional request parameters
- Adding new response fields
- Adding new enum values (where clients should handle unknown values)
- Relaxing validation rules
- Improving error messages
- Adding new HTTP status codes for new scenarios

### Breaking Change Notice

For breaking changes, we provide:

1. **90-day advance notice** via:
   - Developer newsletter
   - Documentation banners
   - API response headers
   - Developer dashboard notifications
   - Community forum announcements

2. **6-month transition period** for major breaking changes

3. **Migration guide** with:
   - Detailed description of changes
   - Code examples for old vs. new implementations
   - Step-by-step upgrade instructions
   - Testing recommendations

## Migration Guides

### Available Migration Guides

| From Version | To Version | Guide                                                  |
| ------------ | ---------- | ------------------------------------------------------ |
| 0.9.0 (beta) | 1.0.0      | [Migration Guide: v0.9 to v1.0](#migration-v09-to-v10) |

### Migration Guide Template

Each migration guide includes:

1. **Summary of Breaking Changes**
   - Removed endpoints
   - Modified parameters
   - Response format changes

2. **Impact Assessment**
   - High: Requires immediate code changes
   - Medium: Requires code changes before deadline
   - Low: Optional improvements recommended

3. **Step-by-Step Migration**
   - Pre-migration checklist
   - Code change examples
   - Testing recommendations
   - Rollout strategy

4. **New Features**
   - Features available after migration
   - Benefits of upgrading

---

## Migration v0.9 to v1.0

### Summary

This guide covers migration from the beta v0.9 API to the stable v1.0 API.

### Breaking Changes

| Change Type      | Description                             | Impact | Replacement                        |
| ---------------- | --------------------------------------- | ------ | ---------------------------------- |
| Endpoint Removal | `/v1/chat/legacy` removed               | High   | Use `/v1/chat` with updated format |
| Parameter Change | `persona` now required in chat requests | Medium | Add `persona` field with valid ID  |
| Response Format  | Chat response includes new structure    | Low    | Update response parsing            |

### Detailed Changes

#### 1. Chat Endpoint Update (High Impact)

**Before (v0.9)**:

```bash
curl -X POST "https://api.lilith.app/v1/chat/legacy" \
  -H "Authorization: Bearer <token>" \
  -d '{"message": "Hello"}'
```

**After (v1.0)**:

```bash
curl -X POST "https://api.lilith.app/v1/chat" \
  -H "Authorization: Bearer <token>" \
  -d '{
    "message": "Hello",
    "persona": "buddha",
    "conversation_id": "optional-id"
  }'
```

#### 2. Required Persona Parameter (Medium Impact)

**Before (v0.9)**: `persona` was optional, defaulted to generic AI **After
(v1.0)**: `persona` is required, must be a valid persona ID

**Available Personas**:

```bash
curl -X GET "https://api.lilith.app/v1/personas" \
  -H "Authorization: Bearer <token>"
```

#### 3. Response Format Changes (Low Impact)

**Before (v0.9)**:

```json
{
  "response": "Hello, seeker.",
  "audio_url": "https://..."
}
```

**After (v1.0)**:

```json
{
  "data": {
    "message": "Hello, seeker.",
    "audio": {
      "url": "https://...",
      "duration_ms": 2500,
      "format": "mp3"
    },
    "persona": {
      "id": "buddha",
      "name": "Buddha"
    }
  },
  "metadata": {
    "conversation_id": "conv_123",
    "turn_id": "turn_456",
    "tokens_used": 150
  }
}
```

### New Features in v1.0

- Enhanced AI persona capabilities with 100+ personalities
- Improved audio streaming quality (up to 320kbps)
- Extended WebSocket message types for real-time features
- Advanced SSML support for TTS customization
- Cross-tradition comparison capabilities

### Recommended Upgrade Path

1. **Review** breaking changes documentation
2. **Update** client code for new chat format
3. **Add** required `persona` field to all chat requests
4. **Update** response parsing for new structure
5. **Test** with staging environment
6. **Deploy** incrementally to production

### Testing Checklist

- [ ] Chat endpoints work with required `persona` parameter
- [ ] Response parsing handles new nested structure
- [ ] Audio playback works with new audio object format
- [ ] Error handling updated for new error structure
- [ ] WebSocket connections use new message format

---

## SDK Compatibility

### SDK Version Mapping

| SDK            | Version | API Compatibility |
| -------------- | ------- | ----------------- |
| TypeScript SDK | 1.0.0   | v1                |
| TypeScript SDK | 0.9.2   | v1-beta           |

### Updating SDKs

**TypeScript/JavaScript**:

```bash
npm install @lilith/sdk@^1.0.0
```

**Update Code**:

```typescript
// Before (v0.9.2)
import { LilithClient } from '@lilith/sdk';
const client = new LilithClient({ apiKey: 'key' });
const response = await client.chat('Hello');

// After (v1.0.0)
import { LilithClient } from '@lilith/sdk';
const client = new LilithClient({ apiKey: 'key' });
const response = await client.chat({
  message: 'Hello',
  persona: 'buddha',
});
```

---

## Version Detection

### Checking API Version

**Endpoint**:

```bash
curl -X GET "https://api.lilith.app/v1/health" \
  -H "Authorization: Bearer <token>"
```

**Response**:

```json
{
  "status": "ok",
  "version": "1.0.0",
  "api_version": "v1",
  "uptime_s": 86400
}
```

### Programmatic Version Check

```typescript
const response = await fetch('https://api.lilith.app/v1/health');
const health = await response.json();
const apiVersion = response.headers.get('X-API-Version');
console.log(`API Version: ${apiVersion}, Service Version: ${health.version}`);
```

---

## Communication Channels

### Staying Informed

Subscribe to these channels for version updates:

| Channel              | Purpose             | Subscribe                                             |
| -------------------- | ------------------- | ----------------------------------------------------- |
| Developer Newsletter | Major announcements | [Subscribe](https://lilith.app/developers/newsletter) |
| Community Forum      | Discussion, Q&A     | [Join](https://community.lilith.app)                  |
| RSS Feed             | Release notes       | [RSS](https://docs.lilith.app/releases.xml)           |
| Slack Channel        | Real-time updates   | #api-announcements                                    |

### Emergency Notifications

For critical security updates and emergency patches:

- Email notifications to registered developers
- In-app dashboard alerts
- Status page updates at [status.lilith.app](https://status.lilith.app)

---

## Emergency Procedures

### Hotfix Policy

| Issue Type               | Response                                    |
| ------------------------ | ------------------------------------------- |
| Security vulnerabilities | Immediate patch to all supported versions   |
| Critical bugs            | Patch to current and previous major version |
| Data integrity issues    | Emergency rollback procedures               |

### Rollback

If you encounter issues after upgrading:

1. Check the [status page](https://status.lilith.app) for known issues
2. Review the migration guide for missed steps
3. Contact [api-support@lilith.app](mailto:api-support@lilith.app) for
   assistance
4. Consider rolling back to previous SDK version while investigating

---

## Related Documentation

- [Authentication](./authentication.md) - Authentication and authorization
- [Rate Limits](./rate-limits.md) - API rate limiting policies
- [Error Codes](./error-codes.md) - Error response reference
- [Changelog](../changelogs/CHANGELOG.md) - Complete change history

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation Issues**:
  [GitHub Issues](https://github.com/lilith/platform/issues)
- **Community**: [Discord Server](https://discord.gg/lilith)
