# Hathor Domain

> **Hathor** - Worldbuilding, Narrative Design, and World Simulation Platform

Hathor is a comprehensive worldbuilding and narrative design platform providing
everything needed to create, simulate, validate, and export interactive worlds.
Named after the Egyptian goddess of love, beauty, and the arts, the domain spans
13 libraries and 4 applications covering: domain models for factions, economies,
laws, cultures, geography, timelines, characters, and locations; a Prisma-backed
database with versioning and branching; narrative systems for quests, dialogues,
story graphs, and journals; simulation engines for economy, politics, culture,
and scenarios with NPC behavior trees and physics; LLM-powered NPC intelligence
with personality, emotion, memory, and multi-platform integration (NVIDIA ACE,
Inworld AI, Convai); lore validation with timeline, causality, taxonomy, and
contradiction checking; a lore compiler targeting game engines (Unreal, Unity,
Godot) and film production (Fountain, FDX); game design and narrative theory
frameworks; pre-production tooling for storyboarding and project planning;
cross-domain event integration; a TypeScript client SDK; and a React-based
workbench application.

---

## Architecture

```
                         @hathor/database
                    (Prisma client, schema, types)
                              |
                     @hathor/domain-models
            (faction, economy, law, culture, geography,
             timeline, character, location models)
                    /         |          \
                   /          |           \
        @hathor/narrative  @hathor/simulation  @hathor/validation
        (quest, dialogue,  (economy, politics,  (timeline, causality,
         story graph,       culture, scenario,   taxonomy, contradiction)
         journal, export)   NPC behavior,
                            state, physics)
              |                    |                    |
              v                    v                    v
      @hathor/lore-compiler   @hathor/llm-npc      @hathor/theory
      (engine artifacts,      (personality,         (MDA framework,
       screenplay,             emotion, memory,      narrative theory,
       Bellona packages)       dialogue, platforms)   cinematography)
                    \          |          /
                     \         |         /
               @hathor/pre-production
              (chronicle parser, storyboard,
               project planning, checklists)
                              |
                @hathor/sophia-integration
              (citation, research grounding,
               lore fact-checking via Sophia)
                              |
          @hathor/event-publisher  @hathor/event-handlers
          (domain event output)   (Sophia, Isis, Yemaya input)
                              |
                      @hathor/client
                   (TypeScript SDK for APIs)

     APPLICATIONS:
     world-api | narrative-api | simulation-worker | workbench
```

---

## Libraries (13)

### Core Data Layer

#### `@hathor/database` - Prisma Database Layer

Prisma-based database schema and client for Hathor world simulation services.
Provides the persistence layer for worlds, entities, story graphs, quests,
dialogues, simulations, and audit logs.

**Key exports:**

- `getHathorClient`, `createHathorClient`, `disconnectHathorClient` -- Prisma
  client lifecycle management
- `connect`, `transaction`, `executeRaw`, `queryRaw` -- Database operations
- Comprehensive type definitions mirroring the Prisma schema, available without
  code generation: `WorldStatus` (DRAFT/ACTIVE/ARCHIVED/DELETED), `WorldGenre`
  (8 genres including FANTASY, SCIENCE_FICTION, HISTORICAL, MYTHOLOGY),
  `WorldScope` (SMALL through COSMIC), `TechnologyLevel` (9 levels from
  PRIMITIVE to ADVANCED), `MagicLevel`, `EntityType` (10 types: CHARACTER,
  FACTION, LOCATION, EVENT, RELATIONSHIP, ERA, REGION, ITEM, CULTURE, RELIGION),
  `CharacterStatus`, `FactionType`, `LocationType`, `QuestStatus`,
  `QuestCategory`, `QuestPriority`, `ObjectiveType`, `StoryNodeType`,
  `DialogueNodeType`, `SimulationType`, `SimulationStatus`,
  `MergeRequestStatus`, `ValidationSeverity`

**Tags:** `scope:hathor`, `layer:data` **Build:** `@nx/js:tsc`

