# Hathor Domain — Architecture

> Worldbuilding, Narrative Design, and World Simulation Platform

Hathor is the creative worldbuilding platform within the Oshun monorepo. Its
purpose is to give writers, game designers, and production teams a single,
structured environment for designing fictional worlds and bringing them to life.
A world author works in the visual Workbench, models factions, economies, and
lore using the domain libraries, runs background simulations to watch the world
evolve, and finally exports the results as engine-native assets for game engines
or industry-standard formats for film production.

The domain spans **17 libraries** and **7 applications** covering world
modeling, narrative systems, simulation engines, LLM-powered NPC intelligence,
lore validation, lore compilation, game design theory, pre-production tooling,
the Veilborn Chronicles game services, and cross-domain integration.

Hathor is a creative pipeline: worlds are designed in the Workbench, populated
via the domain model libraries, simulated in the background worker, and exported
to game engines and film production tools through the lore compiler and Bellona
integration.

---

## 1. System Overview

### Core Responsibilities

- **World Modeling** — Engine-agnostic domain types for factions, economies,
  laws, cultures, geography, timelines, characters, and locations
- **Narrative Systems** — Quest design, branching dialogue, non-linear story
  graphs, journal/codex, and narrative export
- **World Simulation** — Economy, politics, culture, and scenario simulation
  with NPC behavior trees and physics
- **NPC Intelligence** — LLM-powered personality, emotion, memory, world
  awareness, dialogue generation, and multi-platform AI integration
- **Lore Validation** — Timeline, causality, taxonomy, and contradiction
  checking
- **Lore Compilation** — Engine-native artifact generation for Unreal, Unity,
  Godot, Blender, and film formats
- **Theory and Pre-Production** — MDA framework, narrative theory,
  cinematography planning, chronicle parsing, storyboarding, and project
  management
- **Cross-Domain Integration** — Event-driven integration with Sophia, Isis,
  Yemaya, and Bellona

---

## 2. Service Architecture

### 2.1 Applications

The core worldbuilding work is spread across three Hono HTTP services plus a
React SPA. The diagram below shows how they connect to each other and to the
shared PostgreSQL database.

```
                     @hathor/workbench
                     (React SPA, Vite)
                            |
               +------------+------------+
               |                         |
    +----------v---------+  +------------v-----------+
    |   @hathor/world-api |  | @hathor/narrative-api  |
    |   (Hono, Port 3001) |  | (Hono, Port 3002)      |
    |                     |  |                        |
    | - World CRUD        |  | - Story graph CRUD     |
    | - Branch management |  | - Quest CRUD           |
    | - Version control   |  | - Dialogue CRUD        |
    | - Merge requests    |  | - Runtime sessions     |
    | - Query engine      |  | - Narrative validation |
    | - Collaborators     |  +------------------------+
    +----------+----------+
               |
    +----------v-------------------+
    |  @hathor/simulation-worker   |
    |  (Hono, Port 3004)           |
    |                              |
    | Background simulation jobs:  |
    | - Economy simulation         |
    | - Politics simulation        |
    | - Culture simulation         |
    | - Scenario generation        |
    | - Full world simulation      |
    +----------+-------------------+
               |
    +----------v----------+
    |  @hathor/database    |
    |  PostgreSQL          |
    |  (Prisma, no schema  |
    |   namespace)         |
    +---------------------+
```

The diagram above shows the three Hono worldbuilding services and the database.
Three further applications sit alongside them: the `@hathor/workbench` React
SPA, the `@hathor/studio-web` content-map package, and the two Veilborn
Chronicles Fastify game services (`@hathor/veilborn-core`,
`@hathor/veilborn-strategy`) — see § 2.2.

### 2.2 Application Details

#### `@hathor/world-api` (Port 3001)

Hono-based HTTP API server for world state management. This is the primary
persistence boundary for world data: all world CRUD, versioning, branching,
merge requests, entity management, and the query engine flow through this
service.

- **Framework:** Hono with `@hono/zod-validator` validation
- **Dependencies:** `@oshun/event-bus`, `@hathor/event-handlers`,
  `@hathor/event-publisher`
- **Auth:** `X-User-ID` header forwarded from API gateway
- **Rate limit:** 100 req/min per IP on `/api/*` routes

