# Hathor Domain API Reference

Hathor is the worldbuilding domain of the Oshun platform. It provides three
backend services for creating, managing, and simulating fictional worlds:

| Service             | Framework | Default Port | Purpose                                     |
| ------------------- | --------- | ------------ | ------------------------------------------- |
| `world-api`         | Hono      | 3001         | World state, versioning, merging, querying  |
| `narrative-api`     | Hono      | 3002         | Story graphs, quests, dialogues, validation |
| `simulation-worker` | Hono      | 3004         | Background simulation job execution         |

All services use JSON request/response bodies and follow a consistent error
format.

---

## Common Patterns

### Authentication

Requests carry the user identity via the `X-User-ID` header. The API gateway (or
workbench client) is expected to set this header after verifying the user
session. Some endpoints also accept `X-API-Key`.

```
Authorization: Bearer <token>   (handled by gateway)
X-User-ID: usr_abc123           (forwarded to Hathor services)
```

### Error Format

All errors return a JSON body with a top-level `error` object:

```json
{
  "error": {
    "code": "NOT_FOUND",
    "message": "World not found: wld_xyz"
  }
}
```

Zod validation errors include a `details` array with per-field messages. HTTP
status codes follow standard semantics (400, 404, 409, 500, etc.).

### Pagination

List endpoints support cursor/offset pagination with `page` and `limit` query
parameters. Responses include `items`, `total`, and related metadata.

### Rate Limiting

The `world-api` applies rate limiting on `/api/*` routes: 100 requests per
minute per IP. Rate limit state is exposed via response headers:

- `X-RateLimit-Limit`
- `X-RateLimit-Remaining`
- `X-RateLimit-Reset`

---

## 1. World API (`@hathor/world-api`)

Base URL: `/api/v1`

Source: `apps/hathor/world-api/src/`

### 1.1 Health & Readiness

| Method | Path      | Description                                      |
| ------ | --------- | ------------------------------------------------ |
| GET    | `/health` | Returns service status, name, version, timestamp |
| GET    | `/ready`  | Returns readiness with database and cache checks |

### 1.2 World CRUD

All world routes are mounted at `/api/v1/worlds`.

| Method | Path                 | Description                       | Auth      |
| ------ | -------------------- | --------------------------------- | --------- |
| GET    | `/worlds`            | List worlds with filtering & sort | Optional  |
| POST   | `/worlds`            | Create a new world                | X-User-ID |
| GET    | `/worlds/:id`        | Get world by ID                   | Optional  |
| PUT    | `/worlds/:id`        | Update world properties           | X-User-ID |
| DELETE | `/worlds/:id`        | Delete a world                    | X-User-ID |
| POST   | `/worlds/:id/clone`  | Clone a world under a new name    | X-User-ID |
| GET    | `/worlds/:id/export` | Export world as downloadable JSON | Optional  |

#### List Query Parameters

| Parameter        | Type     | Description                                         |
| ---------------- | -------- | --------------------------------------------------- |
| `status`         | string[] | Filter by status (draft, published, archived, etc.) |
| `genre`          | string[] | Filter by genre tag                                 |
| `ownerId`        | string   | Filter by owner user ID                             |
| `collaboratorId` | string   | Filter by collaborator user ID                      |
| `tags`           | string[] | Filter by tags                                      |
| `search`         | string   | Full-text search across world name/description      |
| `page`           | number   | Page number (default: 1)                            |
| `limit`          | number   | Items per page (default: 20)                        |
| `sortBy`         | string   | Sort field                                          |
| `sortOrder`      | string   | `asc` or `desc`                                     |

#### Create World Request Body (validated by `CreateWorldSchema`)

```json
{
  "name": "Middle Kingdoms",
  "description": "A high-fantasy world with complex faction politics",
  "genre": ["fantasy", "political"],
  "tags": ["medieval", "magic-system"],
  "settings": {
    "timescale": "years",
    "simulationEnabled": true
  }
}
```

### 1.3 Collaborator Management

| Method | Path                                | Description           |
| ------ | ----------------------------------- | --------------------- |
| POST   | `/worlds/:id/collaborators`         | Add a collaborator    |
| DELETE | `/worlds/:id/collaborators/:userId` | Remove a collaborator |

**Add Collaborator Request:**

```json
{ "userId": "usr_collaborator456" }
```

### 1.4 Branch Management

Branches enable parallel editing of a world (similar to git branches).