---

#### `@hathor/domain-models` - Engine-Agnostic World Models

Engine-agnostic worldbuilding domain models providing comprehensive type
definitions for every aspect of a fictional world.

**Domain model categories:**

| Category     | Description                                          |
| ------------ | ---------------------------------------------------- |
| `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` **Build:** `@nx/js:tsc`

---

### Narrative Systems

#### `@hathor/narrative` - Interactive Narrative Engine

Engine-agnostic narrative systems for game and interactive fiction development.
Provides five integrated subsystems for building story-driven experiences.

**Subsystems:**

| System                        | Description                                                                                                   |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Quest System (`quest/`)       | Quest design with objectives, rewards, prerequisites, branching paths, and state tracking                     |
| Dialogue System (`dialogue/`) | Dialogue tree authoring with speaker attribution, branching choices, conditions, and variable substitution    |
| Story Graph (`story-graph/`)  | Non-linear story graph with nodes (START, SCENE, CHOICE, CONDITION, ACTION, END), arcs, and state transitions |
| Journal/Codex (`journal/`)    | In-game journal and codex systems for lore entries, discovered knowledge, and player notes                    |
| Export System (`export/`)     | Export to Ink (Inkle), Yarn Spinner, and JSON interchange formats                                             |

**Tags:** `scope:hathor`, `layer:domain` **Build:** `@nx/js:tsc`

---

#### `@hathor/lore-compiler` - Engine and Film Artifact Compiler

Lore compiler that generates engine-ready and film-ready artifacts from
narrative content. Bridges the gap between worldbuilding design and production
implementation.

**Compilers:**

| Compiler                             | Targets                              | Description                                                              |
| ------------------------------------ | ------------------------------------ | ------------------------------------------------------------------------ |
| Quest Compiler (`engine/`)           | Unreal Engine, Unity, Godot, Blender | Compiles quests into engine-specific formats with native data structures |
| Screenplay Compiler (`film/`)        | Fountain, FDX (Final Draft), PDF     | Compiles stories into industry-standard screenplay formats               |
| Bellona Package Builder (`bellona/`) | Cross-engine                         | Creates interchange packages for the Bellona build engine domain         |

**Example:**

```typescript
const questCompiler = createQuestCompiler({ targetEngine: 'unreal' });
const result = questCompiler.compile(sourceQuest);

const screenplayCompiler = createScreenplayCompiler();
const screenplay = screenplayCompiler.compile(sourceStory);
const fountain = screenplayCompiler.export(screenplay.artifact!, 'fountain');
```

---

### Simulation Engines

#### `@hathor/simulation` - World Simulation Engine

Massive simulation library providing four domain-specific simulation managers,
an NPC behavior tree system, state persistence with PostgreSQL and Redis
backends, and a physics engine. This is the largest library in the Hathor
domain.

**Economy Simulation:**

`EconomyManager` with `createEconomyManager` factory. Simulates markets,
resources, trade routes, currencies, guilds, and trade agreements. Features
price calculation, event generation, trade analysis, and economic snapshots.
Branded ID types: `MarketId`, `TradeRouteId`, `ResourceId`, `CurrencyId`,
`GuildId`. Storage providers for resources, markets, trade routes, guilds,
agreements, events, and snapshots.

**Politics Simulation:**

`PoliticsManager` with `createPoliticsManager` factory. Simulates factions,
leaders, alliances, conflicts, treaties, policies, and elections. Features
relations calculation, conflict resolution, succession handling, and power
analysis. Types cover government types, faction ideologies, leader
personalities, alliance obligations, battle records, and political events.

**Culture Evolution Simulation:**

`CultureManager` with `createCultureManager` factory. Simulates cultural trait
evolution, cultural contacts and exchanges, innovations, subcultures, cultural
phases, and influence networks. Features drift calculation, similarity analysis,
diffusion simulation, and phase transitions. Extensive type system with trait
transmission mechanisms, adoption stages, and resilience analysis.