#### `@hathor/narrative-api` (Port 3002)

Hono-based HTTP API server for narrative resources. While the World API owns
world structure and entities, the Narrative API owns the storytelling layer:
story graphs, quests, dialogues, journal entries, and narrative validation.

- **Framework:** Hono with `@hono/zod-validator`
- **Key feature:** Runtime dialogue sessions with state tracking

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

Background worker process for running world simulations. Rather than blocking
the World API, long-running simulation jobs are submitted here and processed
asynchronously by a configurable worker pool. The worker reports progress via
ticks and publishes a completion event when done.

- **Concurrency:** Configurable worker pool with health monitoring
- **Job types:** economy, politics, culture, scenario, integrated
- **State:** PostgreSQL for job records, Redis for state caching

#### `@hathor/workbench` (React SPA)

React-based single-page application for visual worldbuilding. Provides a browser
UI that covers the most common world design workflows without requiring SDK or
API knowledge. Seven primary pages: Dashboard, Worlds, World Editor, Characters,
Factions, Locations, Timeline.

- **Technology:** React 18, React Router DOM, TanStack Query, Zustand, Tailwind
  CSS, Lucide React, Highlight.js, DOMPurify
- **Build:** Vite

#### `@hathor/veilborn-core` (`apps/hathor/svc-veilborn-core`)

Fastify service implementing the core game engine for **Veilborn Chronicles**, a
tabletop RPG and wargame. This application demonstrates Hathor's capabilities as
a game engine, not just an authoring tool. Built on `@lilith/fastify-core` and
`@lilith/service-lib`. The HTTP surface exposes health/readiness/metrics
endpoints; the game systems are ~30 fully tested domain-logic modules under
`src/` (hex-grid combat, character creation, abilities, cards, dice, seeded
procedural world generation, wargame, AI, social, persistence).

#### `@hathor/veilborn-strategy` (`apps/hathor/svc-veilborn-strategy`)

Fastify service implementing the "The Veil War" strategic game mode of Veilborn
Chronicles. REST API for game management, state queries with fog-of-war, action
submission, and save/load snapshots, plus optional `@fastify/websocket`
real-time sync and JWT auth. Five game modes (Echoes of Fate, Resonance Wars,
Weave Conspiracy, Eternal Game, Grand Campaign) each have their own engine, AI
opponent, and route module, alongside a balance pipeline.

#### `@hathor/studio-web` (`apps/hathor/studio-web`)

Small package defining the V2 fighting-game narrative content map (narrative
surfaces, content packs, beats, and compiled-artifact plans). Depends only on
`@hathor/lore-compiler`. Not an HTTP server.

---

## 3. Library Architecture

### 3.1 Layer Overview

Libraries follow a strict layered architecture to enforce unidirectional
dependencies. The data layer sits at the bottom; integration and client layers
sit at the top. Domain libraries may not import from the integration or client
layers, which keeps the core world model testable in isolation.

```
Data layer:
  @hathor/database            — Prisma client and schema

Domain layer (core data):
  @hathor/domain-models       — Engine-agnostic world type system

Domain layer (systems):
  @hathor/narrative           — Quest, dialogue, story graph, journal, export
  @hathor/simulation          — Economy, politics, culture, scenario, NPC behavior, physics
  @hathor/validation          — Timeline, causality, taxonomy, contradiction checking
  @hathor/llm-npc             — LLM-powered NPC brain, dialogue, behavior, platforms
  @hathor/theory              — MDA framework, narrative theory, cinematography
  @hathor/pre-production      — Chronicle parsing, storyboarding, project mgmt, virtual production
  @hathor/lore-compiler       — Engine/film artifact compilation

Façade layer (cross-domain / CGI adapters):
  @hathor/characters          — CGI character-definition import facade
  @hathor/world               — CGI scene-definition import facade
  @hathor/timeline            — Narrative scene-order facade
  @hathor/quests              — Scene-dependency / story-arc capture facade

Integration layer:
  @hathor/sophia-integration  — Research grounding via Sophia
  @hathor/event-handlers      — Incoming event subscriptions
  @hathor/event-publisher     — Outgoing event publishing

Client layer:
  @hathor/client              — TypeScript SDK
```