| Method | Path                             | Description        |
| ------ | -------------------------------- | ------------------ |
| GET    | `/worlds/:id/branches`           | List all branches  |
| POST   | `/worlds/:id/branches`           | Create a branch    |
| GET    | `/worlds/:id/branches/:branchId` | Get branch details |
| DELETE | `/worlds/:id/branches/:branchId` | Delete a branch    |

**Create Branch Request (validated by `CreateBranchSchema`):**

```json
{
  "name": "feature/new-faction",
  "fromVersionId": "ver_abc123",
  "description": "Exploring a new desert faction",
  "isProtected": false
}
```

### 1.5 Status & Settings

| Method | Path                   | Description             |
| ------ | ---------------------- | ----------------------- |
| PUT    | `/worlds/:id/status`   | Update world status     |
| PATCH  | `/worlds/:id/settings` | Partial-update settings |
| PATCH  | `/worlds/:id/stats`    | Update world statistics |

### 1.6 Versioning

Versions represent commits/snapshots of world state. Routes are mounted under
`/api/v1/worlds`.

| Method | Path                                           | Description                         |
| ------ | ---------------------------------------------- | ----------------------------------- |
| GET    | `/worlds/:worldId/versions`                    | List versions (filterable)          |
| POST   | `/worlds/:worldId/versions`                    | Create a new version (commit)       |
| GET    | `/worlds/:worldId/versions/:versionId`         | Get version by ID                   |
| GET    | `/worlds/:worldId/versions/:versionId/history` | Get ancestor chain                  |
| GET    | `/worlds/:worldId/versions/:versionId/state`   | Reconstruct state at a version      |
| GET    | `/worlds/:worldId/versions/:versionId/changes` | Get change set for a version        |
| GET    | `/worlds/:worldId/current`                     | Get the current (head) version      |
| GET    | `/worlds/:worldId/state`                       | Get the current reconstructed state |

#### Version List Query Parameters

| Parameter   | Type    | Description                |
| ----------- | ------- | -------------------------- |
| `branchId`  | string  | Filter by branch           |
| `authorId`  | string  | Filter by author           |
| `isRelease` | boolean | Only show release versions |
| `fromDate`  | string  | ISO date lower bound       |
| `toDate`    | string  | ISO date upper bound       |
| `page`      | number  | Page number                |
| `limit`     | number  | Items per page             |
| `sortOrder` | string  | `asc` or `desc`            |

#### Create Version Request (validated by `CreateVersionSchema`)

```json
{
  "message": "Added desert faction territory",
  "branchId": "br_feature123",
  "changes": [
    {
      "type": "add",
      "entityType": "faction",
      "entityId": "fac_desert01",
      "data": { "name": "Sand Wardens", "territory": "Great Desert" }
    }
  ],
  "tags": ["faction-update"]
}
```

### 1.7 Releases & Snapshots

| Method | Path                                            | Description                  |
| ------ | ----------------------------------------------- | ---------------------------- |
| GET    | `/worlds/:worldId/releases`                     | List all release versions    |
| POST   | `/worlds/:worldId/versions/:versionId/release`  | Mark version as release      |
| POST   | `/worlds/:worldId/versions/:versionId/snapshot` | Create a full state snapshot |
| GET    | `/worlds/:worldId/versions/:versionId/snapshot` | Get snapshot for a version   |

### 1.8 Revert & Compare

| Method | Path                                              | Description               |
| ------ | ------------------------------------------------- | ------------------------- |
| POST   | `/worlds/:worldId/versions/:versionId/revert`     | Revert world to a version |
| GET    | `/worlds/:worldId/versions/:fromId/compare/:toId` | Diff between two versions |

### 1.9 Query Engine

The query engine provides advanced filtering, search, and graph traversal for
world entities (factions, characters, locations, events).

| Method | Path                                                 | Description                             |
| ------ | ---------------------------------------------------- | --------------------------------------- |
| POST   | `/worlds/:worldId/query`                             | General entity query                    |
| GET    | `/worlds/:worldId/search?q=...`                      | Full-text search across entities        |
| GET    | `/worlds/:worldId/factions`                          | Query factions (type-specific)          |
| GET    | `/worlds/:worldId/characters`                        | Query characters                        |
| GET    | `/worlds/:worldId/locations`                         | Query locations                         |
| GET    | `/worlds/:worldId/events`                            | Query timeline events                   |
| GET    | `/worlds/:worldId/entities/:type/:id`                | Get entity by type and ID               |
| POST   | `/worlds/:worldId/entities/:type/batch`              | Batch-get entities by IDs               |
| GET    | `/worlds/:worldId/entities/:type/:id/related/:field` | Get related entities                    |
| POST   | `/worlds/:worldId/relationships`                     | Graph traversal query                   |
| POST   | `/worlds/:worldId/paths`                             | Find paths between entities             |
| POST   | `/worlds/:worldId/aggregate`                         | Aggregation (count, sum, avg, group_by) |