**Scenario Generator:**

`ScenarioManager` with `createScenarioManager` factory. Generates and advances
world scenarios with configurable technology levels, magic levels, conflict
intensity, geography, and climate. Supports timelines, templates, interventions,
and scenario analysis (power balance, economic outlook, cultural trends,
conflict risk projections).

**NPC Behavior System:**

Complete behavior tree implementation with composable node types:

- **Leaf nodes:** `ActionNode`, `ConditionNode`
- **Composite nodes:** `SequenceNode`, `SelectorNode`, `ParallelNode`,
  `RandomSelectorNode`
- **Decorator nodes:** `InverterNode`, `SucceederNode`, `FailerNode`,
  `RepeaterNode`, `RetryNode`, `LimiterNode`, `TimeoutNode`, `CooldownNode`,
  `GuardNode`
- **Builder:** `BehaviorTreeBuilder`, `BT` factory, `buildTree`
- **Common patterns:** `createPatrolBehavior`, `createFleeBehavior`,
  `createAttackBehavior`, `createIdleBehavior`
- **Blackboard:** Shared state container for behavior tree execution

**State Persistence:**

`SimulationStateStore` with in-memory, PostgreSQL, and Redis backends. Supports
snapshots, domain-specific state stores (`DomainStateStores`), serialization
formats, and cache key management (`buildStateCacheKey`, `buildWorldCacheKey`,
`buildDomainCacheKey`).

**Physics Engine:**

`PhysicsEngine` with `createPhysicsEngine` factory and presets
(`createEarthPhysics`, `createMoonPhysics`, `createZeroGPhysics`). Supports
rigid bodies, colliders (box, sphere, capsule, cylinder, plane, heightmap),
constraints (distance, hinge, ball socket, slider, fixed), force fields
(gravity, wind, buoyancy, drag, explosion, vortex), collision detection with
contact points and manifolds, raycasting, and sphere casting. Includes a full 3D
math library (`Vec2`, `Vec3`, `Quat`, `AABBOps`, `TransformOps`).

**Tags:** `scope:hathor`, `layer:domain` **Build:** `@nx/js:tsc`

---

#### `@hathor/llm-npc` - LLM-Powered NPC Intelligence

Comprehensive LLM-powered NPC system providing personality, emotion, memory,
world awareness, dialogue generation, behavior control, and multi-platform
integration with state-of-the-art AI techniques.

**Brain Module:**

| Component               | Description                                                   |
| ----------------------- | ------------------------------------------------------------- |
| `PersonalityManager`    | Big Five personality model with speech pattern customization  |
| `EmotionalStateManager` | Real-time emotional state tracking and transitions            |
| `MemorySystem`          | Short-term and long-term memory with recall and consolidation |
| `WorldAwarenessManager` | Spatial awareness, location tracking, world knowledge         |

**Dialogue Module:**

| Component           | Description                                                          |
| ------------------- | -------------------------------------------------------------------- |
| `DialogueGenerator` | Real-time dialogue generation from personality, emotion, and context |
| `SafetyFilter`      | Content safety filters and guardrails for generated dialogue         |

**Behavior Module:**

| Component                | Description                                               |
| ------------------------ | --------------------------------------------------------- |
| `BehaviorController`     | Goal-driven behavior with scheduling and state management |
| `NPCConversationManager` | NPC-to-NPC autonomous conversation management             |

**Platform Integrations:**

| Platform    | Client            | Description                                                 |
| ----------- | ----------------- | ----------------------------------------------------------- |
| Generic LLM | `LLMClient`       | OpenAI-compatible API with local model support              |
| NVIDIA ACE  | `NVIDIAAceClient` | NVIDIA Avatar Cloud Engine with blendshape facial animation |
| Inworld AI  | `InworldClient`   | Inworld AI sessions, triggers, and character states         |
| Convai      | `ConvaiClient`    | Convai sessions, actions, and face data                     |