The full library roster (17 total): `database`, `domain-models`, `narrative`,
`simulation`, `validation`, `llm-npc`, `theory`, `pre-production`,
`lore-compiler`, `characters`, `world`, `timeline`, `quests`,
`sophia-integration`, `event-handlers`, `event-publisher`, `client`.

### 3.2 Library Descriptions

#### `@hathor/database`

Prisma-based database schema and client for Hathor. This library is the single
source of truth for all persisted world data. It provides lifecycle management
(`getHathorClient`, `createHathorClient`, `disconnectHathorClient`), database
operations, and comprehensive TypeScript type definitions mirroring the schema
(all enums, status types, entity types — available without code generation).

**Tags:** `scope:hathor`, `layer:data`

#### `@hathor/domain-models`

Engine-agnostic worldbuilding domain models providing comprehensive type
definitions for every aspect of a fictional world. This library deliberately has
no runtime dependencies — it is pure TypeScript types, constants, factories, and
validators that any other library or application can import without pulling in
database or HTTP concerns.

| Category     | Contents                                             |
| ------------ | ---------------------------------------------------- |
| `common/`    | Base types, branded IDs, shared enums                |
| `faction/`   | Faction structures, hierarchies, relationships       |
| `economy/`   | Resources, trade routes, markets, currencies, guilds |
| `law/`       | Legal systems, codes, enforcement structures         |
| `culture/`   | Cultural traits, traditions, customs, art forms      |
| `geography/` | Terrain, climate, biomes, natural features           |
| `timeline/`  | Historical events, eras, chronological ordering      |
| `character/` | Character definitions, attributes, backstories       |
| `location/`  | Places, settlements, buildings, dungeons, realms     |

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/narrative`

Engine-agnostic narrative systems with five subsystems. The library is
intentionally separate from `@hathor/domain-models` because narrative structures
(quest state machines, dialogue sessions, story graph traversal) carry runtime
behaviour, not just type definitions.

| Subsystem       | Description                                                                |
| --------------- | -------------------------------------------------------------------------- |
| Quest System    | Objectives, rewards, prerequisites, branching, state tracking              |
| Dialogue System | Tree authoring with speaker attribution, conditions, variable substitution |
| Story Graph     | Non-linear graph with typed nodes, arcs, state transitions                 |
| Journal/Codex   | In-game journal and codex systems with discovery tracking                  |
| Export System   | Export to Ink, Yarn Spinner, and JSON interchange                          |

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/simulation`

The largest library in the Hathor domain, providing four simulation managers, an
NPC behavior tree system, state persistence, and a physics engine. Each
simulation manager owns a distinct slice of world dynamics so they can run
independently or be composed into a full integrated simulation.

- **Economy:** `EconomyManager` — markets, resources, trade routes, currencies,
  guilds
- **Politics:** `PoliticsManager` — factions, leaders, alliances, conflicts,
  treaties, elections
- **Culture:** `CultureManager` — trait evolution, cultural contacts,
  innovations, subcultures
- **Scenario:** `ScenarioManager` — configurable scenario generation with
  timelines and templates
- **NPC Behavior:** Full behavior tree (leaf, composite, decorator nodes) with
  `BehaviorTreeBuilder` and common patterns
- **State Persistence:** `SimulationStateStore` with in-memory, PostgreSQL, and
  Redis backends