#### General Query Request Body (validated by `WorldQuerySchema`)

```json
{
  "entityTypes": ["character", "faction"],
  "search": "desert",
  "filter": {
    "and": [{ "field": "status", "operator": "eq", "value": "active" }]
  },
  "sort": [{ "field": "name", "direction": "asc" }],
  "page": 1,
  "limit": 50,
  "versionId": "ver_abc123"
}
```

#### Search Query Parameters

| Parameter   | Type   | Description                                          |
| ----------- | ------ | ---------------------------------------------------- |
| `q`         | string | **Required.** The search term                        |
| `types`     | string | Comma-separated entity types to search               |
| `page`      | number | Page number                                          |
| `limit`     | number | Results per page (default: 20)                       |
| `versionId` | string | Query against a specific version (time-travel query) |

#### Path Query Request Body (validated by `PathQuerySchema`)

```json
{
  "fromEntityType": "character",
  "fromEntityId": "chr_001",
  "toEntityType": "faction",
  "toEntityId": "fac_002",
  "maxDepth": 4
}
```

### 1.10 Merge System

Git-like diff and merge for collaborative world editing.

| Method | Path                                                          | Description                       |
| ------ | ------------------------------------------------------------- | --------------------------------- |
| GET    | `/worlds/:worldId/diff/:fromId/:toId`                         | Diff between two versions         |
| GET    | `/worlds/:worldId/branches/:sourceId/diff/:targetId`          | Diff between branches (501 - WIP) |
| GET    | `/worlds/:worldId/merge-requests`                             | List merge requests               |
| POST   | `/worlds/:worldId/merge-requests`                             | Create a merge request            |
| GET    | `/worlds/:worldId/merge-requests/:mrId`                       | Get merge request details         |
| POST   | `/worlds/:worldId/merge-requests/:mrId/close`                 | Close a merge request             |
| GET    | `/worlds/:worldId/merge-requests/:mrId/conflicts`             | List conflicts                    |
| POST   | `/worlds/:worldId/merge-requests/:mrId/conflicts/resolve`     | Resolve a single conflict         |
| POST   | `/worlds/:worldId/merge-requests/:mrId/conflicts/resolve-all` | Resolve all with strategy         |
| POST   | `/worlds/:worldId/merge-requests/:mrId/merge`                 | Execute the merge                 |
| POST   | `/worlds/:worldId/cherry-pick`                                | Cherry-pick changes to a branch   |
| POST   | `/worlds/:worldId/rebase`                                     | Rebase a branch onto another      |

#### Create Merge Request (validated by `CreateMergeRequestSchema`)

```json
{
  "sourceBranchId": "br_feature123",
  "targetBranchId": "br_main",
  "title": "Add desert faction content",
  "description": "New faction, territories, and NPCs for the Great Desert region"
}
```

#### Resolve Conflict Request (validated by `ResolveConflictSchema`)

```json
{
  "conflictId": "cfl_001",
  "resolution": "source",
  "customData": null
}
```

#### Resolve All Conflicts

```json
{ "strategy": "source" }
```

Strategy must be `"source"` or `"target"`.

---

## 2. Narrative API (`@hathor/narrative-api`)

Base URL: `/api`

Source: `apps/hathor/narrative-api/src/`

### 2.1 Health & Info

| Method | Path      | Description                   |
| ------ | --------- | ----------------------------- |
| GET    | `/health` | Health check                  |
| GET    | `/`       | API information and endpoints |

### 2.2 Story Graphs (`/api/story-graphs`)

Story graphs represent branching narrative structures with arcs, beats, and
nodes.