**Provider Chain:** `ProviderChain` with circuit breaker patterns, health
monitoring, failover, and provider statistics. Factory functions:
`createStandardProviderChain`, `createGameProviderChain`.

**Advanced SOTA Features:**

- **Personality SOTA:** Enneagram type system (wings, tritypes), BDI model
  (Beliefs, Desires, Intentions), personality drift, faction affiliations
- **Memory SOTA:** Working memory with attention weighting, memory consolidation
  with configurable strategies
- **Dialogue SOTA:** Topic tracking, dialogue act classification, sentiment
  analysis, appropriateness scoring, character consistency checking, fourth-wall
  detection, lore consistency checking, manipulation detection
- **Behavior SOTA:** GOAP (Goal-Oriented Action Planning) with world state, task
  decomposition (HTN), failure recovery, resource gathering, item manipulation
- **Platform SOTA:** NVIDIA Nemo customization, Riva streaming, Audio2Face
  real-time config, Inworld knowledge entries and goals, Convai function calls
  and guardrails, multi-NPC conversation orchestration

**Tags:** `scope:hathor`, `layer:domain`, `type:lib` **Build:**
`nx:run-commands`

---

### Validation and Theory

#### `@hathor/validation` - Lore Validation Engine

Four-layer validation engine for ensuring worldbuilding lore consistency. The
`LoreValidator` class combines all validators into a single pass with
configurable fail-fast behavior and per-category issue limits.

**Validators:**

| Validator     | Factory                       | Description                                                          |
| ------------- | ----------------------------- | -------------------------------------------------------------------- |
| Timeline      | `createTimelineValidator`     | Chronological order, era boundaries, lifespan consistency            |
| Causality     | `createCausalityValidator`    | Temporal consistency of cause-effect chains, cycle detection         |
| Taxonomy      | `createTaxonomyValidator`     | Type checking, hierarchy validation, custom type definitions         |
| Contradiction | `createContradictionDetector` | Temporal, spatial, attribute, relationship, and state contradictions |

**Combined validator:** `createLoreValidator()` runs all four checks and
produces a unified `LoreValidationResult` with severity-classified issues (info,
warning, error), validator run list, and timing data.

**Dependency:** `@hathor/domain-models` (imports `HistoricalEvent`, `Era`,
`Timeline`, `CharacterId`, `FactionId`, `LocationId`)

**Tags:** `scope:hathor`, `layer:domain` **Build:** `@nx/js:tsc`

---

#### `@hathor/theory` - Game Design and Narrative Theory

Three integrated theory subsystems for game design analysis, narrative
structure, and cinematography planning.

**MDA Framework (Mechanics-Dynamics-Aesthetics):**

`MDAManager` with `createMDAManager` factory. Implements the formal game design
framework for analyzing game mechanics, emergent dynamics, and player
aesthetics. Features feedback loop analysis, dynamics simulation, flow analysis,
and experience evaluation. Includes mechanic templates and the standard MDA
aesthetics catalog.

**Narrative Theory:**

`NarrativeManager` with `createNarrativeManager` factory. Story structure
analysis using fabula/syuzhet decomposition, dramatic irony tracking, pacing
analysis, beat sheet generation, and character arc templates. Structure
templates cover Hero's Journey, Three Act, Five Act, Kishōtenketsu, and more.

**Cinematography:**

`CinematographyManager` with `createCinematographyManager` factory. Shot design
with type, angle, movement, lens, and focus specifications. Composition analysis
using rule of thirds, golden ratio, leading lines, and framing. Lighting setup
design, color palette analysis, rhythm analysis, and continuity checking.
Reference databases for shot types, camera angles, movements, lighting setups,
and color scheme effects.

**Tags:** `scope:hathor`, `layer:domain` **Build:** `@nx/js:tsc`

---

### Pre-Production

#### `@hathor/pre-production` - Pre-Production Tooling

Pre-production tools for worldbuilding and lore development, covering document
parsing, narrative structure analysis, visual storyboarding, and project
planning.

**Subsystems:**

