# Hathor — Feature Reference

> **Hathor** is the Worldbuilding, Narrative Design, and World Simulation
> Platform. Named after the Egyptian goddess of love, beauty, and the arts,
> Hathor provides everything needed to design, populate, simulate, validate, and
> export interactive worlds — from the geography and climate of a fantasy
> continent, through its economies, politics, and cultures, all the way to the
> quests, dialogues, and AI-driven NPCs that bring the world to life.

Hathor publishes world artifacts that Bellona consumes for engine-ready world
asset packages. It integrates with Sophia for research-grounded lore and with
Isis for generated world assets (character images, environment concept art), and
it consumes new projects and characters from Yemaya. The platform spans 17
libraries and 7 applications across REST APIs, a simulation worker, a visual
workbench, the Veilborn Chronicles game services, and a TypeScript SDK.

---

## Table of Contents

1. [Platform Overview](#platform-overview)
2. [World Modeling](#world-modeling)
3. [Narrative Design](#narrative-design)
4. [World Simulation](#world-simulation)
5. [Veilborn Chronicles Game Services](#veilborn-chronicles-game-services)
6. [LLM-Powered NPC Intelligence](#llm-powered-npc-intelligence)
7. [Lore Validation](#lore-validation)
8. [Lore Compilation and Export](#lore-compilation-and-export)
9. [Game Design Theory](#game-design-theory)
10. [Pre-Production Tools](#pre-production-tools)
11. [Version Control for Worlds](#version-control-for-worlds)
12. [Research Grounding](#research-grounding)
13. [Visual Workbench](#visual-workbench)
14. [TypeScript SDK](#typescript-sdk)
15. [Cross-Domain Integration](#cross-domain-integration)

---

## Platform Overview

Hathor is implemented across 17 libraries and 7 applications. It sits at the
intersection of creative writing, software engineering, AI research, and game
development — providing a structured approach to the inherently creative task of
worldbuilding.

### Architecture

The diagram below shows the dependency stack from the database up to the SDK.
Domain libraries sit in the middle layers; integration and client layers sit on
top.

```
@hathor/database (Prisma schema + client)
          │
@hathor/domain-models (faction, economy, law, culture, geography, timeline)
          │
┌─────────┼──────────┐
│         │          │
@hathor/  @hathor/   @hathor/
narrative simulation validation
          │
┌─────────┼──────────┐
│         │          │
@hathor/  @hathor/   @hathor/
lore-     llm-npc    theory
compiler
          │
@hathor/pre-production
          │
@hathor/sophia-integration
          │
@hathor/event-publisher + @hathor/event-handlers
          │
@hathor/client (TypeScript SDK)
```

Four additional façade libraries — `@hathor/characters`, `@hathor/world`,
`@hathor/timeline`, `@hathor/quests` — sit on top of `@hathor/domain-models` and
`@hathor/narrative` to adapt Hathor types for cross-domain (CGI / production)
consumption.

### Application Layer

The seven Hathor applications each serve a distinct role in the pipeline. The
three worldbuilding services are Hono; the two game services are Fastify.

| Application         | Port | Purpose                                                           |
| ------------------- | ---- | ----------------------------------------------------------------- |
| `world-api`         | 3001 | World entity CRUD, versioning, branching, query engine            |
| `narrative-api`     | 3002 | Quest, dialogue, story graph, and validation management           |
| `simulation-worker` | 3004 | Background simulation jobs (economy, politics, culture, scenario) |
| `workbench`         | —    | React-based visual editor for world design                        |
| `studio-web`        | —    | V2 fighting-game narrative content map (compiler input)           |
| `veilborn-core`     | 8080 | Veilborn Chronicles core game engine (tabletop RPG / wargame)     |
| `veilborn-strategy` | 8080 | Veilborn Chronicles "The Veil War" strategy game mode             |

`world-api`, `narrative-api`, and `simulation-worker` are Hono services;
`veilborn-core` and `veilborn-strategy` are Fastify services (default `PORT`
8080). The Veilborn services implement a tabletop RPG / wargame and a five-mode
strategy game built on the Hathor domain (see
[World Simulation](#world-simulation)).

### Library Ecosystem

The table below provides a one-line summary of each of Hathor's 17 libraries.

| Library                      | Description                                                                     |
| ---------------------------- | ------------------------------------------------------------------------------- |
| `@hathor/database`           | Prisma ORM client and schema for all Hathor data models                         |
| `@hathor/domain-models`      | Faction, economy, law, culture, geography, timeline, character, location models |
| `@hathor/narrative`          | Quest system, dialogue trees, story graphs, journal and codex, exporters        |
| `@hathor/simulation`         | Economy, politics, culture, scenario simulation + NPC behavior trees + physics  |
| `@hathor/validation`         | Timeline, causality, taxonomy, and contradiction validators                     |
| `@hathor/lore-compiler`      | Game engine artifacts (Unreal, Unity, Godot, Blender) + screenplay export       |
| `@hathor/llm-npc`            | LLM-powered NPC personality, emotion, memory, and multi-platform dialogue       |
| `@hathor/theory`             | MDA framework, narrative theory, cinematography planning                        |
| `@hathor/pre-production`     | Chronicle parser, storyboarding, project planning, virtual-production systems   |
| `@hathor/sophia-integration` | Citation grounding, research integration, lore fact-checking                    |
| `@hathor/event-publisher`    | Domain event output for cross-domain communication                              |
| `@hathor/event-handlers`     | Incoming event handling from Sophia, Isis, and Yemaya                           |
| `@hathor/client`             | Unified TypeScript SDK for the Hathor HTTP APIs                                 |
| `@hathor/characters`         | CGI character-definition import facade                                          |
| `@hathor/world`              | CGI scene-definition import facade                                              |
| `@hathor/timeline`           | Narrative scene-order facade (story-order / shoot-order reconciliation)         |
| `@hathor/quests`             | Scene-dependency and story-arc capture facade                                   |

---

## World Modeling

### World Configuration (`@hathor/domain-models`)

Every world begins with a structured configuration that governs all downstream
content generation and simulation. The configuration is versioned — changing
genre or technology level creates a new version rather than overwriting the
prior configuration.

| Setting              | Options                                                                                                      |
| -------------------- | ------------------------------------------------------------------------------------------------------------ |
| **Genre**            | Fantasy, Science Fiction, Historical, Contemporary, Horror, Mystery, Mythology, and custom                   |
| **Scope**            | Small (village/city), Medium (region/country), Large (continent), Epic (world), Cosmic (multi-world setting) |
| **Technology Level** | Primitive, Ancient, Medieval, Renaissance, Industrial, Modern, Futuristic, Advanced, Mixed                   |
| **Magic Level**      | None, Low, Medium, High, Epic                                                                                |
| **Status**           | Draft, Active, Archived, Deleted                                                                             |

### Geography

Geography defines the physical reality that constrains everything else in the
world — where settlements can be built, what resources are available, which
routes are safe, and what climate the people live under.

- **Terrain Types** — Mountains, forests, deserts, plains, tundra, swamps,
  oceans, rivers, lakes, islands, canyons, and custom terrain types; each
  terrain associates with appropriate flora, fauna, and traversal difficulty
- **Climate Systems** — Temperature zones by latitude, precipitation patterns by
  season, prevailing wind directions, and extreme weather event types
- **Biomes** — Ecological regions with associated plant and animal species
  lists; biomes constrain what resources can be found in each region
- **Natural Features** — Volcanoes, caves, waterfalls, hot springs, mineral
  deposits, ruins, and other discoverable landmarks
- **Hierarchical Maps** — Locations nest within regions nest within continents;
  the same location can be a city on the continental map and a detailed street
  grid on the local map

### Factions

Factions represent the organized power structures of the world — governments,
guilds, cults, criminal organizations, and noble families — each with their own
agenda and resources.

| Faction Attribute | Description                                                                                                                  |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| **Type**          | Government, Military, Religious, Criminal, Merchant Guild, Artisan Guild, Secret Society, Noble Family, Tribal Confederation |
| **Hierarchy**     | Leadership structure with configurable ranks, titles, and succession rules                                                   |
| **Ideology**      | Core beliefs, values, goals, and the means by which the faction pursues them                                                 |
| **Relations**     | Alliances, rivalries, grudging neutrality, active war, and past agreements with other factions                               |
| **Territory**     | Controlled locations with border definitions and disputed regions                                                            |
| **Resources**     | Economic assets, strategic resources, and trade goods controlled by the faction                                              |
| **Military**      | Armed force composition, strength rating, equipment level, and special capabilities                                          |

### Economy (`@hathor/domain-models`)

Economic modeling gives the world a living material basis. Prices emerge from
supply and demand simulation rather than static assignment, which means NPC
merchants respond realistically to world events.

- **Resources** — Define commodities with rarity classification (common,
  uncommon, rare, legendary), production sources (mined, grown, crafted,
  magical), and unit weight/volume for trade simulation
- **Currencies** — Multiple monetary systems with exchange rates; a world can
  have competing currencies from different factions or trade zones
- **Markets** — Trading hubs with supply and demand levels per commodity; market
  prices emerge from supply/demand simulation rather than static assignment
- **Trade Routes** — Connections between markets with road quality, distance,
  terrain difficulty, and associated risk (bandit activity, weather hazard)
- **Guilds** — Economic organizations controlling specific industries with
  membership requirements, fees, and enforcement mechanisms
- **Trade Agreements** — Bilateral and multilateral economic treaties with
  duration, terms, and compliance tracking

### Legal Systems

A world's legal framework shapes the daily life of its population — what is
forbidden, who enforces it, and what happens when the rules are broken.

- **Legal Codes** — Formal rule sets with specific prohibitions, requirements,
  and associated penalties for violation
- **Enforcement Structures** — Guards, courts, arbitration bodies, and vigilante
  groups; each with jurisdiction scope and enforcement effectiveness rating
- **Crime Categories** — Severity classification from petty crime through
  capital offense with typical penalties per severity
- **Legal Traditions** — Common law (precedent-based), civil law (code-based),
  religious law (scripture-based), or customary law (tradition-based)

### Culture

Rich cultural modeling informs NPC behavior, dialogue tone, and world
atmosphere. Culture is not just a label but a set of attributes that propagate
through the simulation and the LLM-NPC system.

- **Traditions** — Named customs, ceremonies, and rites of passage with
  associated dates, required participants, and social significance
- **Art Forms** — Music genres, literary styles, visual arts, and performance
  traditions specific to each culture
- **Social Structures** — Class systems, kinship patterns, gender role norms,
  coming-of-age markers, and social mobility rules
- **Belief Systems** — Religious and philosophical frameworks including creation
  myths, afterlife beliefs, moral codes, and ritual practices
- **Languages** — Naming conventions (what kinds of names are culturally
  typical), common phrases, grammatical quirks, and linguistic family
  relationships
- **Cuisine and Architecture** — Food traditions (taboo foods, feast traditions,
  cooking methods) and architectural styles (materials, ornamentation, building
  purposes)

### Characters (10 Entity Types)

Characters are stored as the `CHARACTER` entity type, one of 10 entity types
supported by the universal `Entity` table. The full set of character attributes
is:

| Character Aspect         | Details                                                                      |
| ------------------------ | ---------------------------------------------------------------------------- |
| **Identity**             | Name, aliases, species, approximate age, gender expression                   |
| **Physical Attributes**  | Height, build, distinguishing features, voice quality                        |
| **Abilities and Skills** | Combat skills, magical abilities, professional skills, and expertise ratings |
| **Backstory**            | Origin, formative events, defining traumas, catalytic moments                |
| **Motivations**          | Primary goal, secondary desires, and what the character fears most           |
| **Relationships**        | Family connections, friendships, rivalries, romantic interests, and mentors  |
| **Faction Allegiance**   | Current faction, rank within it, and loyalty strength                        |
| **Status**               | Alive, Deceased, Unknown, Missing, Legendary                                 |
| **Location**             | Current whereabouts, home location, and frequently visited places            |
| **Narrative Role**       | Protagonist, antagonist, mentor, herald, trickster, or custom role type      |

### Locations

Location types: City, Town, Village, Fortress, Temple, Dungeon, Wilderness,
Landmark, Region, Realm, Plane. Locations nest hierarchically — a room is inside
a building is inside a district is inside a city is inside a region.

Each location has: physical description, atmosphere, notable NPCs, available
services, controllable factions, and associated lore entries.

### Timelines

Timelines give the world a historical dimension. The system can detect
chronological gaps and flag when a character is referenced as active after their
recorded death date.

- **Eras** — Named historical periods with start and end dates in world-time;
  each era has a dominant faction, technology level, and defining events
- **Events** — Historical occurrences with date, location, involved parties,
  causes, and consequences; linked to the characters and factions involved
- **Chronological Ordering** — Automatic sorting and gap detection in the
  timeline; conflicting dates are flagged for resolution
- **Event Chains** — Explicit cause-and-effect sequences linking events; enables
  "if you remove this event, these consequences are no longer historically
  explained"
- **Character Lifespans** — Birth, death, and major life events tied to timeline
  dates; the system can detect if a character is referenced as active after
  their recorded death date

---

## Narrative Design

### Quest System (`@hathor/narrative`)

Quests are the primary mechanism by which players interact with world events.
The quest system models both the authoring side (what the designer defines) and
the runtime side (how quest state advances as the player acts).

| Quest Element       | Description                                                                                                                                                                                                             |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Objectives**      | Eight objective types: Collect (gather items), Kill (defeat enemies), Talk (initiate dialogue), Explore (discover location), Escort (protect NPC to destination), Deliver (transport item), Craft (create item), Custom |
| **Prerequisites**   | Quests, items, faction reputation levels, or character attributes required before a quest becomes available                                                                                                             |
| **Branching Paths** | Multiple routes through a quest based on player choices; branch decisions recorded for downstream narrative consequences                                                                                                |
| **Rewards**         | Items, currency, experience points, faction reputation, skill unlocks, or custom arbitrary rewards                                                                                                                      |
| **Categories**      | Main Story, Side Quest, Exploration, Faction, Daily, World Event                                                                                                                                                        |
| **Priority**        | Low, Normal, High, Critical — affects display and NPC reaction urgency                                                                                                                                                  |
| **Status**          | Draft, Available, Active, Completed, Failed, Abandoned — with automatic transitions                                                                                                                                     |

### Dialogue System

The dialogue system supports both authoring (building the tree) and runtime
(tracking which node the player is at during a live conversation). Variable
substitution and conditional display make it possible to write a single dialogue
tree that behaves differently for every player.

- **Dialogue Trees** — Hierarchical conversation structures with speaker
  attribution at every node; supports arbitrarily deep branching
- **Node Types** — Greeting (session opener), Statement (NPC speaks without
  response prompt), Question (prompts player for response), Response (player
  replies), Choice (player selects from options), End (closes conversation)
- **Player Choices** — Multiple configurable response options at each Choice
  node with text, conditions, and target node
- **Conditional Display** — Show or hide dialogue options based on game state
  variables: faction reputation threshold, item possession check, quest status,
  character attribute comparison, and arbitrary custom conditions
- **Variable Substitution** — Insert dynamic values (character name, location
  name, item name, quest state) into dialogue text at runtime using a template
  syntax
- **Speaker Attribution** — Every line records which character is speaking,
  enabling export tools to correctly format dialogue for each engine

### Story Graph

A story graph models narrative at a higher level than a single dialogue tree —
it represents the full arc of a storyline, with branching caused by both player
choices and world-state conditions.

| Node Type | Purpose                                                                |
| --------- | ---------------------------------------------------------------------- |
| START     | Entry point of the narrative; exactly one per story graph              |
| SCENE     | A narrative scene with description, mood, and triggered events         |
| CHOICE    | A branching point where the player selects from 2-8 options            |
| CONDITION | An automatic branch where game state determines the path               |
| ACTION    | A triggered game-world action (spawn NPC, change weather, unlock door) |
| END       | A conclusion point; a story graph can have multiple distinct endings   |

- **Directed Arcs** — Connections between nodes with optional conditions and
  priority ordering; the highest-priority valid arc is taken
- **State Variables** — Named variables tracked through the story graph; can be
  set, incremented, or tested at any node
- **Narrative State Transitions** — Record which state the narrative is in at
  any save point; enables resuming and branching correctly
- **Multiple Endings** — Design branching narrative conclusions where different
  accumulated choices lead to distinct resolutions

### Journal and Codex System

The journal and codex give players a way to review discovered lore and track
their quest progress inside the game world, without requiring the author to
manually manage what has and hasn't been revealed.

- **Journal Entries** — Chronological log of events, quest updates, and
  character discoveries; entries unlock as the player progresses through
  specific triggers
- **Codex Entries** — Encyclopedia-style articles about world lore: factions,
  locations, characters, history, and concepts; the in-game knowledge repository
- **Progressive Discovery** — Entries begin locked and unlock when the player
  encounters the associated entity, completes a quest, or reaches a trigger
  point
- **Player Notes** — Allow players to add their own annotations to any journal
  or codex entry
- **Category Organization** — Group entries by region, faction, character, item
  type, or custom category

### Narrative Export Formats

Once a narrative is authored in Hathor, it can be exported into any of three
industry-standard dialogue formats for use in game engines or interactive
fiction platforms.

| Format       | Tool                   | Use Case                                                     |
| ------------ | ---------------------- | ------------------------------------------------------------ |
| Ink          | Inkle Ink/Inky         | Interactive fiction and branching narrative web/mobile games |
| Yarn Spinner | Yarn Spinner for Unity | Unity-based dialogue systems with branching                  |
| JSON         | Any engine             | Custom engines and proprietary dialogue runtime formats      |

---

## World Simulation

### Economy Simulation (`@hathor/simulation`)

Economy simulation models a world as a system of interacting markets, producers,
and consumers. Rather than setting prices manually, the author configures
production and demand levels and watches prices emerge from the simulation.

- **Supply/Demand Dynamics** — Market prices fluctuate based on supply, demand,
  and scarcity; hoarding by factions causes price spikes; productive events
  create surpluses and price drops
- **Trade Route Modeling** — Profitability calculations per route based on
  distance, terrain cost, risk (banditry probability), and commodity price
  differential between endpoints
- **Resource Flow Simulation** — Production (mines, farms, workshops) generates
  resources; consumption (population, military, industry) depletes them;
  stockpiles build when production exceeds consumption
- **Guild Dynamics** — Guilds enforce price floors, restrict market entry, and
  apply tariffs; guild power shifts based on economic simulation outcomes
- **Economic Events** — Famines (crop failure, production drop), windfalls
  (discovery of deposits), trade embargoes (route closure), economic booms
- **Economic Snapshots** — Capture the economic state at any simulation tick for
  comparison and rollback; enables "what would have happened if" analysis

### Politics Simulation

Political simulation models how factions compete for power, form alliances, and
resolve conflicts. The simulation runs continuously in the background, so the
political landscape can shift in response to player actions.

- **Dynamic Faction Relations** — Alliance strength, rivalry intensity, and
  neutrality calculated continuously from recent interactions, ideology
  compatibility, and resource competition
- **Conflict Simulation** — War resolution based on military strength, terrain,
  supply lines, and morale; diplomatic resolution via treaty negotiation
- **Leader Behavior** — Each leader has a personality profile that drives their
  decisions; succession rules activate when leaders die or abdicate
- **Alliance Management** — Alliance formation based on common enemies and
  interests; maintenance via contribution compliance; dissolution when trust
  drops below threshold
- **Treaty Tracking** — Peace treaties, trade agreements, and military pacts
  with compliance monitoring; breach of treaty triggers relationship damage
  events
- **Elections** — Configurable electoral systems for democratic factions with
  campaign simulation and voter behavior modeling
- **Political Events** — Coups, rebellions, assassinations, policy changes, and
  scandals with causal chains and aftermath modeling

### Culture Evolution Simulation

Culture simulation models how beliefs, practices, and values spread and change
over time. It is most useful for generating historical depth in world chronicles
or simulating the long-term effects of contact between civilizations.

- **Cultural Trait Drift** — Individual cultural values and practices gradually
  shift over generations under the influence of internal innovation and external
  contact
- **Cultural Contact Effects** — When cultures interact through trade, war, or
  migration, traits exchange, assimilate, or generate resistance reactions
- **Innovation Events** — Random and condition-triggered innovations in
  technology, philosophy, art, and social organization
- **Subculture Emergence** — When groups within a culture diverge significantly
  in values, they split into distinct subcultures with their own trajectories
- **Cultural Phases** — Growth (expanding influence), Flourishing (peak
  expression), Decline (diminishing vitality), and Renaissance (revival) phases
  drive simulation dynamics
- **Influence Network Analysis** — Map how cultural traits spread through
  geographic and social proximity networks

### Scenario Generation

Scenario generation lets an author define a hypothetical world state, step the
simulation forward, and compare what happens under different interventions —
without committing any results back to the main world.

- **Configurable Starting Conditions** — Set technology level, magic prevalence,
  conflict intensity, geographic configuration, climate, and faction power
  balance
- **Time Advancement** — Step the simulation forward in configurable tick
  increments; each tick applies one round of economy, politics, and culture
  simulation
- **Intervention Application** — Apply events (plague, war declaration,
  discovery, natural disaster) and observe ripple effects through the simulation
- **Results Analysis** — Automated analysis: current power balance by faction,
  economic health by region, cultural trend trajectories, conflict risk
  assessment
- **Scenario Templates** — Pre-built starting condition templates for classic
  historical periods and genre archetypes
- **Branch Comparison** — Run two scenarios from the same starting point with
  different interventions and compare outcomes side-by-side

### NPC Behavior Trees

Behavior trees give NPCs structured decision-making without requiring the author
to write custom conditional logic for each character. The `BehaviorTreeBuilder`
fluent API makes it possible to construct complex trees by composing pre-built
node types.

| Node Category | Node Types                                                                                                                                                                                           |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Leaf          | Action (execute a specific behavior), Condition (evaluate a boolean game state test)                                                                                                                 |
| Composite     | Sequence (run children in order, fail on first failure), Selector (try children until one succeeds), Parallel (run children simultaneously), Random Selector (choose a random child)                 |
| Decorator     | Inverter, Succeeder, Failer, Repeater (loop N times), Retry (retry on failure), Limiter (max N times), Timeout, Cooldown (minimum delay between activations), Guard (condition before running child) |

- **Pre-Built Patterns** — Patrol, Flee, Attack, and Idle pre-built behavior
  templates as starting points
- **Fluent Builder API** — Compose behavior trees programmatically using a
  chainable builder that validates tree structure
- **Runtime Execution** — Behavior trees tick at configurable frequency during
  simulation; execution state is serializable for save/load

### Physics Engine

The physics engine supports world scenarios that require physical interaction
modeling — for example, simulating the trajectory of projectiles, the movement
of large bodies across terrain, or the collision dynamics of a siege engine.

| Feature             | Details                                                                                       |
| ------------------- | --------------------------------------------------------------------------------------------- |
| Rigid Bodies        | Mass, velocity, angular velocity, coefficient of friction, restitution (bounciness)           |
| Colliders           | Box, sphere, capsule, cylinder, plane, and heightmap collider shapes                          |
| Constraints         | Distance (springs), hinge (doors/hinges), ball socket (joints), slider (rails), fixed (welds) |
| Force Fields        | Gravity, directional wind, buoyancy, drag, explosion impulse, and vortex                      |
| Collision Detection | Broad phase (AABB tree) and narrow phase (contact manifold generation)                        |
| Raycasting          | Ray and sphere casting for sight lines, projectile hit detection, and terrain queries         |
| Presets             | Earth gravity (9.81 m/s²), Moon gravity (1.62 m/s²), Zero-G (space environments)              |

A full 3D math library is included: `Vec2`, `Vec3`, `Quaternion`, `AABB`,
`Transform` with arithmetic, normalization, interpolation, and coordinate
transformation operations.

### Simulation State Persistence

Simulation state can be stored in three backends depending on the use case —
in-memory for fast testing, Redis for ephemeral high-frequency state during
active simulation ticks, and PostgreSQL for durable job records and
point-in-time snapshots.

- **Storage Backends** — In-memory (testing), PostgreSQL (production), Redis
  (fast ephemeral state)
- **Snapshot System** — Capture a complete copy of simulation state at any tick
  for later comparison, rollback, or analysis
- **Domain-Specific State Stores** — Separate stores for economy, politics, and
  culture state; enables analyzing one domain while freezing others
- **Cache Key Management** — Structured cache keys for world, domain, and
  entity-level simulation states; consistent key format enables reliable
  invalidation

---

## Veilborn Chronicles Game Services

Two Fastify services under `apps/hathor/` implement **Veilborn Chronicles**, a
playable game built on the Hathor worldbuilding domain. They are full game
engines, not authoring tools, and they demonstrate how Hathor domain libraries
can be used as the foundation for a shipped game.

### Core Game Engine (`@hathor/veilborn-core`)

The core engine powers the tabletop RPG and wargame. It is implemented as ~30
domain-logic modules (~42k lines), each independently unit-tested:

- **Tactical combat ("Confluence")** — hex-grid combat with axial/cube hex
  coordinates and pathfinding, a Tide Initiative turn-order system, an
  Impulse/Flow/Surge/Torrent action economy, and line-of-sight and cover
- **Character systems** — character creation, character sheets, abilities,
  awakening, paths, and resonance
- **Cards and dice** — a card system and dice-resolution mechanics
- **Procedural world generation** — seeded generation of realms, regions,
  locations, items, creatures, and factions
- **Wargame** — wargame rules, territory control, combat AI, and a "veylmaster"
  AI game-master system
- **Social and live systems** — weave, threads, social, multiplayer, game state,
  tutorial, launch content, mobile UI, and asset generation

### Strategy Game Service (`@hathor/veilborn-strategy`)

The strategy service powers "The Veil War" mode: a turn-based strategy game with
game management, player-scoped state queries with fog-of-war, action submission,
and save/load snapshots. It supports optional WebSocket real-time
synchronization and JWT authentication. Five game modes each have their own
engine, AI opponent, and route module:

| Mode             | Description                                  |
| ---------------- | -------------------------------------------- |
| Echoes of Fate   | Timeline-manipulation strategy mode          |
| Resonance Wars   | Combat-focused strategy mode                 |
| Weave Conspiracy | Social-deduction mode                        |
| Eternal Game     | Area-control mode                            |
| Grand Campaign   | Multi-session meta-game tying modes together |

The service also ships a balance pipeline (skill rating, pattern tracking, and a
tournament runner) for tuning game balance.

---

## LLM-Powered NPC Intelligence

### Personality System (`@hathor/llm-npc`)

The personality system gives each NPC a stable cognitive model that governs how
they speak, act, and interpret the world. Three complementary frameworks are
combined: the Big Five trait model (personality dimensions), the Enneagram (type
archetypes), and the BDI cognitive architecture (goal-directed reasoning).

**Big Five Personality Model (Ocean):**

| Trait             | Low Expression                            | High Expression                                   |
| ----------------- | ----------------------------------------- | ------------------------------------------------- |
| Openness          | Conventional, routine-preferring, literal | Curious, creative, imaginative, experimental      |
| Conscientiousness | Spontaneous, disorganized, flexible       | Organized, diligent, reliable, perfectionist      |
| Extraversion      | Reserved, quiet, energized by solitude    | Outgoing, energetic, talkative, attention-seeking |
| Agreeableness     | Competitive, skeptical, challenging       | Cooperative, trusting, empathetic, accommodating  |
| Neuroticism       | Emotionally stable, calm, resilient       | Anxious, moody, reactive, emotionally volatile    |

**Enneagram System:** 9 core personality types with wing influences (adjacent
type modifiers), tritype (three dominant types), and integration/disintegration
paths (how the type behaves under growth vs. stress).

**BDI Cognitive Model:** Beliefs (what the NPC believes is true about the
world), Desires (what they want to achieve or avoid), Intentions (what they are
currently planning to do). The BDI model ensures coherent goal-directed
behavior: an NPC acts consistently with what they believe, not just with what is
objectively true.

**Speech Patterns:** Configurable vocabulary level (simple to sophisticated),
sentence structure preference (short punchy vs. elaborate), verbal tics
(catchphrases, filler words), formality level, dialect markers, and accent notes
for voice actors or TTS.

### Emotional State

Emotions are tracked as real-time intensity values that decay toward baseline
and are shifted by new stimuli. This means an NPC who was insulted an hour ago
in world-time will still be slightly on edge, rather than instantly resetting to
neutral.

- **Core Emotions** — Joy, sadness, anger, fear, surprise, disgust, trust,
  anticipation (Plutchik's eight primary emotions); each tracked as a 0-1
  intensity value
- **Emotional Intensity Decay** — Emotions gradually return toward baseline
  unless reinforced by new stimuli; decay rate configurable per trait
- **Mood** — A sustained emotional baseline that shifts slowly based on
  accumulated experiences; mood colors how the NPC interprets neutral events
- **Emotion History** — Recent emotional states stored in a time-stamped buffer;
  enables consistent character behavior and player-recognizable emotional arcs

### Memory System

The memory system distinguishes short-term conversational context (what was said
in the current session) from long-term episodic memory (what the NPC has learned
about the world over their lifetime).

**Short-Term Memory:**

- Configurable capacity (default: last 20 conversation turns and events)
- Attention-weighting that prioritizes emotionally significant events
- Recency bias with configurable decay half-life

**Long-Term Memory:**

- Important life events, formative relationships, and world knowledge stored
  with indefinite persistence
- Learned information from player conversations stored and retrievable in future
  interactions
- Memory consolidation process (STM → LTM promotion) runs on configurable
  triggers (end of conversation, sleeping, time passage)
- Configurable consolidation strategies: summarize, prioritize, or verbatim

### World Awareness

World awareness gives the NPC a coherent sense of their place in the world —
what they can see, who is nearby, what faction controls this territory, and what
events they would plausibly know about.

- **Spatial Awareness** — Current location with knowledge of adjacent connected
  spaces; knows what is physically nearby
- **Social Awareness** — Knowledge of other NPCs currently in the same area;
  recognizes named characters vs. unnamed bystanders
- **Political Awareness** — Which faction controls the current location; knows
  current political tensions that are "common knowledge" in their region
- **Event Awareness** — Aware of recent significant events within their
  knowledge radius; does not know about distant events unless they heard about
  them
- **Environmental Awareness** — Time of day, weather conditions, ambient sound

### Dialogue Generation

Dialogue generation combines personality, emotional state, memory, and world
awareness into a single prompt context so the generated speech is coherent with
everything else the NPC system knows about the character.

- **Personality-Consistent Speech** — Generated dialogue reflects the NPC's Big
  Five traits; a high-agreeableness NPC is more conciliatory than a
  low-agreeableness one
- **Emotion-Influenced Tone** — Current emotional state shifts word choice,
  sentence length, and communication style; an angry NPC is more curt
- **Memory-Informed References** — NPC references past interactions
  appropriately: "Last time we spoke, you mentioned..." when memory contains
  that exchange
- **Topic Tracking** — Tracks the current conversational topic across multiple
  turns; detects topic changes and responds appropriately
- **Dialogue Act Classification** — Each generated utterance tagged with its
  communicative purpose: greeting, question, statement, agreement, refusal,
  farewell
- **Sentiment Analysis of Player Input** — The NPC interprets the emotional tone
  of player messages; a hostile message received by a timid NPC triggers fear
- **Character Consistency Checking** — Before delivering a response, validate
  that it does not contradict the NPC's established beliefs or past statements

### Safety and Guardrails

The safety system prevents NPC-generated dialogue from breaking character,
generating harmful content, or revealing information the character should not
know. Guardrails operate at multiple levels so a single bypass attempt is
unlikely to succeed through all of them.

- **Content Safety Filters** — Prevent NPCs from generating harmful, explicit,
  or illegal content regardless of player manipulation attempts
- **Fourth-Wall Detection** — NPC should not acknowledge being a simulation,
  break character to discuss the game mechanics, or reference the real world
- **Lore Consistency Checking** — NPC cannot state facts that contradict
  established world lore; a character living before gunpowder was invented
  cannot reference firearms
- **Manipulation Detection** — Detect social engineering attempts by players
  trying to make NPCs violate their personality or reveal restricted information
- **Configurable Safety Thresholds** — Per-organization and per-production
  safety configuration for appropriate content levels

### Advanced Behavior Control

GOAP and HTN give NPCs the ability to plan multi-step strategies for achieving
goals, rather than just reacting to immediate stimuli. When a plan fails, the
NPC replans automatically rather than stopping.

- **GOAP (Goal-Oriented Action Planning)** — NPCs formulate multi-step plans to
  achieve goals using a planning algorithm that searches action space (GOAP is
  an AI planning technique where the agent defines world states and actions that
  transition between them, and a planner finds the optimal action sequence)
- **HTN Planning (Hierarchical Task Networks)** — Complex tasks decompose
  recursively into subtasks until primitive executable actions are reached (HTN
  is a hierarchical approach to planning where high-level goals break down into
  manageable task trees)
- **Failure Recovery** — When a plan fails mid-execution (e.g., a locked door
  blocks a path), the NPC replans around the obstacle rather than freezing
- **Resource Gathering** — NPCs can identify needed resources, locate them, and
  execute plans to acquire them; enables autonomous NPC survival behaviors
- **Item Manipulation** — NPCs can interact with world items: pick up, use,
  drop, trade; item actions constrained by NPC capabilities and permissions

### NPC-to-NPC Conversations

Beyond player-NPC dialogue, the system supports autonomous NPC-to-NPC
conversations driven by each NPC's individual goals and personality. These
conversations can occur off-screen during simulation ticks and produce
relationship state changes that persist.

- **Multi-NPC Orchestration** — Two or more NPCs can hold a conversation
  independently of player involvement
- **Turn-Taking Management** — Conversational turn allocation based on topic
  initiation, relationship hierarchy, and personality dominance
- **Topic Negotiation** — NPCs may redirect conversation to topics they consider
  more relevant or important
- **Relationship-Aware Dialogue** — NPC dialogue toward another NPC reflects
  their relationship (ally, rival, subordinate, superior, romantic interest)
- **Conversation Goal Tracking** — Each NPC has a goal for the conversation; the
  system tracks whether the goal was achieved

### Platform Integrations

The NPC system supports four AI platforms. A `ProviderChain` routes requests to
the best available platform, with automatic failover if one goes down.

| Platform    | Features                                                                                                                                                                    |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Generic LLM | OpenAI-compatible API support; local model hosting via Ollama; streaming response support                                                                                   |
| NVIDIA ACE  | Avatar Cloud Engine for real-time digital humans; blendshape-driven facial animation; Audio2Face lip sync; Nemo guardrails for safety; Riva ASR/TTS streaming               |
| Inworld AI  | Managed NPC platform; session management with persistent state; character trigger events; knowledge entry injection; goal-directed conversations; behavioral state tracking |
| Convai      | Hosted conversational NPC platform; real-time action triggers; facial animation data; function call support for game actions; configurable safety guardrails                |

### Provider Chain Resilience

The provider chain implements the circuit breaker pattern so the NPC system
degrades gracefully when an AI platform is unavailable, rather than failing the
entire conversation.

- **Priority-Ordered Provider List** — Configure multiple providers in fallback
  order; primary provider handles requests unless unavailable
- **Circuit Breaker Pattern** — After a configurable number of consecutive
  failures, a provider's circuit "opens" and stops sending it requests until a
  health check period passes
- **Automatic Failover** — When the primary provider's circuit is open,
  automatically route to the next healthy provider in the chain
- **Health Statistics** — Track success rate, average latency, and error types
  per provider for monitoring and tuning
- **Factory Presets** — `createStandardProviderChain` (GPT-4 → Claude → local)
  and `createGameProviderChain` (optimized for real-time game dialogue latency)

### Tiered NPC Cognition and On-Device SLM (Phases 81–83)

The roadmap extends the cloud-LLM NPC system above into a tiered cognitive
architecture where most NPC thinking runs on the player's machine. The Maya-side
packages exist under `libs/maya/` (`npc-agency-orchestrator`,
`npc-cooperation-negotiation`, `npc-distillation`, `npc-cloud-fallback`,
`npc-occupations`); the Hathor-side semantics remain planned:

- **Cognition tiers (Phase 81)** — Tier 1 behavior trees / GOAP (implemented
  above), a Tier 2 lightweight personality neural network for fast reactive
  judgment, a Tier 3 on-device SLM inference engine for dialogue and reasoning,
  and Tier 4 cloud LLM fallback (the provider chain above) for the hardest
  prompts — with teacher-student distillation (via Nous training infrastructure)
  compressing cloud-LLM behavior into the on-device tiers.
- **Runtime budgets (Phase 81)** — a VRAM budget manager and compute scheduler
  shares GPU headroom between rendering and NPC inference; a cognitive LOD
  manager and attention/salience scoring decide which NPCs think at which tier
  each tick, so hundreds of NPCs stay believable within a fixed budget, all
  coordinated by a unified cognitive loop.
- **Emergent agency (Phase 83)** — multi-horizon autonomous planning beyond
  per-goal GOAP/HTN (daily, seasonal, and life-goal horizons), reflection and
  insight generation over accumulated memories, emergent goal generation from
  personality plus memory, multi-NPC emergent cooperation beyond scripted
  conversations, NPC lifecycle and skill progression, and voice-driven emergent
  narrative hooks (Phase 82's voice input feeding narrative state).

Maya's `maya-souls` crate consumes this architecture in-world; the world-side
evolution systems (urban growth and decay, living infrastructure) are captured
in `DOMAINS/maya/features.md` under Living World Evolution, and the voice input
stack under Voice-First Gameplay Input.

---

## Lore Validation

### Timeline Validation (`@hathor/validation`)

Timeline validation catches the class of errors that arise when events,
characters, and eras are entered independently and their dates turn out to
contradict each other.

- **Chronological Ordering** — Verify that events are internally consistent in
  time; event A cannot be described as causing event B if A occurs after B
- **Era Boundary Checking** — Detect overlapping eras (two eras claiming the
  same period) or orphaned events (events dated outside all defined eras)
- **Character Lifespan Consistency** — Verify no character is described as
  participating in events outside their birth-to-death range
- **Event Date Range Validation** — Each event's date must fall within a defined
  era or be flagged as undated (acceptable) or contradictory (error)

### Causality Validation

Causality validation catches logical contradictions in event chains: effects
that precede causes, missing causal links, and circular causality.

- **Temporal Consistency** — Effects cannot chronologically precede their
  causes; the validator detects causal inversion
- **Causal Chain Completeness** — If event B claims to be caused by event A,
  both events must exist in the timeline and A must precede B
- **Cycle Detection** — Detect circular causality (A causes B causes C causes A)
  which creates logical impossibilities

### Taxonomy Validation

Taxonomy validation enforces that entity types and type hierarchies are used
consistently across the world.

- **Entity Type Checking** — An entity typed as a Character cannot also be a
  Location; type constraints enforced across all entity references
- **Hierarchy Validation** — Sub-types must conform to their parent type rules;
  a "desert town" inherits all constraints of both "desert" terrain and "town"
  location
- **Custom Type Definitions** — User-defined types validated against their
  declared constraints

### Contradiction Detection

Contradiction detection catches factual inconsistencies where two parts of the
world lore make mutually incompatible claims.

| Contradiction Type | Example                                                                   |
| ------------------ | ------------------------------------------------------------------------- |
| Temporal           | Character described as alive and dead during the same period              |
| Spatial            | Character described as being in two different places at the same moment   |
| Attribute          | Character's eye color or physical description changes between two sources |
| Relationship       | A is described as B's parent in one place and B's child in another        |
| State              | A door is described as locked and open simultaneously                     |

### Unified Validation Report

All four validators can be run in a single combined pass via
`createLoreValidator()`, which produces a unified report covering every
category.

- **Single-Pass All-Validator Run** — `createLoreValidator()` runs timeline,
  causality, taxonomy, and contradiction validation in one pass
- **Fail-Fast Option** — Stop validation at the first error found for rapid
  feedback, or collect all errors for comprehensive review
- **Severity Levels** — the `@hathor/validation` library classifies each issue
  as `error`, `warning`, or `info`. (The `@hathor/database` `ValidationSeverity`
  enum, used for persisted `ValidationResult` rows, additionally has
  `CRITICAL`.)
- **Per-Category Issue Limits** — Cap the number of issues reported per category
  (`maxIssuesPerCategory`, default 100) to prevent one systemic error from
  drowning out other issues
- **Summary** — the result `summary` reports `errorCount`, `warningCount`,
  `infoCount`, the list of validators run, and total `duration`

---

## Lore Compilation and Export

### Game Engine Compilation (`@hathor/lore-compiler`)

Hathor content (quests, dialogue, NPC definitions) is stored in a format-neutral
representation. The lore compiler converts this representation into
engine-native artifacts that can be imported directly into the target game
engine without any manual reformatting.

| Target Engine | Output Formats                       | Content Types Compiled                                  |
| ------------- | ------------------------------------ | ------------------------------------------------------- |
| Unreal Engine | Data Tables (CSV), Blueprint classes | Quests, dialogue trees, NPC data, item tables           |
| Unity         | C# ScriptableObjects                 | Quests, dialogue (Yarn Spinner format), NPCs, items     |
| Godot         | GDScript resources                   | Quests, dialogue trees, NPC definitions, item resources |
| Blender       | Python setup scripts                 | Scene character placement, prop positioning             |

### Screenplay Compilation

For production teams working in film or animation, the screenplay compiler
exports Hathor narrative content into industry-standard script formats.

| Format            | Target Tool                                 | Features                                                                        |
| ----------------- | ------------------------------------------- | ------------------------------------------------------------------------------- |
| Fountain          | Any plain text editor or Fountain-aware app | Industry-standard plain text format; readable without special software          |
| FDX (Final Draft) | Final Draft 12+                             | Native Final Draft XML format; preserves all formatting metadata                |
| PDF               | Any PDF viewer                              | Print-ready layout with scene headings, action, and dialogue properly formatted |

### Bellona Package Builder

The Bellona Package Builder bundles all compiled artifacts into a single
deployable package that the Bellona domain can consume for engine project
generation.

- **Cross-Engine Asset Packages** — Bundle world data, quest definitions, and
  dialogue trees into a single deployable package
- **Content Manifest** — Human-readable manifest listing every compiled artifact
  and its source lore element
- **Target Engine Specification** — Declare the target engine; the compiler
  selects appropriate output formats automatically
- **Metadata Injection** — Package includes versioning metadata linking it to
  the specific world and lore version it was compiled from

---

## Game Design Theory

### MDA Framework (`@hathor/theory`)

The MDA (Mechanics-Dynamics-Aesthetics) framework is a formal model for game
design analysis and planning. It helps designers reason about how their rules
create emergent behaviors, and how those behaviors translate into player
experiences.

- **Mechanics Catalog** — Define and document game mechanics (rules, actions,
  resources) in structured records with intent descriptions
- **Dynamics Simulation** — Simulate emergent dynamics that arise from mechanics
  interacting; predict unintended consequences before implementation
- **Aesthetics Evaluation** — Evaluate expected player experience across 8
  aesthetic categories: sensation, fantasy, narrative, challenge, fellowship,
  discovery, expression, submission
- **Feedback Loop Analysis** — Classify feedback loops as positive (amplifying)
  or negative (stabilizing); analyze system stability
- **Flow Analysis** — Evaluate challenge vs. skill balance using
  Csikszentmihalyi's flow theory; identify zones of anxiety (too hard) and
  boredom (too easy)
- **Pre-Built Mechanic Templates** — Common game mechanic starting points for
  progression, economy, crafting, combat, social, and exploration systems

### Narrative Theory

The narrative theory subsystem provides formal story structure templates and
analysis tools drawn from academic narratology and professional screenwriting
practice.

Structure templates for story architecture:

- **Hero's Journey (12 stages)** — Call to Adventure, Refusal, Mentor, Crossing
  the Threshold, Tests/Allies/Enemies, Approach, Ordeal, Reward, Road Back,
  Resurrection, Return
- **Three Act Structure** — Setup (25%), Confrontation (50%), Resolution (25%)
  with midpoint and turning points
- **Five Act Structure** — Exposition, Rising Action, Climax, Falling Action,
  Denouement
- **Kishōtenketsu** — Four-act structure from Chinese, Japanese, and Korean
  narrative traditions (Introduction, Development, Twist, Conclusion)

**Analysis Tools:**

- **Fabula/Syuzhet Decomposition** — Separate the raw story events (fabula) from
  their narrative presentation order (syuzhet); enables analysis of non-linear
  storytelling
- **Dramatic Irony Tracking** — Identify moments where the audience knows more
  than the in-story characters; plan and balance dramatic irony deliberately
- **Pacing Analysis** — Plot tension level against story time to visualize
  narrative tempo; identify flat sections or premature peaks
- **Beat Sheet Generation** — Generate structured beat sheets from story
  outlines mapping each beat to a template stage
- **Character Arc Templates** — Pre-built arc patterns: positive change
  (growth), negative change (fall), flat (steadfastness), corruption, redemption

### Cinematography Planning

For productions that need visual language planning alongside narrative, the
cinematography manager provides structured tools for pre-visualizing shots,
compositions, and lighting setups before production begins.

- **Shot Design** — Define shot type (extreme wide through extreme close-up),
  camera angle (eye level, low, high, bird's eye, dutch), camera movement
  (static, pan, tilt, dolly, crane, handheld, Steadicam), lens focal length, and
  focus plane
- **Composition Analysis** — Tools for rule of thirds, golden ratio, leading
  lines, depth of field, and framing weight analysis
- **Lighting Design** — Three-point lighting setup documentation, practical
  light integration, and motivated lighting rationale
- **Color Palette Analysis** — Temperature (warm/cool), saturation, mood
  association, and season-appropriate palette selection
- **Rhythm Analysis** — Shot duration patterns and their effect on editing
  rhythm; montage theory application tools
- **Continuity Checking** — Visual consistency analysis across shots in a scene:
  eye-line match, 180-degree rule, match cut eligibility
- **Reference Databases** — Cataloged reference data for shot types, camera
  angles, movements, lighting setups, and color effects drawn from film history

---

## Pre-Production Tools

### Chronicle Parser (`@hathor/pre-production`)

The chronicle parser ingests worldbuilding documents written in natural prose —
the kind of document a writer produces before any formal world structure is
established — and extracts structured timeline and entity data automatically.

- **Era and Event Extraction** — Identify era declarations and dated events from
  narrative text; build timeline records automatically from prose chronicles
- **Speaker Attribution** — Detect direct speech and attribute it to the
  appropriate character
- **Document References** — Identify references to other documents, locations,
  and characters for cross-linking in the knowledge graph
- **Error Diagnostics** — Parse warnings and errors reported with line numbers
  and context for correction

### Narrative Structure Analysis

Once a chronicle or outline has been parsed, the narrative structure analyzer
can score how closely it adheres to a chosen story template and surface missing
structural beats before writing begins.

- **Beat Mapping** — Map identified story beats to template positions in a
  chosen structure (Hero's Journey, Three Act, etc.)
- **Adherence Score** — Calculate a 0-1 score representing how closely the story
  follows the chosen template; useful for identifying structural gaps
- **Missing Beat Detection** — Identify critical structural beats that are
  absent from the current outline
- **Pacing Intensity Curve** — Plot predicted emotional intensity across all
  identified beats; surface pacing problems before writing begins

### Visual Storyboarding

The storyboard system is embedded in Hathor so that visual pre-production and
world design happen in the same environment. A storyboard frame carries enough
structured metadata that it can feed directly into camera automation systems.

- **Frame Creation** — Individual storyboard panels with description, mood,
  camera specification, and notes
- **Sequences** — Ordered collections of frames forming scenes; scenes ordered
  into acts
- **Layer Composition** — Define foreground, midground, and background elements
  per frame for composition planning
- **Camera Specifications** — Shot type, camera angle, and lens for each frame;
  data usable by autonomous camera systems
- **Transitions** — Cut, dissolve, fade, wipe, and custom transition types
  between frames
- **Character Placement** — Position named characters within the frame with
  orientation and action notes
- **Props and Effects** — Add props and visual effects (rain, fire, explosions)
  with placement in the frame
- **Text Overlays** — Dialogue, captions, sound effect indicators, and timing
  notes overlaid on frames
- **Timeline Linking** — Connect storyboard frames to specific world timeline
  events for production scheduling integration
- **Export** — Export storyboard PDFs for director review and production
  packages

### Pre-Production Project Management

The project manager provides a structured workflow for taking a world from
initial concept to production-ready state, with built-in quality checklists for
each entity type.

- **Project Phases** — Concept, Development, Refinement, Polish phases with
  configurable milestones per phase
- **Task Management** — Create tasks with assignee, deadline, dependencies, and
  status; dependency graph prevents marking a task complete before its
  prerequisites are done
- **Progress Calculation** — Automatic project health percentage based on task
  and milestone completion
- **Built-In Checklists** — Pre-built quality checklists for: Character
  creation, Location creation, Faction creation, Historical event planning,
  Magic system design, World overview completeness

---

## Version Control for Worlds

### Git-Like Versioning (`@hathor/world-api`)

Hathor implements a complete version control system for world data, inspired by
git but designed for structured data rather than text files. This makes it safe
to experiment with alternative world states without losing the main timeline.
The versioning, branching, and merge logic lives in `@hathor/world-api`'s
services (version, merge, and world services); the `WorldVersion`, `Branch`, and
`MergeRequest` Prisma models back it.

- **Versions** — Every change to world content creates a new version with an
  author, timestamp, and description of what changed
- **Branches** — Create named branches to explore alternative world states
  (e.g., "what if the empire never fell?") without affecting the main timeline
- **Merge Requests** — Propose merging a branch back into the main world;
  reviewers can approve, comment, or request changes before execution
- **Conflict Resolution** — When merging branches with conflicting changes, each
  conflict is presented individually with source/target strategy selection
- **Cherry-Pick** — Apply specific individual changes from one branch to another
  without merging the entire branch
- **Rebase** — Rebase a branch onto the latest main world state; replays the
  branch's changes on top of current main
- **Version Comparison** — Diff any two versions to see exactly what changed:
  which entities were added, modified, or removed
- **Version History** — Complete chronological audit trail of every change with
  author, timestamp, and description

### Collaboration

Multiple authors can work on the same world concurrently. Write operations
record who made each change via the `X-User-ID` header forwarded by the API
gateway.

- **Collaborator Management** — Add or remove per-world collaborators by user ID
  (`POST`/`DELETE /worlds/:id/collaborators`); collaborator state is part of the
  in-memory world record
- **Rate Limiting** — 100 requests per minute per IP on the world API; prevents
  accidental bulk operation flooding
- **Authenticated Mutations** — Write operations read an `X-User-ID` request
  header (forwarded by the API gateway) for ownership and authorship

---

## Research Grounding

### Citation Service (`@hathor/sophia-integration`)

Sophia's research corpus serves as an external grounding layer for world lore.
Rather than inventing facts that could contradict real-world history or
anthropology, a world author can search Sophia for supporting sources and attach
citations directly to lore elements.

- **Research Index Search** — Search Sophia's indexed documents for sources
  relevant to specific world elements
- **Citation Creation** — Create citation records linking a specific lore
  element to a specific source document; establishes a provenance chain for
  world content
- **Citation Verification** — Verify that cited sources actually support the
  lore claim; prevents citation of irrelevant sources

### Research Grounding Service

The research grounding service does the inverse of citation: given a world
description, it searches Sophia for real-world parallels and enrichment
opportunities.

- **Lore Element Grounding** — Given a world description (e.g., "feudal
  agricultural economy with serfdom"), search Sophia for real-world historical
  parallels and suggested reference materials
- **Real-World Entity Discovery** — Identify real-world historical and cultural
  entities (from Sophia's knowledge graph) that are relevant to the world's
  themes; suggests enrichment opportunities
- **Relationship Suggestions** — Surface relationships between world elements
  and research sources that the author may not have considered

### Lore Fact-Checking

Lore fact-checking lets a world author submit specific claims to Sophia for
verification against the research corpus, either one at a time or in bulk.

- **Individual Fact Checks** — Submit a specific factual claim from world lore
  and check it against the Sophia knowledge base for plausibility
- **Batch Validation** — Submit entire lore sections for bulk fact-checking;
  results returned as a structured report with per-claim verdicts
- **Confidence Scoring** — Each fact check returns a confidence score reflecting
  how strongly the research corpus supports or contradicts the claim
- **Correction Suggestions** — When a claim is unsupported or contradicted, the
  system suggests source-backed corrections

---

## Visual Workbench

The Hathor workbench is a React-based web application for visual world design
without requiring SDK knowledge. It covers the most common world design
workflows across seven pages.

| Page             | Purpose                                                                                                                              |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| **Dashboard**    | World count and status summary, recent activity feed, quick navigation to recently edited worlds                                     |
| **Worlds**       | Browse all worlds with filter and search; create new worlds; open, clone, archive, or delete                                         |
| **World Editor** | Edit world configuration; manage entities across all categories; view version history; create and manage branches and merge requests |
| **Characters**   | Browse character roster; create and edit character profiles; view relationship graph; link to factions and locations                 |
| **Factions**     | Create and manage factions; define inter-faction relationships; track territory and resource holdings                                |
| **Locations**    | Create and nest locations in the world hierarchy; view map relationships and spatial connections                                     |
| **Timeline**     | Chronological event visualization with era markers; create events and link to characters and factions                                |

---

## TypeScript SDK

The `@hathor/client` SDK wraps all three Hathor HTTP APIs (World, Narrative, and
Simulation) with typed resources, branded ID types, and a comprehensive error
hierarchy. It is the recommended way to interact with Hathor from application
code.

### World Resource (`@hathor/client`)

The World Resource covers world lifecycle, version control, branch management,
and entity operations.

- `createWorld()` / `getWorld()` / `updateWorld()` / `deleteWorld()` /
  `listWorlds()`
- `cloneWorld()` — Create a copy of a world with full history
- `exportWorld()` — Export world data as a portable JSON bundle
- `getVersion()` / `listVersions()` / `createVersion()` / `revertToVersion()` /
  `compareVersions()`
- `createBranch()` / `listBranches()` / `deleteBranch()`
- `createMergeRequest()` / `getMergeRequest()` / `updateMergeRequest()` /
  `executeMerge()`
- `addEntity()` / `updateEntity()` / `removeEntity()` / `getRelationships()` /
  `findConnectedEntities()`

### Narrative Resource

The Narrative Resource covers story graph, quest, and dialogue operations,
including runtime session management for live dialogue playback.

- Story graph CRUD: create, read, update, delete story graphs with full arc and
  node management
- State variable management: set, get, reset named variables
- Quest CRUD with lifecycle transitions: `startQuest()`, `completeQuest()`,
  `failQuest()`, `abandonQuest()`
- Objective progress: `updateObjectiveProgress(questId, objectiveId, progress)`
- Dialogue tree CRUD with node and choice management
- Runtime dialogue sessions: `startSession(npcId, playerId)`,
  `advance(sessionId, choiceId)`, `endSession(sessionId)`

### Simulation Resource

The Simulation Resource manages the lifecycle of simulation jobs, which run
asynchronously in the simulation worker.

- `submitJob(type, input, priority)` — Start an
  economy/politics/culture/scenario/integrated simulation job asynchronously
- `getJobStatus(jobId)` — Poll simulation progress across all stages
- `getResults(jobId)` — Retrieve structured simulation results with analysis
- `cancelJob(jobId)` / `retryJob(jobId)` — Job lifecycle management

### Convenience Helper Functions

The SDK ships a set of higher-level helper functions in `helpers/` that combine
multiple API calls into useful single-call operations.

| Function                                      | Purpose                                                 |
| --------------------------------------------- | ------------------------------------------------------- |
| `getWorldStateSnapshot()`                     | Capture complete world state at current tick            |
| `buildRelationshipMap()`                      | Generate a map of all entity relationships              |
| `findConnectedEntities(id, depth)`            | Traverse entity graph to specified depth                |
| `getTimelineRange(start, end)`                | Get all events within a date range                      |
| `analyzeFaction(factionId)`                   | Analyze faction strength, relationships, and trajectory |
| `compareVersions(v1, v2)`                     | Diff two world versions with structured change list     |
| `searchWorld(query, filters)`                 | Full-text search across all entities in a world         |
| `generateQuestFromTemplate(template, params)` | Generate a quest using a built-in template              |
| `generateQuestChain(theme, length)`           | Generate a series of N connected quests                 |
| `validateWorldLore(worldId)`                  | Run all four validators; return unified report          |
| `checkLoreImpact(worldId, change)`            | Predict the impact of a proposed lore change            |

### Built-In Quest Templates

`QUEST_TEMPLATES` provides six built-in templates — Fetch, Elimination, Escort,
Exploration, Investigation, and Faction — with configurable parameters
(`generateQuestFromTemplate`), plus `generateQuestChain` for connected quest
series and `analyzeQuest` / `getQuestRecommendations` for design feedback.

---

## Cross-Domain Integration

### Events Published (`@hathor/event-publisher`)

Hathor publishes seven event types to the `@oshun/event-bus`. Each event has a
default set of target domains that receive it, though the caller can override
the target list per call.

| Event                         | Trigger                            | Default targets     |
| ----------------------------- | ---------------------------------- | ------------------- |
| `hathor.world.created`        | New world created                  | `isis`, `bellona`   |
| `hathor.world.published`      | World published for production use | `bellona`, `yemaya` |
| `hathor.element.added`        | Entity added to a world            | (broadcast)         |
| `hathor.narrative.generated`  | Narrative content generated        | `sophia`            |
| `hathor.simulation.started`   | Simulation job begins processing   | (broadcast)         |
| `hathor.simulation.completed` | Simulation job finishes            | `bellona`           |
| `hathor.world.validated`      | Lore validation results available  | (broadcast)         |

### Events Consumed (`@hathor/event-handlers`)

Hathor subscribes to four upstream events. Each subscription runs with its own
concurrency limit so a burst from one source does not block the others.

| Source Event               | Source | Hathor Action                                                                     |
| -------------------------- | ------ | --------------------------------------------------------------------------------- |
| `sophia.document.ingested` | Sophia | Incorporate research documents as grounding material for world lore               |
| `isis.asset.generated`     | Isis   | Link generated character/environment assets to corresponding world entities       |
| `yemaya.project.created`   | Yemaya | Synchronize a new creative project with world state (create initial world record) |
| `yemaya.character.created` | Yemaya | Incorporate a new character created in Yemaya into the world character graph      |

### Platform Availability

The table below shows which interface (REST API, SDK, or visual web UI) is
available for each Hathor feature. Features marked `—` are not currently exposed
through that interface and must be accessed through another.

| Feature                           | API | SDK | Web UI |
| --------------------------------- | --- | --- | ------ |
| World creation and editing        | Yes | Yes | Yes    |
| Entity management                 | Yes | Yes | Yes    |
| Version control                   | Yes | Yes | Yes    |
| Quest design                      | Yes | Yes | —      |
| Dialogue authoring                | Yes | Yes | —      |
| Story graph design                | Yes | Yes | —      |
| Narrative export                  | —   | Yes | —      |
| Economic simulation               | Yes | Yes | —      |
| Political simulation              | Yes | Yes | —      |
| Cultural simulation               | Yes | Yes | —      |
| Scenario generation               | Yes | Yes | —      |
| NPC personality system            | —   | Yes | —      |
| NPC dialogue generation           | —   | Yes | —      |
| Lore validation                   | —   | Yes | —      |
| Lore compilation                  | —   | Yes | —      |
| Storyboarding                     | —   | Yes | —      |
| Pre-production project management | —   | Yes | —      |
| MDA framework analysis            | —   | Yes | —      |
| Cinematography planning           | —   | Yes | —      |
| Research grounding                | —   | Yes | —      |

---

## Neith Story, Animation, and Engine Dependencies (planned — Phases 141, 156, 171-174)

The integration surfaces in this section are planned cross-domain work, not yet
implemented in `libs/hathor/*`. Hathor owns world state, lore, narrative, NPC
cognition, quest logic, dialogue, and simulation semantics. Neith owns the
animation, storyboard, engine, and DCC surfaces that can visualize or execute
Hathor-authored worlds.

- **2D animation and storyboard surfaces (Phases 141 and 156)**: Hathor exports
  characters, dialogue, storyboards, scene beats, timing, and narrative intent
  into Neith's 2D animation scene model, exposure sheets, frame-by-frame
  drawing, rigged puppets, lip sync, camera/composite tools, Grease Pencil-class
  2D-in-3D drawing, line-art generation, VR/AR spatial drawing, and
  storyboard/previs workflows.
- **Engine narrative parity (Phases 171-174)**: Hathor integrates with Neith's
  Smart Objects, Gameplay Interactions, Chooser tables, StateTree, behavior-tree
  convergence, Enhanced Input, GameplayTags, GAS cues, gameplay cameras, Common
  UI, Data Registry, localization, Visual Logger, Gameplay Debugger, NavMesh, AI
  Perception, Zone Graph, Mass Traffic, Dataflow, subsystems, Sequencer
  bindings, Blueprint graph depth, Game Features, Modular Gameplay, Rewind
  Debugger, actor pooling, Blender annotations, timeline/pose markers, drivers,
  Python scripting, custom properties, and RNA reflection.

## Neural World Model Integration (planned — Phase 176)

This section describes planned cross-domain work, not yet implemented in
`libs/hathor/*`. Hathor consumes Nous world models for NPC imagination planning,
living-world simulation rollouts, political-intrigue simulator planning,
economy/culture latent dynamics, and on-device NPC cognitive-core upgrades.
Hathor owns world state, lore, narrative constraints, NPC goals, and simulation
semantics; Nous owns reusable RSSM, Dreamer, MuZero, Genie, and benchmark
primitives.

## Training-Data Flywheel (Phases 85–86)

`libs/hathor/training-data` implements this domain's side of the ML-sovereignty
data flywheel: a training-data pipeline that captures worldbuilding and
narrative interactions (lore edits, quest/dialogue authoring, NPC conversations)
as passive training signals. Signals are consent-gated, anonymized where
required, and emitted in the shared flywheel envelope that Nous dataset
management (Phase 87) ingests for training and evaluation. Nous owns the
training infrastructure; this domain owns what constitutes a high-quality domain
signal.