| Method | Path                                          | Description                 |
| ------ | --------------------------------------------- | --------------------------- |
| GET    | `/api/story-graphs`                           | List story graphs           |
| POST   | `/api/story-graphs`                           | Create a story graph        |
| GET    | `/api/story-graphs/:id`                       | Get story graph by ID       |
| PUT    | `/api/story-graphs/:id`                       | Update story graph          |
| DELETE | `/api/story-graphs/:id`                       | Delete story graph          |
| POST   | `/api/story-graphs/:id/arcs`                  | Add a story arc             |
| PUT    | `/api/story-graphs/:id/arcs/:arcId`           | Update an arc               |
| DELETE | `/api/story-graphs/:id/arcs/:arcId`           | Remove an arc               |
| POST   | `/api/story-graphs/:id/nodes`                 | Add a story node            |
| PUT    | `/api/story-graphs/:id/nodes/:nodeId`         | Update a node               |
| DELETE | `/api/story-graphs/:id/nodes/:nodeId`         | Remove a node               |
| POST   | `/api/story-graphs/:id/nodes/:nodeId/connect` | Connect two nodes           |
| PUT    | `/api/story-graphs/:id/state`                 | Set story state             |
| PUT    | `/api/story-graphs/:id/variables/:name`       | Set a story variable        |
| PUT    | `/api/story-graphs/:id/flags/:name`           | Set a story flag            |
| POST   | `/api/story-graphs/:id/clone`                 | Clone the story graph       |
| GET    | `/api/story-graphs/:id/export`                | Export as downloadable JSON |

#### List Query Parameters (validated by `StoryGraphListQuerySchema`)

| Parameter | Type     | Description           |
| --------- | -------- | --------------------- |
| `worldId` | string   | Filter by world       |
| `state`   | string[] | Filter by story state |
| `search`  | string   | Search                |
| `page`    | number   | Page number           |
| `limit`   | number   | Items per page        |

#### Connect Nodes Request

```json
{
  "targetNodeId": "snode_002",
  "label": "Accept quest",
  "priority": 1,
  "isDefault": false
}
```

### 2.3 Quests (`/api/quests`)

| Method | Path                                         | Description                 |
| ------ | -------------------------------------------- | --------------------------- |
| GET    | `/api/quests`                                | List quests                 |
| POST   | `/api/quests`                                | Create a quest              |
| GET    | `/api/quests/:id`                            | Get quest by ID             |
| PUT    | `/api/quests/:id`                            | Update quest                |
| DELETE | `/api/quests/:id`                            | Delete quest                |
| POST   | `/api/quests/:id/start`                      | Transition to `active`      |
| POST   | `/api/quests/:id/complete`                   | Mark as completed           |
| POST   | `/api/quests/:id/fail`                       | Mark as failed              |
| POST   | `/api/quests/:id/abandon`                    | Mark as abandoned           |
| PUT    | `/api/quests/:id/objectives/:objId/progress` | Update objective progress   |
| POST   | `/api/quests/:id/objectives/:objId/complete` | Complete an objective       |
| POST   | `/api/quests/:id/clone`                      | Clone quest                 |
| GET    | `/api/quests/:id/export`                     | Export as downloadable JSON |

#### Quest List Query Parameters (validated by `QuestListQuerySchema`)

| Parameter  | Type     | Description                                       |
| ---------- | -------- | ------------------------------------------------- |
| `worldId`  | string   | Filter by world                                   |
| `status`   | string[] | Filter by status (draft, active, completed, etc.) |
| `category` | string[] | Filter by category                                |
| `priority` | string[] | Filter by priority                                |
| `search`   | string   | Text search                                       |
| `page`     | number   | Page number                                       |
| `limit`    | number   | Items per page                                    |

#### Update Objective Progress

```json
{ "progress": 75 }
```

### 2.4 Dialogues (`/api/dialogues`)

Dialogue trees support branching conversations with speakers, choices, and
runtime sessions.

| Method | Path                                                 | Description                   |
| ------ | ---------------------------------------------------- | ----------------------------- |
| GET    | `/api/dialogues`                                     | List dialogue trees           |
| POST   | `/api/dialogues`                                     | Create a dialogue tree        |
| GET    | `/api/dialogues/:id`                                 | Get dialogue tree             |
| PUT    | `/api/dialogues/:id`                                 | Update dialogue tree          |
| DELETE | `/api/dialogues/:id`                                 | Delete dialogue tree          |
| POST   | `/api/dialogues/:id/nodes`                           | Add a dialogue node           |
| PUT    | `/api/dialogues/:id/nodes/:nodeId`                   | Update a node                 |
| DELETE | `/api/dialogues/:id/nodes/:nodeId`                   | Remove a node                 |
| POST   | `/api/dialogues/:id/nodes/:nodeId/choices`           | Add a choice to a node        |
| PUT    | `/api/dialogues/:id/nodes/:nodeId/choices/:choiceId` | Update a choice               |
| DELETE | `/api/dialogues/:id/nodes/:nodeId/choices/:choiceId` | Remove a choice               |
| POST   | `/api/dialogues/:id/speakers`                        | Add a speaker                 |
| PUT    | `/api/dialogues/:id/speakers/:speakerId`             | Update a speaker              |
| DELETE | `/api/dialogues/:id/speakers/:speakerId`             | Remove a speaker              |
| POST   | `/api/dialogues/:id/sessions`                        | Start a runtime session       |
| GET    | `/api/dialogues/sessions/:sessionId`                 | Get session state             |
| GET    | `/api/dialogues/sessions/:sessionId/current`         | Get current node in session   |
| POST   | `/api/dialogues/sessions/:sessionId/advance`         | Advance session (make choice) |
| DELETE | `/api/dialogues/sessions/:sessionId`                 | End session                   |
| POST   | `/api/dialogues/:id/clone`                           | Clone dialogue tree           |
| GET    | `/api/dialogues/:id/export`                          | Export as downloadable JSON   |