- **Physics:** `PhysicsEngine` with rigid bodies, colliders, constraints, force
  fields, raycasting, and presets

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/llm-npc`

Comprehensive LLM-powered NPC system. The library is organized into four modules
— brain, dialogue, behavior, and platform integrations — so that the cognitive
model (personality, emotion, memory) is decoupled from the specific AI platform
used to generate speech.

**Brain Module:**

- `PersonalityManager` — Big Five + Enneagram type system + BDI model
- `EmotionalStateManager` — Real-time emotional state tracking
- `MemorySystem` — Short-term and long-term memory with consolidation
- `WorldAwarenessManager` — Spatial awareness and world knowledge

**Dialogue Module:**

- `DialogueGenerator` — Real-time dialogue from personality, emotion, context
- `SafetyFilter` — Content safety and lore consistency guardrails

**Behavior Module:**

- `BehaviorController` — Goal-driven scheduling with GOAP and HTN
- `NPCConversationManager` — Multi-NPC autonomous conversation management

**Platform Integrations:**

- `LLMClient` (generic OpenAI-compatible)
- `NVIDIAAceClient` (NVIDIA ACE with blendshapes, Riva, Audio2Face)
- `InworldClient` (sessions, triggers, knowledge, goals)
- `ConvaiClient` (sessions, actions, face data, function calls)

**Provider Chain:** `ProviderChain` with circuit breakers and automatic failover
across the above platforms.

**Tags:** `scope:hathor`, `layer:domain`, `type:lib`

#### `@hathor/validation`

Four-layer lore validation engine. Each validator targets a specific class of
consistency problem; `createLoreValidator()` composes all four into a single
combined pass.

| Validator              | Factory                       | Checks                                                      |
| ---------------------- | ----------------------------- | ----------------------------------------------------------- |
| Timeline               | `createTimelineValidator`     | Chronological order, era boundaries, lifespan consistency   |
| Causality              | `createCausalityValidator`    | Temporal consistency, cycle detection                       |
| Taxonomy               | `createTaxonomyValidator`     | Type checking, hierarchy validation                         |
| Contradiction detector | `createContradictionDetector` | Temporal, spatial, attribute, relationship, state conflicts |

Combined: `createLoreValidator()` runs all four checks and produces a unified
`LoreValidationResult`.

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/theory`

Three integrated theory subsystems that bring academic frameworks for game
design and storytelling into the authoring pipeline.

- **MDA Framework:** `MDAManager` — mechanics, dynamics, aesthetics analysis
  with feedback loops, flow analysis, and experience evaluation
- **Narrative Theory:** `NarrativeManager` — fabula/syuzhet, pacing, beat
  sheets, character arc templates, structure templates (Hero's Journey, Three
  Act, Five Act, Kishōtenketsu)
- **Cinematography:** `CinematographyManager` — shot design, composition,
  lighting, color, rhythm, continuity

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/pre-production`

Pre-production tools that help a team move from a written world document into a
production-ready plan.

- **Scriptwriting:** Chronicle parser with era/event headings, speaker
  attribution, diagnostic reporting; narrative structure analysis with template
  adherence scoring
- **Storyboard:** `StoryboardManager` for visual planning with frames,
  sequences, layers, camera specs, transitions, character placement, exports,
  timeline linking
- **Planning:** a `ProjectManager` for worldbuilding project management (phases,
  milestones, tasks, dependencies, built-in checklists, project health) **plus**
  a large library of virtual-production / on-set systems (~240 `*-system.ts` and
  `drone-*` modules: drone choreography and safety, virtual sets, LED-wall
  ICVFX, relighting, motion capture, switching, color, and continuity), each
  with a matching test file

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/lore-compiler`

Compiles narrative content into engine-ready and film-ready artifacts. This
library is the bridge between the world-as-data (stored in Hathor) and
world-as-executable-artifact (consumed by game engines and Bellona).

| Compiler                      | Targets                              | Description                                 |
| ----------------------------- | ------------------------------------ | ------------------------------------------- |
| Quest Compiler (`engine/`)    | Unreal Engine, Unity, Godot, Blender | Engine-specific format compilation          |
| Screenplay Compiler (`film/`) | Fountain, FDX, PDF                   | Industry-standard screenplay formats        |
| Bellona Package Builder       | Cross-engine                         | Interchange packages for the Bellona domain |

**Tags:** `scope:hathor`, `layer:domain`

#### `@hathor/sophia-integration`

Direct integration layer between Hathor and the Sophia research domain. Sophia
owns a large corpus of indexed documents and a knowledge graph; this library
gives Hathor access to that corpus so that world lore can be grounded in
real-world research rather than invented wholesale.

- `CitationService` — Link world lore to research sources via Sophia search
- `ResearchGroundingService` — Generate world content grounded in researched
  knowledge
- `LoreValidationService` — Fact-check world lore against Sophia's research
  corpus

**Tags:** `scope:hathor`, `layer:domain`

#### Façade libraries (`@hathor/characters`, `@hathor/world`, `@hathor/timeline`, `@hathor/quests`)

Four thin façade libraries adapt Hathor domain types for cross-domain (CGI /
production) consumption. Each façade exports metadata, a packet builder, a
validator, and a serializer. The façade boundary exists because CGI pipelines
(e.g., a VFX pipeline consuming character definitions) need a stable, minimal
interface — not the full richness of the internal domain model.