| System                           | Description                                                                                                                                                                                                                                                                                                          |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Scriptwriting (`scriptwriting/`) | Chronicle document parser with era headings, event headings, speaker attribution, sections, document references, title pages. Inline formatting support. Diagnostic reporting. Narrative structure analysis with built-in templates (Epic Journey, Chronicle, Rise and Fall). Pacing analysis and adherence scoring. |
| Storyboard (`storyboard/`)       | `StoryboardManager` for visual planning with frames, sequences, layers, camera specs, transitions, character placement, props, effects, and text overlays. Export support. Timeline linking.                                                                                                                         |
| Planning (`planning/`)           | `ProjectManager` for worldbuilding project management with phases, milestones, tasks, dependencies, and progress tracking. Built-in checklists for character creation, location creation, faction creation, event planning, magic systems, and world overviews. Project health calculation.                          |

**Tags:** `scope:hathor`, `layer:domain` **Build:** `@nx/js:tsc`

---

### Integration Layer

#### `@hathor/sophia-integration` - Sophia Knowledge Integration

Integration layer between Hathor world simulation and Sophia knowledge services
for research-grounded worldbuilding.

**Services:**

| Service                    | Description                                                                                             |
| -------------------------- | ------------------------------------------------------------------------------------------------------- |
| `CitationService`          | Link world lore to research sources via Sophia's search index. Creates and verifies citations.          |
| `ResearchGroundingService` | Generate world content grounded in researched knowledge. Discovers entities and suggests relationships. |
| `LoreValidationService`    | Fact-check world lore against Sophia's research corpus. Validates individual facts and batch lore.      |

**Unified client:** `HathorSophiaIntegration` combines all three services with
convenience methods (`cite`, `verify`, `ground`).

**Tags:** `scope:hathor`, `layer:domain` **Build:** `@nx/js:tsc`

---

#### `@hathor/event-handlers` - Cross-Domain Event Subscriptions

Handles incoming events from Sophia, Isis, and Yemaya domains to build and
maintain coherent narrative worlds.

**Subscriptions:**

| Event                      | Source | Handler                                          |
| -------------------------- | ------ | ------------------------------------------------ |
| `sophia.document.ingested` | Sophia | Incorporates research documents into world lore  |
| `isis.asset.generated`     | Isis   | Links generated assets to world entities         |
| `yemaya.project.created`   | Yemaya | Synchronizes creative projects with world state  |
| `yemaya.character.created` | Yemaya | Incorporates new characters into the world graph |

`setupHathorEventHandlers` initializes all subscriptions with consumer group
support, logging, and graceful shutdown. Uses `@oshun/event-bus` for transport.

**Tags:** `scope:hathor`, `type:lib`, `layer:integration` **Build:**
`nx:run-commands`

---

#### `@hathor/event-publisher` - Domain Event Publishing

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

**Published events:**

- `HathorWorldCreatedPayload` -- new world created
- `HathorWorldPublishedPayload` -- world published
- `HathorElementAddedPayload` -- entity added to world
- `HathorNarrativeGeneratedPayload` -- narrative content generated
- `HathorSimulationStartedPayload` / `HathorSimulationCompletedPayload` --
  simulation lifecycle
- `HathorWorldValidatedPayload` -- validation results

**Tags:** `scope:hathor`, `type:lib`, `layer:integration` **Build:**
`@nx/js:tsc`

---

### Client SDK

#### `@hathor/client` - TypeScript Client SDK

TypeScript SDK for interacting with Hathor's HTTP APIs. Provides unified access
to World, Narrative, and Simulation APIs.

**API Resources:**

| Resource             | Description                                                          |
| -------------------- | -------------------------------------------------------------------- |
| `WorldResource`      | World CRUD, versioning, branching, entity management, merge requests |
| `NarrativeResource`  | Story graphs, quests, dialogues with list/create/update/delete       |
| `SimulationResource` | Submit simulation jobs, query status, retrieve results               |

**Features:**

