# Hathor Domain - Architecture

> **Canonical source:** the canonical architecture document for this domain is
> [`deep-dive/architecture.md`](./deep-dive/architecture.md), rendered in the
> docs center. This file is its operational companion (service topology, APIs,
> schemas, runtime detail) — reconciled by linking, not duplicated (§2, §13).

Hathor is the worldbuilding, narrative design, and world simulation domain of
the Oshun platform. It provides a comprehensive toolkit for creating fictional
worlds with emergent behavior: domain models for every aspect of a world
(factions, economies, laws, cultures, geography, timelines, characters,
locations), narrative systems (story graphs, dialogues, quests, journals), world
simulation engines (economy, politics, culture, scenarios), NPC intelligence
powered by LLMs, lore validation, artifact compilation for game engines and film
production, and cross-domain integration with Sophia, Isis, and Yemaya.

---

## Table of Contents

1. [System Architecture Overview](#system-architecture-overview)
2. [Application Architecture](#application-architecture)
3. [Library Architecture](#library-architecture)
4. [Dependency Graph](#dependency-graph)
5. [Data Flow Diagrams](#data-flow-diagrams)
6. [Key Design Decisions](#key-design-decisions)
7. [Integration Points](#integration-points)
8. [Infrastructure Requirements](#infrastructure-requirements)

---

## System Architecture Overview

Hathor follows a layered architecture with four applications consuming thirteen
libraries. The system separates concerns into distinct API surfaces: world state
management (world-api), narrative content (narrative-api), background simulation
processing (simulation-worker), and visual management (workbench). All
applications share a common database through the `@hathor/database` Prisma layer
and communicate cross-domain via `@oshun/event-bus` (Redis Streams).

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           PRESENTATION LAYER                                │
│                                                                             │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │            @hathor/workbench (React SPA, Vite, Tailwind)            │   │
│   │   Pages: Dashboard, Worlds, Characters, Locations, Factions,        │   │
│   │          Timeline, WorldEditor                                      │   │
│   │   Services: worlds, characters, factions, locations, timeline,      │   │
│   │             dashboard, auth                                         │   │
│   └────────────────────────────┬────────────────────────────────────────┘   │
│                                │ HTTP (REST)                                │
│                                ▼                                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                             API LAYER                                       │
│                                                                             │
│   ┌──────────────────────┐  ┌──────────────────────┐                       │
│   │  @hathor/world-api   │  │ @hathor/narrative-api │                       │
│   │  Port: 3400          │  │ Port: 3003            │                       │
│   │  Hono + Zod OpenAPI  │  │ Hono + Zod Validator  │                       │
│   │                      │  │                       │                       │
│   │  /api/v1/worlds      │  │ /api/story-graphs     │                       │
│   │    - CRUD            │  │ /api/quests           │                       │
│   │    - Versioning      │  │ /api/dialogues        │                       │
│   │    - Querying        │  │ /api/validation       │                       │
│   │    - Diff/Merge      │  │                       │                       │
│   └──────────┬───────────┘  └──────────┬────────────┘                       │
│              │                         │                                    │
├──────────────┼─────────────────────────┼────────────────────────────────────┤
│              │    WORKER LAYER         │                                    │
│              │                         │                                    │
│   ┌──────────┼─────────────────────────┼──────────────────────────────┐     │
│   │  @hathor/simulation-worker                                        │     │
│   │  Port: 3004 (API for job submission)                              │     │
│   │                                                                   │     │
│   │  ┌──────────────┐ ┌────────────────┐ ┌────────────────┐         │     │
│   │  │ Economy      │ │ Politics       │ │ Culture        │         │     │
│   │  │ Worker       │ │ Worker         │ │ Worker         │         │     │
│   │  │ (markets,    │ │ (factions,     │ │ (traits,       │         │     │
│   │  │  trade,      │ │  diplomacy,    │ │  innovations,  │         │     │
│   │  │  resources)  │ │  governance)   │ │  exchanges)    │         │     │
│   │  └──────────────┘ └────────────────┘ └────────────────┘         │     │
│   │  ┌──────────────┐                                                │     │
│   │  │ Scenario     │  JobQueue -> WorkerPool -> BaseWorker          │     │
│   │  │ Worker       │  (polling loop, heartbeat, cancellation)       │     │
│   │  │ (integrated) │                                                │     │
│   │  └──────────────┘                                                │     │
│   └──────────────────────────────────────────────────────────────────┘     │
│                                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                          DOMAIN LAYER (Libraries)                           │
│                                                                             │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│   │ @hathor/     │  │ @hathor/     │  │ @hathor/     │  │ @hathor/     │  │
│   │ domain-models│  │ narrative    │  │ simulation   │  │ validation   │  │
│   │ (types for   │  │ (quest,      │  │ (economy,    │  │ (timeline,   │  │
│   │  all world   │  │  dialogue,   │  │  politics,   │  │  causality,  │  │
│   │  entities)   │  │  story graph,│  │  culture,    │  │  taxonomy,   │  │
│   │              │  │  journal,    │  │  scenario,   │  │  contradict.)│  │
│   │              │  │  export)     │  │  NPC behavior,│  │              │  │
│   │              │  │              │  │  state, phys.)│  │              │  │
│   └──────────────┘  └──────────────┘  └──────────────┘  └──────────────┘  │
│                                                                             │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│   │ @hathor/     │  │ @hathor/     │  │ @hathor/     │  │ @hathor/     │  │
│   │ llm-npc      │  │ lore-compiler│  │ theory       │  │ pre-         │  │
│   │ (personality,│  │ (Unreal,     │  │ (MDA,        │  │ production   │  │
│   │  emotion,    │  │  Unity,      │  │  narrative   │  │ (chronicle,  │  │
│   │  memory,     │  │  Godot,      │  │  theory,     │  │  storyboard, │  │
│   │  dialogue,   │  │  Fountain,   │  │  cinemato-   │  │  planning,   │  │
│   │  platforms)  │  │  FDX, PDF)   │  │  graphy)     │  │  checklists) │  │
│   └──────────────┘  └──────────────┘  └──────────────┘  └──────────────┘  │
│                                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                       INTEGRATION LAYER                                     │
│                                                                             │
│   ┌──────────────────┐  ┌────────────────────┐  ┌────────────────────┐     │
│   │ @hathor/sophia-  │  │ @hathor/event-      │  │ @hathor/event-     │     │
│   │ integration      │  │ handlers            │  │ publisher          │     │
│   │ (citation,       │  │ (sophia.document,   │  │ (world.created,    │     │
│   │  research,       │  │  isis.asset,        │  │  world.published,  │     │
│   │  lore validation)│  │  yemaya.project,    │  │  element.added,    │     │
│   │                  │  │  yemaya.character)  │  │  narrative.gen,    │     │
│   │                  │  │                     │  │  simulation.*)     │     │
│   └──────────────────┘  └────────────────────┘  └────────────────────┘     │
│                                                                             │
│   ┌──────────────────┐                                                      │
│   │ @hathor/client   │  TypeScript SDK (worlds, narratives, simulations)    │
│   └──────────────────┘                                                      │
│                                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                        DATA LAYER                                           │
│                                                                             │
│   ┌────────────────────────────┐  ┌────────────────────────────────────┐   │
│   │  @hathor/database          │  │  Redis (via @oshun/event-bus)       │   │
│   │  PostgreSQL + Prisma ORM   │  │  - Event bus (Redis Streams)       │   │
│   │  - Worlds, entities        │  │  - Simulation job queues           │   │
│   │  - Story graphs, quests    │  │  - Rate limit state                │   │
│   │  - Dialogue trees          │  │  - Simulation state cache          │   │
│   │  - Simulation runs         │  │                                    │   │
│   │  - Version control         │  │                                    │   │
│   │  - Audit logs              │  │                                    │   │
│   └────────────────────────────┘  └────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Application Architecture

### @hathor/world-api (Port 3400)

The central API for world state management. Built with Hono, it provides REST
endpoints for creating and managing worlds, entities, versions, and merge
operations. This is the primary entry point for world data.

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

```
world-api/src/
  app.ts               # Hono app with middleware stack
  index.ts             # Server entry, event bus init, graceful shutdown
  types.ts             # Request/response type definitions
  middleware/
    rate-limit.ts      # Rate limiting (100 req/min per IP)
  routes/
    worlds.ts          # World CRUD (/api/v1/worlds)
    versions.ts        # Version management (/api/v1/worlds/:id/versions)
    query.ts           # Entity queries (/api/v1/worlds/:id/query, /search)
    merge.ts           # Diff/merge (/api/v1/worlds/:id/diff, /merge-requests)
  schemas/             # Zod schemas for request validation
  services/
    world.service.ts        # World CRUD and state management
    version.service.ts      # Version control for worlds
    query.service.ts        # World state queries
    world-graph.service.ts  # Graph-based world relationships
    merge.service.ts        # Branch merging with conflict detection
  utils/               # Utility functions
```

**Middleware stack:** `secureHeaders` -> `cors` -> `logger` -> `prettyJSON` ->
`rateLimit` (on `/api/*`)

**CORS origins:** `http://localhost:3000`, `http://localhost:5173` (workbench
dev server)

**Key architectural note:** The world-api initializes cross-domain event
handlers at startup. It creates an `@oshun/event-bus` connection, then calls
`setupHathorEventHandlers` from `@hathor/event-handlers` with a consumer group
(`hathor-world-api`). This allows it to react to events from Sophia, Isis, and
Yemaya domains.

**Event bus configuration:**

- Source domain: `hathor`
- Key prefix: `oshun:events`
- Persistence: enabled (24-hour TTL)
- Retry: exponential backoff (3 attempts, 1s-30s)
- Dead letter: enabled (7-day retention, 1000 entries)

---

### @hathor/narrative-api (Port 3003)

Manages narrative content: story graphs, quests, dialogues, and narrative
validation. Separate from the world-api to allow independent scaling of
narrative workloads.

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

```
narrative-api/src/
  app.ts               # Hono app configuration
  index.ts             # Server entry point
  types.ts             # Type definitions
  middleware/           # Middleware
  routes/              # Route handlers
  schemas/             # Zod validation schemas
  services/
    story-graph.service.ts   # Branching narrative graphs
    dialogue.service.ts      # Dialogue trees with conditions/effects
    quest.service.ts         # Quest definitions with objectives
    validation.service.ts    # Cross-reference lore validation
```

**API routes:**

| Route               | Purpose                             |
| ------------------- | ----------------------------------- |
| `/api/story-graphs` | Story graph CRUD and traversal      |
| `/api/quests`       | Quest definition and state tracking |
| `/api/dialogues`    | Dialogue tree management            |
| `/api/validation`   | Lore consistency validation         |

---

### @hathor/simulation-worker (Port 3004)

Background worker process for running world simulations. Provides a job queue,
worker pool, and an HTTP API for job submission and monitoring.

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

```
simulation-worker/src/
  app.ts                     # Hono app with createApp factory
  index.ts                   # Server entry, environment config
  api/
    routes.ts                # HTTP API for job submission/monitoring
    worker-pool.ts           # Worker pool management
  jobs/                      # Job type definitions
  queue/
    job-queue.ts             # In-memory job queue with polling
  types/                     # Type definitions
  workers/
    base-worker.ts           # Abstract base worker class
    economy-worker.ts        # Economy simulation worker
    politics-worker.ts       # Politics simulation worker
    culture-worker.ts        # Culture simulation worker
    scenario-worker.ts       # Integrated scenario worker
```

**Worker architecture:**

All workers extend `BaseWorker`, which provides:

- Simulation loop with configurable tick intervals (hour, day, week, month,
  year)
- Heartbeat monitoring and health reporting
- Job processing lifecycle (initialize -> executeTick -> takeSnapshot ->
  compileOutput -> cleanup)
- Cancellation via `AbortController` (workers check `signal.aborted` each tick)
- Memory and uptime tracking

**Worker pool:**

The `WorkerPool` manages multiple worker instances. The number of workers per
type is configurable via environment variables:

| Variable           | Default | Purpose                    |
| ------------------ | ------- | -------------------------- |
| `ECONOMY_WORKERS`  | 1       | Number of economy workers  |
| `POLITICS_WORKERS` | 1       | Number of politics workers |
| `CULTURE_WORKERS`  | 1       | Number of culture workers  |
| `SCENARIO_WORKERS` | 1       | Number of scenario workers |

**HTTP API:**

| Method | Path                   | Purpose                 |
| ------ | ---------------------- | ----------------------- |
| POST   | `/api/jobs`            | Submit a simulation job |
| GET    | `/api/jobs`            | List all jobs           |
| GET    | `/api/jobs/:id`        | Get job status          |
| POST   | `/api/jobs/:id/cancel` | Cancel a running job    |
| GET    | `/api/workers`         | Get worker pool status  |
| GET    | `/api/stats`           | Get queue statistics    |

---

### @hathor/workbench (Vite SPA)

React-based single-page application for visual worldbuilding. Provides a
graphical interface for managing worlds, entities, narratives, and simulations.

**Source:** `apps/hathor/workbench/src/`

```
workbench/src/
  App.tsx              # Root component with routing
  main.tsx             # Application entry point
  index.css            # Global styles (Tailwind)
  api/
    client.ts          # HTTP client for API calls
    types.ts           # API type definitions
    mock-data.ts       # Mock data for offline development
    services/
      auth-service.ts       # Authentication
      worlds-service.ts     # World management
      characters-service.ts # Character management
      factions-service.ts   # Faction management
      locations-service.ts  # Location management
      timeline-service.ts   # Timeline management
      dashboard-service.ts  # Dashboard aggregations
  components/          # Reusable UI components
  context/             # React contexts
  hooks/               # Custom React hooks
  pages/
    Dashboard.tsx      # Overview dashboard
    Worlds.tsx         # World listing and creation
    WorldEditor.tsx    # World detail editor
    Characters.tsx     # Character management
    Factions.tsx       # Faction management
    Locations.tsx      # Location management
    Timeline.tsx       # Timeline visualization
  test/                # Test setup and utilities
```

**Technology:**

- **Framework:** React 18 with React Router DOM 6
- **Build:** Vite 5
- **Styling:** Tailwind CSS 3
- **Data fetching:** TanStack Query 5
- **State management:** Zustand 4
- **Icons:** Lucide React
- **Code highlighting:** Highlight.js
- **HTML sanitization:** DOMPurify

---

## Library Architecture

The 13 libraries are organized into four architectural layers:

### Layer 1: Data Foundation

| Library            | Package                | Purpose                                          |
| ------------------ | ---------------------- | ------------------------------------------------ |
| `@hathor/database` | `libs/hathor/database` | Prisma schema, generated client, database access |

The database library is the foundation of all data access. It provides the
Prisma client, connection management (`getHathorClient`, `createHathorClient`,
`disconnectHathorClient`), raw query execution, and transaction support. All
type definitions for database records are exported from here.

### Layer 2: Domain Models and Logic

| Library                  | Package                      | Dependencies                                                       | Purpose                                    |
| ------------------------ | ---------------------------- | ------------------------------------------------------------------ | ------------------------------------------ |
| `@hathor/domain-models`  | `libs/hathor/domain-models`  | (standalone)                                                       | Type definitions for all world aspects     |
| `@hathor/narrative`      | `libs/hathor/narrative`      | `@hathor/domain-models`                                            | Story graphs, dialogues, quests, export    |
| `@hathor/simulation`     | `libs/hathor/simulation`     | `@hathor/domain-models`                                            | Economy, politics, culture, scenarios      |
| `@hathor/validation`     | `libs/hathor/validation`     | `@hathor/domain-models`                                            | Lore consistency validation                |
| `@hathor/llm-npc`        | `libs/hathor/llm-npc`        | `@hathor/domain-models`                                            | LLM-powered NPC intelligence               |
| `@hathor/theory`         | `libs/hathor/theory`         | (standalone)                                                       | MDA, narrative theory, cinematography      |
| `@hathor/lore-compiler`  | `libs/hathor/lore-compiler`  | `@hathor/domain-models`, `@hathor/narrative`, `@hathor/simulation` | Engine/film artifact compilation           |
| `@hathor/pre-production` | `libs/hathor/pre-production` | (standalone)                                                       | Chronicle parsing, storyboarding, planning |

### Layer 3: Integration

| Library                      | Package                          | Dependencies             | Purpose                              |
| ---------------------------- | -------------------------------- | ------------------------ | ------------------------------------ |
| `@hathor/sophia-integration` | `libs/hathor/sophia-integration` | (Sophia domain services) | Research grounding for worldbuilding |
| `@hathor/event-handlers`     | `libs/hathor/event-handlers`     | `@oshun/event-bus`       | Inbound cross-domain events          |
| `@hathor/event-publisher`    | `libs/hathor/event-publisher`    | `@oshun/event-bus`       | Outbound cross-domain events         |

### Layer 4: Client SDK

| Library          | Package              | Dependencies | Purpose                                |
| ---------------- | -------------------- | ------------ | -------------------------------------- |
| `@hathor/client` | `libs/hathor/client` | (standalone) | TypeScript SDK for world/narrative/sim |

---

## Dependency Graph

```
                         ┌──────────────────┐
                         │ @hathor/database  │
                         │ (Prisma, types)   │
                         └────────┬─────────┘
                                  │
                    ┌─────────────┼─────────────┐
                    │             │              │
                    ▼             ▼              ▼
          ┌─────────────┐ ┌──────────────┐ ┌──────────────┐
          │  @hathor/    │ │   (direct    │ │   (direct    │
          │ domain-models│ │    DB use    │ │    DB use    │
          │ (all world   │ │    by apps)  │ │    by apps)  │
          │  types)      │ │              │ │              │
          └──┬──┬──┬──┬──┘ └──────────────┘ └──────────────┘
             │  │  │  │
     ┌───────┘  │  │  └───────────────┐
     │          │  │                  │
     ▼          ▼  ▼                  ▼
┌──────────┐ ┌──────────┐     ┌──────────────┐
│ @hathor/ │ │ @hathor/ │     │  @hathor/     │
│ narrative│ │simulation│     │  validation   │
│          │ │          │     │              │
└────┬─────┘ └────┬─────┘     └──────────────┘
     │            │
     │   ┌────────┘
     │   │
     ▼   ▼
┌─────────────────┐                ┌──────────────┐
│ @hathor/        │                │  @hathor/     │
│ lore-compiler   │                │  llm-npc      │
│ (domain-models, │                │ (domain-models│
│  narrative,     │                │  + LLM APIs)  │
│  simulation)    │                └──────────────┘
└─────────────────┘

                                   ┌──────────────┐
                                   │ @hathor/      │
                                   │ theory        │
                                   │ (standalone)  │
                                   └──────────────┘

                                   ┌──────────────┐
                                   │ @hathor/      │
                                   │ pre-production│
                                   │ (standalone)  │
                                   └──────────────┘

INTEGRATION:
┌───────────────────┐  ┌────────────────────┐  ┌───────────────────┐
│ @hathor/sophia-   │  │ @hathor/event-     │  │ @hathor/event-    │
│ integration       │  │ handlers           │  │ publisher         │
│ (external: Sophia)│  │ (@oshun/event-bus) │  │ (@oshun/event-bus)│
└───────────────────┘  └────────────────────┘  └───────────────────┘

CLIENT:
┌───────────────────┐
│ @hathor/client    │
│ (HTTP transport,  │
│  standalone)      │
└───────────────────┘

APPLICATION DEPENDENCIES:
┌─────────────────────────────────────────────────────────────┐
│ world-api         -> @hathor/event-handlers                  │
│                   -> @hathor/event-publisher                  │
│                   -> @oshun/event-bus                         │
│                   -> Hono, @hono/node-server, @hono/zod-openapi │
│                                                              │
│ narrative-api     -> Hono, @hono/node-server, @hono/zod-validator │
│                                                              │
│ simulation-worker -> @hathor/simulation                       │
│                   -> Hono, @hono/node-server                  │
│                                                              │
│ workbench         -> React, React Router, TanStack Query,    │
│                      Zustand, Tailwind, Vite                 │
└─────────────────────────────────────────────────────────────┘
```

---

## Data Flow Diagrams

### World Creation and Versioning

```
User (Workbench)          world-api                  Database
     │                        │                          │
     │  POST /api/v1/worlds   │                          │
     │  {name, genre, scope,  │                          │
     │   technologyLevel, ... }│                          │
     │───────────────────────>│                          │
     │                        │  world.service.ts        │
     │                        │  create world record     │
     │                        │─────────────────────────>│
     │                        │                          │
     │                        │  version.service.ts      │
     │                        │  create initial version  │
     │                        │  create main branch      │
     │                        │─────────────────────────>│
     │                        │                          │
     │                        │  event-publisher          │
     │                        │  emit world.created ──────┼──> Redis Streams
     │                        │                          │       │
     │  201 {world, version}  │                          │       │
     │<───────────────────────│                          │       │
     │                        │                          │       │
     │                        │                          │       ▼
     │                        │                          │  Other domains
     │                        │                          │  (Sophia, Isis,
     │                        │                          │   Yemaya listen)
```

### Simulation Execution

```
Client              simulation-worker              Database        Redis
  │                      │                            │              │
  │  POST /api/jobs      │                            │              │
  │  {type: "economy",   │                            │              │
  │   worldId, input}    │                            │              │
  │─────────────────────>│                            │              │
  │                      │  JobQueue.enqueue()        │              │
  │  202 {jobId}         │                            │              │
  │<─────────────────────│                            │              │
  │                      │                            │              │
  │                      │  WorkerPool matches job    │              │
  │                      │  to EconomyWorker          │              │
  │                      │                            │              │
  │                      │  worker.initialize()       │              │
  │                      │───────────────────────────>│              │
  │                      │  (load world state)        │              │
  │                      │                            │              │
  │                      │  ┌─── TICK LOOP ──────────────────────┐  │
  │                      │  │ executeTick(job, N, date, signal)  │  │
  │                      │  │   -> calculate markets, trade      │  │
  │                      │  │   -> generate events               │  │
  │                      │  │   -> update metrics                │  │
  │                      │  │                                    │  │
  │                      │  │ if N % snapshotInterval == 0:      │  │
  │                      │  │   takeSnapshot(job, N)             │  │
  │                      │  │   -> capture state ───────────────>│  │
  │                      │  │                                    │  │
  │                      │  │ if signal.aborted: BREAK           │  │
  │                      │  └────────────────────────────────────┘  │
  │                      │                            │              │
  │                      │  compileOutput()           │              │
  │                      │───────────────────────────>│              │
  │                      │  (save SimulationRun,      │              │
  │                      │   Events, Snapshots)       │              │
  │                      │                            │              │
  │  GET /api/jobs/:id   │                            │              │
  │─────────────────────>│                            │              │
  │  200 {status: done,  │                            │              │
  │       output: {...}} │                            │              │
  │<─────────────────────│                            │              │
```

### Cross-Domain Event Flow

```
External Domains                    Hathor Event Handlers           Hathor Services
                                         │
Sophia                                   │
  sophia.document.ingested ──────────────>│
  {documentId, topics, entities}         │  sophia-document-ingested.ts
                                         │  -> Extract entities from document
                                         │  -> Link to world lore
                                         │  -> Update world entity graph
                                         │
Isis                                     │
  isis.asset.generated ──────────────────>│
  {assetId, type, worldId, entityId}     │  isis-asset-generated.ts
                                         │  -> Link generated asset to entity
                                         │  -> Update entity properties
                                         │
Yemaya                                   │
  yemaya.project.created ────────────────>│
  {projectId, worldId}                   │  yemaya-project-created.ts
                                         │  -> Sync project with world state
                                         │  -> Create world reference
                                         │
  yemaya.character.created ──────────────>│
  {characterId, worldId, properties}     │  yemaya-character-created.ts
                                         │  -> Create CHARACTER entity
                                         │  -> Build relationships
                                         │
                                         │
Hathor Event Publisher ──────────────────> External Domains
  hathor.world.created                    │
  hathor.world.published                  │  -> Sophia: index world knowledge
  hathor.element.added                    │  -> Isis: generate assets
  hathor.narrative.generated              │  -> Yemaya: update project state
  hathor.simulation.started               │
  hathor.simulation.completed             │
  hathor.world.validated                  │
```

### Lore Compilation Pipeline

```
Source Content               Lore Compiler               Output Artifacts
                                  │
Narrative (story graph, ─────────>│
  quests, dialogues)              │
                                  │  Quest Compiler
Domain Models (world ────────────>│  ┌─────────────────────────┐
  entities, factions,             │  │ Unreal Engine .uasset   │
  timelines)                      │  │ Unity .asset            │
                                  │  │ Godot .tres             │
Simulation Data ─────────────────>│  │ Blender data blocks     │
  (economy state,                 │  └─────────────────────────┘
   political state)               │
                                  │  Screenplay Compiler
                                  │  ┌─────────────────────────┐
                                  │  │ Fountain (.fountain)    │
                                  │  │ Final Draft (.fdx)      │
                                  │  │ PDF                     │
                                  │  └─────────────────────────┘
                                  │
                                  │  Bellona Package Builder
                                  │  ┌─────────────────────────┐
                                  │  │ Cross-engine interchange│
                                  │  │ packages for Bellona     │
                                  │  │ build engine domain     │
                                  │  └─────────────────────────┘
```

### NPC Dialogue Generation

```
Game Client              @hathor/llm-npc                     LLM Providers
     │                        │                                    │
     │  generateDialogue(     │                                    │
     │    npcId, context)     │                                    │
     │───────────────────────>│                                    │
     │                        │  PersonalityManager                │
     │                        │  -> Get Big Five traits            │
     │                        │  -> Get Enneagram type             │
     │                        │  -> Get speech patterns            │
     │                        │                                    │
     │                        │  EmotionalStateManager             │
     │                        │  -> Get current emotional state    │
     │                        │  -> Apply context transitions      │
     │                        │                                    │
     │                        │  MemorySystem                      │
     │                        │  -> Recall relevant memories       │
     │                        │  -> Working memory attention       │
     │                        │                                    │
     │                        │  WorldAwarenessManager             │
     │                        │  -> Get spatial context            │
     │                        │  -> Get world knowledge            │
     │                        │                                    │
     │                        │  ProviderChain (failover)          │
     │                        │───────────────────────────────────>│
     │                        │  Provider 1: LLMClient (OpenAI)    │
     │                        │  Provider 2: NVIDIAAceClient       │
     │                        │  Provider 3: InworldClient         │
     │                        │  Provider 4: ConvaiClient          │
     │                        │                                    │
     │                        │  SafetyFilter                      │
     │                        │  -> Content safety check           │
     │                        │  -> Lore consistency check         │
     │                        │  -> Fourth-wall detection          │
     │                        │                                    │
     │  {dialogue, emotion,   │                                    │
     │   actions, memory}     │                                    │
     │<───────────────────────│                                    │
```

---

## Key Design Decisions

### 1. Separate API Surfaces

**Decision:** World management, narrative content, and simulation processing are
split across three independent server applications (world-api, narrative-api,
simulation-worker).

**Rationale:** Simulation workloads are CPU-intensive and long-running (minutes
to hours). Separating them into a dedicated worker prevents simulation jobs from
blocking world or narrative API requests. The narrative API handles different
query patterns (graph traversal, dialogue session state) than the world API
(CRUD, versioning, search). Independent deployment and scaling is possible.

### 2. Git-Like Versioning for Worlds

**Decision:** Worlds support branches, versions, and merge requests analogous to
Git repositories.

**Rationale:** Worldbuilding is inherently collaborative and exploratory.
Authors need to experiment with "what if" scenarios (branches), compare states
(diffs), and merge changes from different contributors (merge requests). The
versioning system uses `WorldVersion` records with parent-child chains and
`Branch` records with a designated main branch.

### 3. Entity-Relationship Model with JSON Properties

**Decision:** All world objects (characters, factions, locations, events, items,
cultures, religions) are stored as `Entity` records with a polymorphic `type`
field and type-specific data in a `properties` JSON column.

**Rationale:** This provides a flexible, queryable graph without requiring a
separate table per entity type. The `EntityRelation` model captures typed,
weighted, optionally bidirectional relationships between any entities. Full-text
search is supported via a `searchVector` tsvector column.

### 4. Behavior Trees for NPC AI

**Decision:** NPC behavior uses a full behavior tree implementation (composites,
decorators, leaf nodes) rather than finite state machines.

**Rationale:** Behavior trees are more composable and maintainable than FSMs for
complex NPC behavior. The implementation includes standard patterns
(`createPatrolBehavior`, `createFleeBehavior`, `createAttackBehavior`) and
advanced nodes (cooldown, timeout, guard, retry). A shared `Blackboard` provides
state communication between nodes.

### 5. Multi-Provider LLM Architecture

**Decision:** The `@hathor/llm-npc` library uses a `ProviderChain` with circuit
breaker failover across multiple LLM providers (generic LLM/OpenAI, NVIDIA ACE,
Inworld AI, Convai).

**Rationale:** NPC dialogue generation is a critical real-time path. A single
provider failure must not break the experience. The provider chain monitors
health, tracks statistics, and automatically fails over to the next provider.
Different providers offer different strengths (NVIDIA ACE for facial animation,
Inworld AI for game-specific features, generic LLM for flexibility).

### 6. Event-Driven Cross-Domain Communication

**Decision:** Hathor communicates with other domains (Sophia, Isis, Yemaya)
exclusively through an event bus (`@oshun/event-bus` backed by Redis Streams),
not direct API calls.

**Rationale:** Loose coupling between domains allows independent development and
deployment. Events are persistent (24-hour TTL), retryable (exponential
backoff), and have dead letter support. Consumer groups ensure each event is
processed exactly once per consumer.

### 7. Workbench as Standalone SPA

**Decision:** The workbench is a standalone React SPA (Vite build) that
communicates with Hathor APIs via HTTP, rather than being server-rendered or
integrated into the API servers.

**Rationale:** The workbench is a rich, interactive application (world graphs,
timeline visualizations, entity editors) that benefits from client-side
rendering and state management. Separating it from the API layer allows
independent development and potentially different deployment targets (desktop
via Electron, embedded in other tools).

---

## Integration Points

### Inbound (Events Consumed by Hathor)

| Event                      | Source | Payload                          | Handler Action                         |
| -------------------------- | ------ | -------------------------------- | -------------------------------------- |
| `sophia.document.ingested` | Sophia | documentId, topics, entities     | Extract entities, link to world lore   |
| `isis.asset.generated`     | Isis   | assetId, type, worldId, entityId | Link generated asset to world entity   |
| `yemaya.project.created`   | Yemaya | projectId, worldId               | Synchronize project with world state   |
| `yemaya.character.created` | Yemaya | characterId, worldId, properties | Create CHARACTER entity in world graph |

### Outbound (Events Published by Hathor)

| Event                         | Payload                             | Consumers            |
| ----------------------------- | ----------------------------------- | -------------------- |
| `hathor.world.created`        | worldId, name, genre, scope         | Sophia, Yemaya       |
| `hathor.world.published`      | worldId, version                    | Sophia, Isis         |
| `hathor.element.added`        | worldId, entityId, entityType, name | Isis, Yemaya         |
| `hathor.narrative.generated`  | worldId, narrativeId, type          | Yemaya               |
| `hathor.simulation.started`   | worldId, simulationId, type         | (monitoring)         |
| `hathor.simulation.completed` | worldId, simulationId, results      | Yemaya, (monitoring) |
| `hathor.world.validated`      | worldId, isValid, issues            | (monitoring)         |

### Sophia Integration (Direct Service Calls)

The `@hathor/sophia-integration` library provides direct integration with Sophia
knowledge services for research-grounded worldbuilding:

| Service                    | Purpose                                               |
| -------------------------- | ----------------------------------------------------- |
| `CitationService`          | Link world lore to research sources via Sophia search |
| `ResearchGroundingService` | Generate world content grounded in research knowledge |
| `LoreValidationService`    | Fact-check world lore against Sophia research corpus  |

The `HathorSophiaIntegration` unified client exposes convenience methods:
`cite`, `verify`, and `ground`.

### Bellona Integration (Compile-Time)

The lore compiler (`@hathor/lore-compiler`) produces packages for the Bellona
build engine domain via the Bellona Package Builder. This is a compile-time
integration, not a runtime API call. Compiled packages are interchange artifacts
that Bellona can consume for cross-engine builds.

### Client SDK

The `@hathor/client` TypeScript SDK provides external consumers with typed
access to all Hathor APIs:

| Resource             | Operations                                                  |
| -------------------- | ----------------------------------------------------------- |
| `WorldResource`      | CRUD, versioning, branching, entity management, merge       |
| `NarrativeResource`  | Story graphs, quests, dialogues (list/create/update/delete) |
| `SimulationResource` | Submit jobs, query status, retrieve results                 |

Features include `HttpTransport` with auth headers and timeouts, a comprehensive
error hierarchy, branded ID types, pagination support, and helper functions for
world state analysis.

---

## Infrastructure Requirements

### Required Services

| Service    | Port(s) | Purpose                                       |
| ---------- | ------- | --------------------------------------------- |
| PostgreSQL | 5432    | Primary database (Hathor schema via Prisma)   |
| Redis      | 6379    | Event bus, job queues, simulation state cache |

### Optional Services

| Service | Port(s)    | Purpose                                    |
| ------- | ---------- | ------------------------------------------ |
| Neo4j   | 7687, 7474 | Knowledge graph for world entity relations |

### Environment Variables

| Variable              | Default                                                         | Used By            |
| --------------------- | --------------------------------------------------------------- | ------------------ |
| `HATHOR_DATABASE_URL` | `postgresql://oshun:oshun_dev@localhost:5432/hathor`            | `@hathor/database` |
| `REDIS_URL`           | `redis://localhost:6379`                                        | Event bus, queues  |
| `PORT`                | `3400` (world-api), `3003` (narrative-api), `3004` (sim-worker) | API servers        |
| `HOST`                | `0.0.0.0`                                                       | API servers        |
| `NEO4J_URL`           | `bolt://localhost:7687`                                         | Knowledge graph    |
| `ECONOMY_WORKERS`     | `1`                                                             | Simulation worker  |
| `POLITICS_WORKERS`    | `1`                                                             | Simulation worker  |
| `CULTURE_WORKERS`     | `1`                                                             | Simulation worker  |
| `SCENARIO_WORKERS`    | `1`                                                             | Simulation worker  |

### Docker Setup

```bash
# Start core infrastructure (PostgreSQL + Redis)
docker compose -f docker/docker-compose.dev.yml up -d

# Optional: Neo4j for world entity graphs
docker compose -f docker/docker-compose.dev.yml --profile graph up -d
```

### Database Setup

```bash
# Generate Prisma client
pnpm nx run @hathor/database:prisma:generate

# Apply migrations
cd libs/hathor/database && npx prisma migrate dev

# Seed data
cd libs/hathor/database && npx tsx prisma/seed.ts
```

### Running All Services

```bash
# Start all four applications (in separate terminals or via process manager)
pnpm nx serve @hathor/world-api           # Port 3400
pnpm nx serve @hathor/narrative-api       # Port 3003
pnpm nx serve @hathor/simulation-worker   # Port 3004
pnpm nx dev @hathor/workbench             # Port 5173 (Vite dev server)
```

### Build and Test

```bash
# Build all Hathor projects
pnpm nx run-many --target=build --projects=tag:scope:hathor

# Test all Hathor projects
pnpm nx run-many --target=test --projects=tag:scope:hathor

# Lint all Hathor projects
pnpm nx run-many --target=lint --projects=tag:scope:hathor
```