- `@hathor/characters` — CGI character-definition import facade; maps
  `Character` records into a CGI character packet (appearance, costume designs,
  visual references). Depends on `@hathor/domain-models` and
  `@hathor/pre-production`.
- `@hathor/world` — CGI scene-definition import facade. Depends on
  `@hathor/domain-models`.
- `@hathor/timeline` — narrative scene-order facade (story-order vs. shoot-order
  reconciliation, causal-dependency checking, world-state continuity). Depends
  on `@hathor/domain-models`.
- `@hathor/quests` — scene-dependency / story-arc capture facade. Depends on
  `@hathor/narrative`.

#### `@hathor/event-handlers`

Handles incoming events from Sophia, Isis, and Yemaya using `@oshun/event-bus`.
`setupHathorEventHandlers` initializes all subscriptions with consumer group
support, logging, and graceful shutdown.

**Tags:** `scope:hathor`, `type:lib`, `layer:integration`

#### `@hathor/event-publisher`

Type-safe event publisher for all Hathor domain events. Singleton pattern:
`getHathorEventPublisher` / `createHathorEventPublisher`.

The following event payload types are published:

- `HathorWorldCreatedPayload`
- `HathorWorldPublishedPayload`
- `HathorElementAddedPayload`
- `HathorNarrativeGeneratedPayload`
- `HathorSimulationStartedPayload`
- `HathorSimulationCompletedPayload`
- `HathorWorldValidatedPayload`

**Tags:** `scope:hathor`, `type:lib`, `layer:integration`

#### `@hathor/client`

TypeScript SDK for the Hathor HTTP APIs. Provides `WorldResource`,
`NarrativeResource`, and `SimulationResource` with pagination, a comprehensive
error hierarchy, branded ID types, and helper functions.

**Tags:** `scope:hathor`, `layer:clients`

---

## 4. Data Flow

The following flows trace a world's lifecycle through the Hathor pipeline.

### 4.1 World Creation and Editing Flow

A world begins as an API call from the Workbench or any SDK client. Each entity
change produces a new immutable `WorldVersion` record, and a domain event is
published so downstream consumers (such as analytics) can react.

```
Workbench / API Client
        |
        v
world-api (POST /api/v1/worlds)
        |
        +-- Create World record in PostgreSQL
        +-- Create initial WorldVersion (v1, main branch)
        |
        v
Entity operations (addEntity, updateEntity, removeEntity)
        |
        +-- Update Entity table in PostgreSQL
        +-- Create new WorldVersion (with changes delta)
        |
        v
hathor.element.added event  ─────────────>  Event consumers (analytics)
```

### 4.2 Branching and Merge Flow

The branching model mirrors git: branches diverge from a specific version and
can be merged back via a merge request. Conflicts must be resolved individually
before the merge can be executed.

```
world-api POST /branches
        |
        +-- Create Branch record (branchPointVersionId = current)
        |
entity changes on branch
        |
        +-- WorldVersion records linked to Branch
        |
POST /merge-requests
        |
        +-- Diff source and target versions
        +-- Identify conflicts (same entity, different changes)
        |
POST /merge-requests/:mrId/conflicts/resolve
        |
        +-- Record resolution per conflict (source / target / custom)
        |
POST /merge-requests/:mrId/merge
        |
        +-- Apply resolved changes
        +-- Create new WorldVersion on target branch
        +-- Set MergeRequest status = MERGED
```

### 4.3 Simulation Flow

Simulation jobs are decoupled from the World API. An external trigger (an API
call or a Yemaya event) submits a job to the simulation worker, which processes
it asynchronously and publishes a completion event when finished. The separation
keeps the World API responsive while long-running simulations run in the
background.

```
API Client / Event (yemaya.build.requested)
        |
        v
simulation-worker POST /api/jobs
        |
        +-- Create SimulationRun record (PENDING)
        +-- Enqueue job in worker pool
        |
        v
Worker picks up job
        |
        +-- Load world state from PostgreSQL
        +-- Run simulation ticks:
        |       Economy: EconomyManager
        |       Politics: PoliticsManager
        |       Culture: CultureManager
        |       Scenario: ScenarioManager
        |
        +-- Emit SimulationEvents per tick
        +-- Save SimulationSnapshot at intervals
        +-- Update progress on SimulationRun
        |
        v
SimulationRun.status = COMPLETED
        |
        v
Publish: hathor.simulation.completed
```