- `HttpTransport` with configurable base URL, auth headers, timeouts
- Comprehensive error hierarchy: `HathorError`, `NetworkError`, `TimeoutError`,
  `AbortError`, `NotFoundError`, `ValidationError`, `UnauthorizedError`,
  `ForbiddenError`, `ConflictError`, `RateLimitError`
- Branded ID types: `WorldId`, `VersionId`, `BranchId`, `EntityId`,
  `StoryGraphId`, `QuestId`, `DialogueId`, `JobId`
- Pagination support (`PaginatedResponse`, `PaginationOptions`)
- Helper functions: `getWorldStateSnapshot`, `buildRelationshipMap`,
  `findConnectedEntities`, `getTimelineRange`, `analyzeFaction`,
  `compareVersions`, `searchWorld`, `generateQuestFromTemplate`,
  `generateQuestChain`, `validateWorldLore`, `checkLoreImpact`
- Quest templates (`QUEST_TEMPLATES`) with generation options

**Tags:** `scope:hathor`, `layer:clients` **Build:** `nx:run-commands`

---

## Applications (4)

### `@hathor/world-api` - World Model API

Hono-based HTTP API server for world state management, versioning, branching,
entity CRUD, and queries. Integrates with the event bus for cross-domain
communication.

**Dependencies:** `hono`, `@hono/node-server`, `@hono/zod-openapi`, `zod`,
`@oshun/event-bus`, `@hathor/event-handlers`, `@hathor/event-publisher`

---

### `@hathor/narrative-api` - Narrative Content API

Hono-based HTTP API server for narrative resources: story graphs, quests,
dialogues, and journal entries.

**Dependencies:** `hono`, `@hono/node-server`, `@hono/zod-validator`, `zod`

---

### `@hathor/simulation-worker` - Simulation Background Worker

Background worker process for running world simulations (economy, politics,
culture, scenarios). Processes queued simulation jobs and reports results.

**Dependencies:** `@hathor/simulation`, `hono`, `@hono/node-server`

---

### `@hathor/workbench` - Visual Worldbuilding Application

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

**Technology:** React 18, React Router DOM, TanStack Query (data fetching),
Zustand (state management), Tailwind CSS (styling), Lucide React (icons),
Highlight.js (code highlighting), DOMPurify (HTML sanitization)

**Build:** Vite

---

## Database

**PostgreSQL** with the `hathor` schema via Prisma ORM.

**Core tables:** World, WorldVersion, Branch, MergeRequest, Entity,
EntityRelation, StoryGraph, StoryNode, StoryArc, DialogueTree, DialogueNode,
DialogueSession, Quest, QuestObjective, QuestReward, SimulationRun,
SimulationEvent, SimulationSnapshot, ValidationResult, AuditLog.

**Version control model:** Worlds support Git-like versioning with branches and
merge requests. Each version tracks changes. Merge requests can be opened,
approved, merged, or rejected.

---

## Technology Stack

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

---

## Development

```bash
# Run tests for a specific library
pnpm nx test @hathor/simulation
pnpm nx test @hathor/narrative
pnpm nx test @hathor/validation

# Build a specific library
pnpm nx build @hathor/domain-models

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

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

# Start the world API
pnpm nx serve @hathor/world-api

# Start the workbench
pnpm nx serve @hathor/workbench

# Database operations
pnpm nx run @hathor/database:prisma:generate
pnpm nx run @hathor/database:prisma:migrate
```

---

## Related Domains

- **Sophia** - Research and knowledge domain providing grounded facts for
  worldbuilding via `@hathor/sophia-integration`
- **Isis** - Generative factory domain producing assets that link to world
  entities via event handlers
- **Yemaya** - Creative studio domain synchronizing projects and characters with
  world state
- **Bellona** - Build engine domain receiving compiled packages from the lore
  compiler
- **Kuanyin** - Ethics domain providing content moderation for generated
  narrative content
- **Maya** - Game engine domain that could consume Hathor worlds for playable
  experiences