#### Start Session Request

```json
{
  "initialVariables": { "playerName": "Kael", "reputation": 50 },
  "initialFlags": { "metTheQueen": false, "hasKey": true }
}
```

#### Advance Session Request

```json
{ "choiceId": "choice_accept_quest" }
```

### 2.5 Validation (`/api/validation`)

| Method | Path                                | Description                      |
| ------ | ----------------------------------- | -------------------------------- |
| POST   | `/api/validation/story-graphs`      | Validate a story graph           |
| POST   | `/api/validation/quests`            | Validate a quest                 |
| POST   | `/api/validation/dialogues`         | Validate a dialogue tree         |
| POST   | `/api/validation/batch`             | Batch-validate multiple entities |
| POST   | `/api/validation/constraints/check` | Check a single constraint        |

#### Validate Story Graph Request (validated by `ValidateStoryGraphSchema`)

```json
{
  "storyGraphId": "sg_001",
  "checks": ["reachability", "dead_ends", "loops"]
}
```

#### Batch Validate Request (validated by `BatchValidateSchema`)

```json
{
  "entities": [
    { "type": "story_graph", "id": "sg_001" },
    { "type": "quest", "id": "quest_001" },
    { "type": "dialogue", "id": "dlg_001" }
  ]
}
```

---

## 3. Simulation Worker (`@hathor/simulation-worker`)

Base URL: `/api`

Default Port: 3004

Source: `apps/hathor/simulation-worker/src/`

The simulation worker processes long-running world simulation jobs in the
background. It supports economy, politics, culture, scenario, and integrated
simulation types.

### 3.1 Health & Info

| Method | Path      | Description                             |
| ------ | --------- | --------------------------------------- |
| GET    | `/health` | Health with worker count and queue size |
| GET    | `/`       | Service info including simulation types |

### 3.2 Job Management

| Method | Path                      | Description                    |
| ------ | ------------------------- | ------------------------------ |
| POST   | `/api/jobs`               | Submit a new simulation job    |
| GET    | `/api/jobs`               | List jobs (filterable)         |
| GET    | `/api/jobs/:jobId`        | Get job status and progress    |
| POST   | `/api/jobs/:jobId/cancel` | Cancel a running or queued job |
| POST   | `/api/jobs/:jobId/retry`  | Retry a failed job             |

#### Submit Job Request

```json
{
  "type": "economy",
  "input": {
    "worldId": "wld_001",
    "startDate": "1000-01-01",
    "endDate": "1010-01-01",
    "parameters": {
      "tradeFrequency": "monthly",
      "inflationRate": 0.02
    }
  },
  "priority": "normal"
}
```

**Simulation Types:** `economy`, `politics`, `culture`, `scenario`, `integrated`

#### Submit Job Response (201)

```json
{
  "jobId": "job_abc123",
  "status": "queued",
  "queuePosition": 3
}
```

#### Job List Query Parameters

| Parameter | Type   | Description                                                        |
| --------- | ------ | ------------------------------------------------------------------ |
| `status`  | string | Comma-separated: pending,queued,running,completed,failed,cancelled |
| `type`    | string | Comma-separated simulation types                                   |
| `limit`   | number | Max items (default: 20)                                            |
| `offset`  | number | Skip count (default: 0)                                            |

### 3.3 Worker Pool

| Method | Path                     | Description                    |
| ------ | ------------------------ | ------------------------------ |
| GET    | `/api/workers`           | Get all worker health statuses |
| GET    | `/api/workers/:workerId` | Get specific worker health     |

### 3.4 Statistics & Maintenance

| Method | Path           | Description                         |
| ------ | -------------- | ----------------------------------- |
| GET    | `/api/stats`   | Queue + worker aggregate statistics |
| POST   | `/api/cleanup` | Trigger cleanup of completed jobs   |