### 4.4 Lore Compilation Flow

When a world is published, both Hathor and Bellona act on the event. Hathor's
`@hathor/lore-compiler` produces compiled intermediate artifacts; Bellona's own
integration library then converts those into engine-native project assets.

```
Publish: hathor.world.published
        |
        v
@hathor/event-handlers (Bellona handles this too)
        |
        v
@hathor/lore-compiler (QuestCompiler, ScreenplayCompiler, BellonaPackageBuilder)
        |
        +-- Compile quests, dialogues, NPCs into engine-native format:
        |       Unreal: Blueprints + DataTables
        |       Unity:  C# ScriptableObjects
        |       Godot:  GDScript + Resources
        |
        v
Bellona package: world data + quest data + dialogue data + manifest
        |
        v
Bellona domain consumes package for engine project generation
```

---

## 5. Key Design Patterns

### 5.1 Layered Domain Architecture

Libraries are organized in strict layers (data → domain → integration → client)
to enforce unidirectional dependencies. Domain libraries do not import from
integration or client layers. This means the pure world model
(`@hathor/domain-models`, `@hathor/narrative`, `@hathor/simulation`) can be
tested without any HTTP, database, or event-bus dependencies in scope.

### 5.2 Factory Functions Throughout

All managers and services expose factory functions (`createEconomyManager`,
`createPoliticsManager`, `createLoreValidator`, etc.) rather than requiring
direct instantiation. This enables dependency injection and clean testing
without having to subclass or monkey-patch anything.

### 5.3 JSON Properties for Polymorphic Entities

The `Entity` table uses a `properties: Json` field for type-specific data rather
than per-type tables. This enables the world model to accommodate all 10 entity
types (and custom types) without schema migrations when new types are added.
Type-specific validation is handled in `@hathor/domain-models` validators rather
than at the database level.

### 5.4 Git-Like Version Model

The versioning model mirrors git: `WorldVersion` records form a parent-child
chain (commits), `Branch` records track named development lines, and
`MergeRequest` tracks the review and merge workflow. `isCurrent` on
`WorldVersion` marks the HEAD of each branch. This model makes it safe to
experiment with alternative world timelines (e.g. "what if the empire never
fell?") without losing the main world state.

### 5.5 Behavior Tree Composability

The NPC behavior tree system follows the standard behavior tree pattern with
leaf (Action, Condition), composite (Sequence, Selector, Parallel), and
decorator (Inverter, Repeater, Timeout, etc.) nodes. The `BehaviorTreeBuilder`
provides a fluent API for constructing trees without manual node wiring. Trees
are serializable so their execution state can be saved and restored across
simulation ticks.

### 5.6 Provider Chain with Circuit Breaker

The `@hathor/llm-npc` `ProviderChain` implements the circuit breaker pattern
across multiple AI platform clients. When a provider fails a configurable number
of times in a row, its circuit opens and traffic fails over to the next healthy
provider automatically. This makes the NPC system resilient to third-party AI
platform outages.

---

## 6. Technology Stack

| Layer             | Technology                                    |
| ----------------- | --------------------------------------------- |
| Language          | TypeScript (ESM)                              |
| API Framework     | Hono with Zod OpenAPI validation              |
| Database          | PostgreSQL via Prisma ORM (`hathor` schema)   |
| Event Bus         | `@oshun/event-bus` (Kafka)                    |
| Frontend          | React 18, Vite, TanStack Query, Zustand       |
| Build (libraries) | `@nx/js:tsc` (most), `nx:run-commands` (some) |
| Testing           | Vitest                                        |

### Technology Rationale

- **Hono** chosen for the World API for its lightweight footprint, native Zod
  OpenAPI integration, and TypeScript-first design
- **JSON `properties` field** on Entity enables flexible entity models without
  schema migrations as new world element types are introduced
- **Redis for simulation state** caching enables low-latency state access across
  simulation ticks without hitting PostgreSQL on every tick
- **`nx:run-commands`** used for libraries (`@hathor/llm-npc`, `@hathor/client`)
  that require custom build steps beyond standard TypeScript compilation

---

## 7. Project Structure

The Hathor file tree below maps each directory to its library or application.

```
apps/hathor/
  world-api/             # World state, versioning, branching, query engine (Hono, 3001)
  narrative-api/         # Story graphs, quests, dialogues, validation (Hono, 3002)
  simulation-worker/     # Background world simulation jobs (Hono, 3004)
  workbench/             # React SPA for visual worldbuilding
  studio-web/            # V2 fighting-game narrative content map
  svc-veilborn-core/     # Veilborn Chronicles core game engine (Fastify)
  svc-veilborn-strategy/ # Veilborn "The Veil War" strategy game (Fastify)

libs/hathor/
  client/              # TypeScript SDK
  database/            # Prisma schema and generated client
  domain-models/       # Engine-agnostic world type system
  event-handlers/      # Cross-domain event subscriptions
  event-publisher/     # Outgoing event publishing
  llm-npc/             # LLM-powered NPC intelligence
  narrative/           # Quest, dialogue, story graph, journal, export
  pre-production/      # Chronicle parsing, storyboarding, project mgmt, virtual production
  simulation/          # Economy, politics, culture, scenario, NPC behavior, physics
  sophia-integration/  # Research grounding via Sophia
  theory/              # MDA framework, narrative theory, cinematography
  validation/          # Lore consistency validation
  lore-compiler/       # Engine and film artifact compilation
  characters/          # CGI character-definition import facade
  world/               # CGI scene-definition import facade
  timeline/            # Narrative scene-order facade
  quests/              # Scene-dependency / story-arc capture facade
```

---

## 8. Cross-Domain Dependencies

Hathor both consumes from and publishes to other Oshun domains. Understanding
these boundaries matters because they determine which side owns a given piece of
data and which side must wait for an event.

### Why These Boundaries Exist

- **Sophia → Hathor:** Sophia owns the research corpus and knowledge graph.
  Hathor cannot replicate that data, so it calls Sophia synchronously for
  citation lookups and subscribes to document-ingestion events so new research
  can flow into world lore automatically.
- **Isis → Hathor:** Isis owns asset generation (AI-generated images, concept
  art). When Isis produces an asset, Hathor links it to the corresponding world
  entity — Hathor does not generate assets itself.
- **Yemaya → Hathor:** Yemaya is the creative studio management domain. When a
  new project or character is created there, Hathor needs to know so it can
  create or update the corresponding world record.
- **Hathor → Bellona:** Bellona owns game engine project generation. Hathor
  publishes a `world.published` event with compiled artifacts; Bellona consumes
  it to build engine-native project assets. The boundary is at the compiled
  artifact — Hathor does not know about Bellona's engine project format.

### Upstream Events Consumed

| Domain | Event                      | Handler                  | Effect                               |
| ------ | -------------------------- | ------------------------ | ------------------------------------ |
| Sophia | `sophia.document.ingested` | `@hathor/event-handlers` | Incorporate research into world lore |
| Isis   | `isis.asset.generated`     | `@hathor/event-handlers` | Link generated assets to entities    |
| Yemaya | `yemaya.project.created`   | `@hathor/event-handlers` | Sync creative projects with worlds   |
| Yemaya | `yemaya.character.created` | `@hathor/event-handlers` | Incorporate characters into world    |

### Downstream Events Produced

| Domain  | Event consumed           | How consumed                                       |
| ------- | ------------------------ | -------------------------------------------------- |
| Bellona | `hathor.world.published` | Triggers engine project generation and compilation |
| Yemaya  | `hathor.world.created`   | Surfaces world to creative studio                  |

### Sophia Direct Integration

`@hathor/sophia-integration` calls Sophia's search API directly (not via events)
for citation search, lore fact-checking, and research grounding operations that
require synchronous responses. The event subscription handles asynchronous
document ingestion; the direct API call handles interactive "check this fact
now" workflows.

### Shared Oshun Libraries Used

| Library            | Usage                                   |
| ------------------ | --------------------------------------- |
| `@oshun/event-bus` | Kafka event publishing and subscription |
| `@oshun/logging`   | Structured logging across all apps      |
