# Hathor — Systems Deep Dive

> The `libs/hathor/` area: twenty Nx libraries that make up **Hathor, the "World
> Builder" domain** — engine-agnostic worldbuilding, narrative, and simulation
> tooling that turns authored lore into engine-ready and film-ready (CGI)
> production artifacts.

## What this area is

Hathor is Oshun's worldbuilding and narrative-design domain. Its job is to let
authors model a fictional world — its characters, cultures, factions, economies,
laws, geography, timelines, locations, quests, and dialogue — and then compile
that world into artifacts other tools can consume: game-engine quest packages,
film screenplays, and CGI scene/character/timeline "packets" for DCC pipelines
(Maya, Unreal, Blender). Everything here is deliberately **engine-agnostic
TypeScript**: the libraries define domain types and deterministic logic, and
emit interchange data rather than binding to any one runtime.

The area is layered. At the bottom sits `@hathor/domain-models`, the shared type
spine (factions, economies, laws, cultures, geography, timelines, characters,
locations, plus a V2 fighting-game record set) that almost every other library
imports. On top of it are the **engine libraries**: `@hathor/narrative` (quests,
dialogue, story graphs, journals), `@hathor/simulation` (economy / politics /
culture / scenario / physics / NPC-behaviour-tree / state-persistence engines),
`@hathor/theory` (MDA, narrative-theory, and cinematography analysis),
`@hathor/validation` (lore consistency checks), `@hathor/pre-production`
(scriptwriting, storyboarding, and a very large drone production-planning
subsystem), and the AI-facing `@hathor/llm-npc`, `@hathor/narrative-generation`,
and `@hathor/lore-compiler`.

A third group are the **CGI export facades** — `@hathor/characters`,
`@hathor/world`, `@hathor/quests`, and `@hathor/timeline`. Each is described in
its own metadata as an "import facade", but in practice each is a real
packet-builder-plus-validator: it maps the rich domain models into a flat,
schema-versioned CGI packet (e.g. `hathor-world-cgi-scene/v1`) and then
validates that packet for completeness before it crosses into a DCC tool.

Finally there is the **integration and delivery tier**:
`@hathor/event-publisher` and `@hathor/event-handlers` connect Hathor to the
cross-domain event bus, `@hathor/sophia-integration` grounds and fact-checks
lore against the Sophia knowledge services, `@hathor/database` owns the Prisma
schema/client, and `@hathor/client` is the TypeScript SDK over Hathor's HTTP
APIs.

## How it fits the wider system

Hathor consumes from and emits to its sibling domains. `@hathor/event-handlers`
subscribes to Sophia (`sophia.document.ingested`), Isis
(`isis.asset.generated`), and Yemaya (`yemaya.project.created`,
`yemaya.character.created`) events to grow the world graph, while
`@hathor/event-publisher` emits Hathor's own lifecycle events
(`HathorEventTypes` from `@oshun/contracts`) onto the bus via
`@oshun/event-bus`. `@hathor/sophia-integration` reaches into Sophia's search,
graph, and ingestion clients for research grounding and lore validation. The
LLM-facing libraries (`@hathor/narrative-generation`, `@hathor/llm-npc`) compose
a governed `LLMProviderInterface` from `@oshun/ai` plus a deterministic planner,
so generation is provider-injected and fail-loud rather than self-contained. The
CGI facades and `@hathor/lore-compiler` are the outbound boundary toward Bellona
/ DCC and film pipelines. Walk the "used by" edges on any node below to see who
depends on it; the dependency arrows almost all point down toward
`@hathor/domain-models`.

## Entity reference

### @hathor/domain-models

The engine-agnostic type spine for the whole area
(`libs/hathor/domain-models/src`). Its `index.ts` re-exports eight worldbuilding
sub-domains — `faction`, `economy`, `law`, `culture`, `geography`, `timeline`,
`character`, `location` — plus a `common` base layer and a V2 `fighting-game`
narrative-record module, each with its own `types.ts`, `constants.ts`,
`factories.ts`, `utils.ts`, and `validators.ts`. It also ships shared helpers
(e.g. `sortEventsChronologically`, `calendarDateToSortKey`,
`formatCalendarDate`) that the timeline and validation libraries build on.
Nearly every other `@hathor/*` library imports its types, so it is the
foundational node of the domain.

### @hathor/narrative

The interactive-narrative engine (`libs/hathor/narrative/src`): a quest system
(`quest/quest-engine.ts`), a dialogue engine (`dialogue/dialogue-engine.ts`), a
story-graph traverser with effect execution (`story-graph/traversal.ts`,
exporting `StoryGraphTraverser` and `EffectExecutor`), a journal/codex system,
branching utilities, and an export subsystem that serialises stories to Ink,
Yarn, and JSON (`export/ink-exporter.ts`, `yarn-exporter.ts`, `json-exporter.ts`
behind an `exporter-factory`). The `index.ts` re-exports the story-graph surface
selectively to avoid name collisions with the quest module's
`ConditionEvaluator`/`GameStateContext`. Its `Quest` and `StoryArc` types are
the inputs the `@hathor/quests` facade captures.

### @hathor/simulation

The world-simulation engine bundle (`libs/hathor/simulation/src`). It carries
five distinct subsystems, each with a manager + provider/storage seam: `economy`
(markets, trade routes, guilds, a `SeededRandom`, a
`PriceCalculatorProvider.calculatePrice` supply/demand model, event generation),
`politics` (factions, leaders, alliances, conflicts, treaties, elections),
`culture` (trait diffusion, cultural contact/exchange, drift and resilience
analysis), `scenario` (scenario generation and world-state advancement), plus a
`physics` engine (`physics/engine.ts` — a real fixed-step `PhysicsEngine` with
rigid bodies, colliders, constraints, force fields, broad-phase, and Earth/Moon/
zero-G presets), an `npc` behaviour-tree library (`SequenceNode`,
`SelectorNode`, decorators, a `BehaviorTreeBuilder`, and pattern factories), and
a `state` persistence layer with in-memory, Postgres, and Redis backends. All
storage is behind injectable providers (in-memory implementations shipped by
default).

### @hathor/theory

Game-design and storytelling theory tooling (`libs/hathor/theory/src`), in three
managed subsystems. `mda/` implements the Mechanics-Dynamics-Aesthetics
framework (`MDAManager`, a dynamics simulator, aesthetics analyzer,
feedback-loop visualizer, plus `MDA_AESTHETICS` and mechanic templates).
`narrative/` provides story-structure analysis (`NarrativeManager`,
fabula/syuzhet mapping, dramatic irony, pacing analysis, beat-sheet generation,
and structure templates). `cinematography/` covers shot design, composition,
lighting, and colour theory (`CinematographyManager` with
composition/lighting/colour-theory references and a continuity checker). Each
subsystem follows the same `types.ts` / `constants.ts` / `manager.ts` shape with
default in-memory storage and reference-data providers.

### @hathor/validation

Lore-consistency validation (`libs/hathor/validation/src`). Four focused
validators — `timeline/` (chronological order, era boundaries, lifespans),
`causality/` (temporal consistency, cycle detection, causal-chain analysis),
`taxonomy/` (type and hierarchy checking), and `contradiction/` (temporal,
spatial, attribute, relationship, and state contradictions across characters and
locations) — are composed by a top-level `LoreValidator` (`index.ts`) that runs
the configured set, supports `failFast`, caps issues per category, and returns a
merged `LoreValidationResult` with error/warning/info counts. Inputs are the
`@hathor/domain-models` event/era/character/location types.

### @hathor/pre-production

The largest library in the area (`libs/hathor/pre-production/src`, ~258 non-test
implementation files), covering three concerns. `scriptwriting/` is a
"Chronicle" document parser plus narrative-structure analyzer with built-in
templates (Epic Journey, Chronicle, Rise-and-Fall) and a Fountain-style
exporter. `storyboard/` is a visual-planning system (`StoryboardManager`,
frames, sequences, style guides, export). `planning/` is project management plus
an unusually deep **drone-cinematography production-planning** subsystem: dozens
of plan/sample/assess/export systems for flight-path design, choreography, speed
ramps, obstacle avoidance, fleet/formation control, photogrammetry / NeRF /
Gaussian-splatting / LiDAR capture, scan-to-CGI pipelines, and regulatory
compliance (geofencing, NOTAM airspace deconfliction, pre-flight regulatory
packets). Each system ships typed plans, fixtures, and assessment functions.

### @hathor/llm-npc

An LLM-powered NPC "brain" system (`libs/hathor/llm-npc/src`; note the source
header still reads `@yemaya/llm-npc`, but the project name is
`@hathor/llm-npc`). It composes a `brain` (personality manager with Big-Five
traits, emotional-state manager, short/long-term memory, world awareness), a
`dialogue` module (`DialogueGenerator` plus a `SafetyFilter`), a `behavior`
module (`BehaviorController`, NPC-to-NPC conversation), a `platforms` layer with
clients for NVIDIA ACE, Inworld, Convai, and a generic LLM client, a
`ProviderChain` fallback system with circuit breaking, and an `advanced` SOTA
tier (Enneagram + BDI personality, GOAP/HTN behaviour planning,
attention-weighted memory consolidation, dialogue-act and manipulation
detection). Substantial and genuinely implemented, with per-module spec files.

### @hathor/narrative-generation

LLM narrative-generation pipelines (`libs/hathor/narrative-generation/src`). The
design is planner→writer: Neith's deterministic tension/motif machinery plans
the structure, then a governed LLM writes inside it via an injected
`LLMProviderInterface` from `@oshun/ai` (`NarrativeGenerationService` in
`generators.ts`). Around that core it adds prompt builders, a
`QuestBatchGenerator`, a `QualityGatedQuestBatchGenerator`, a `runStagedVolume`
staged generator that measures per-stage quality and corpus diversity and
**STOPs on regression** (`staged-volume.ts`, reusing `corpusDiversity` from
`@oshun/content-quality-judge`), a `LoreConsistencyChecker`, and a review
workflow. The model boundary is fail-loud: with no provider wired the writer
throws `NarrativeGenerationError` rather than fabricating output.

### @hathor/lore-compiler

The outbound compiler (`libs/hathor/lore-compiler/src`) that turns narrative
content into engine-ready and film-ready artifacts. `engine/quest-compiler.ts`
compiles quests for game engines (Unreal, Unity, Godot, Blender) into typed
`CompiledQuest` artifacts; `film/screenplay-compiler.ts` compiles stories into
screenplays exportable as Fountain/FDX/PDF; `bellona/package-builder.ts` builds
engine-interchange packages for the Bellona pipeline; and
`v2/v2-package-compiler.ts` emits the V2 fighting-game contract. The `index.ts`
exposes factory functions (`createQuestCompiler`, `createScreenplayCompiler`,
`createPackageBuilder`).

### @hathor/ideation

The pre-writing surface (`libs/hathor/ideation/src/index.ts`): where an idea
lives before it is canon. It owns capture and triage (a status machine from
`captured` through `developing`/`shortlisted`/`selected` to `promoted`, with
append-only revisions and cycle-checked lineage links), the **development
ladder** (logline → synopsis → treatment → beat outline, where editing means
appending a version rather than overwriting one), and generators split by tier:
deterministic ones (SCAMPER operators, phonotactic naming, premise
combinatorics, MAP-Elites quality-diversity selection) and model-tier ones that
fail loud when no provider is wired rather than fabricating a draft.

Selection is quantitative. Option sets are compared with pairwise tournaments
fitted by Bradley–Terry (plus Elo for live scheduling), judge disagreement is
measured rather than eyeballed, and every kill or promotion writes an immutable
`DecisionRecord` — rejected siblings, scores as they stood, stated reason,
decider — so a later re-scoring can never rewrite why a past call was made.

Four cross-cutting guards wrap that surface, each enforced at a seam rather than
at call sites:

- **Content safety.** `withContentSafetyScreening` wraps the storage provider so
  model-generated ideas pass Yemaya's `ContentFilterManager` before they
  persist; blocked content becomes a redacted tombstone carrying the category
  result and a digest of the refused text, never a silent drop.
  `withPromptInjectionScreening` wraps the model provider so user text is
  screened before it reaches a prompt.
- **Canon guardrails.** The same contradiction/causality validators run at both
  ends of an idea's life with opposite consequences: advisory at capture (an
  idea that contradicts canon is often the point), blocking at promotion, where
  an override requires a named decider and a stated reason and writes an
  `override` DecisionRecord.
- **Attribution.** The AI-vs-human split is computed from the revision trail —
  the longest common subsequence between the model's origin draft and the
  current text — so the disclosure describes the idea as it is now, not as it
  was generated. Records go through Yemaya's `EthicsManager`, which also holds
  the likeness consent that a real-person character concept needs before it can
  be promoted.
- **Access.** `idea:read`, `idea:create`/`idea:update`, `idea:judge`, and
  `idea:promote` are distinct permissions in the shared `@yemaya/rbac` registry:
  a reviewer judges what they cannot rewrite, and an editor drafts but cannot
  commit to canon.

Promotion hands the finished idea to its owning system (character, culture,
world entity, quest) through `@hathor/narrative` and `@hathor/domain-models`,
recording an append-only promotion ledger whose rows survive deletion of the
target — marked, never removed, so the idea's history always explains what it
became.

### @hathor/characters

A CGI character-definition export facade
(`libs/hathor/characters/src/index.ts`). Despite the "import facade" label it is
a real builder: `createHathorCharactersCgiPacket` maps `@hathor/domain-models`
`Character` records (and `@hathor/pre-production` `CharacterReference`s) into a
flat `HathorCharactersCgiPacket` — flattening appearance
(height/age/hair/eyes/skin), costume designs, and visual references — and
`validateHathorCharactersCgiPacket` checks for missing characters, appearance,
costumes, visual references, and export metadata, emitting blocking vs. warning
issues. It defaults the export target to `['maya','unreal','blender']` under
schema `hathor-characters-cgi/v1`.

### @hathor/world

A CGI scene-definition export facade (`libs/hathor/world/src/index.ts`).
`createHathorWorldCgiSceneDefinition` flattens `Location`, `Region`, `Era`, and
`Culture` domain models — including buildings, rooms, points of interest,
architectural styles, terrain, climate, and a coordinate system (origin /
up-axis / scale) — into a `HathorWorldCgiSceneDefinition` under schema
`hathor-world-cgi-scene/v1`, and `validateHathorWorldCgiSceneDefinition`
enforces that required locations, primary time period, cultures, architecture
styles, and coordinate/export metadata are all present. Like the other facades
it is a real mapper-plus-validator, not a stub.

### @hathor/quests

A quest scene-dependency capture facade (`libs/hathor/quests/src/index.ts`).
`createHathorQuestSceneDependencyPacket` takes `Quest` and `StoryArc` records
from `@hathor/narrative` plus author-supplied scene requirements, cross-indexes
which scenes satisfy which quests/arcs, and produces a
`HathorQuestSceneDependencyPacket`. `validateHathorQuestSceneDependencyPacket`
performs real dependency checking — missing scenes/quests/arcs/objectives,
dangling scene and quest dependencies, and missing capture requirements — under
schema `hathor-quests-scene-dependencies/v1`.

### @hathor/timeline

A narrative scene-order facade (`libs/hathor/timeline/src/index.ts`). It
reconciles **story order** against **shoot order**:
`createHathorTimelineSceneOrderPacket` sorts `HistoricalEvent`s chronologically
(via `sortEventsChronologically` / `calendarDateToSortKey` from
`@hathor/domain-models`), assigns each linked scene a derived `storyOrder`, and
captures world-state tags. `validateHathorTimelineSceneOrderPacket` detects
story-order conflicts and **causal-dependency violations** (a scene appearing
before its causal prerequisite), plus missing scenes/events/world-state and
export metadata, under schema `hathor-timeline-scene-order/v1`. The most
algorithmically interesting of the four facades.

### @hathor/sophia-integration

The bridge between Hathor's world model and Sophia's knowledge services
(`libs/hathor/sophia-integration/src`). Three services compose into a unified
`HathorSophiaIntegration` client: `CitationService` links world lore to research
sources, `LoreValidationService` fact-checks lore against research, and
`ResearchGroundingService` generates grounded world content from a topic. The
unified client is fail-honest by construction — research grounding is only
instantiated when both a graph client and an ingestion client are supplied, and
the `ground()` helper throws if those are absent rather than returning
fabricated results. All Sophia clients are injected interfaces
(`SophiaSearchClient`, `SophiaGraphClientForGrounding`,
`SophiaIngestionClientForGrounding`).

### @hathor/event-handlers

Hathor's inbound cross-domain event subscriptions
(`libs/hathor/event-handlers/src`). `setupHathorEventHandlers` wires the
`HATHOR_SUBSCRIPTIONS` map — `sophia.document.ingested`, `isis.asset.generated`,
`yemaya.project.created`, `yemaya.character.created` — onto an
`@oshun/event-bus` `IEventBus`, builds a per-event `HathorHandlerContext` (world
graph, world/suggestion/character/asset/ relationship repositories, a job queue,
logger), and returns a handle with `stop()`, `isRunning()`, and `getStats()`.
The four handlers live under `src/handlers/` and grow/maintain the world graph
from sibling-domain activity; `getHandlerRegistrations()` exposes per-event
concurrency for custom setups.

### @hathor/event-publisher

Hathor's outbound event surface (`libs/hathor/event-publisher/src`). The
`HathorEventPublisher` class (`hathor-event-publisher.ts`) lazily initialises an
`@oshun/event-bus` connection and exposes type-safe publish methods for the
domain's lifecycle events — world created/published/validated, element added,
narrative generated, simulation started/completed — keyed off `HathorEventTypes`
from `@oshun/contracts`. It honours an `enabled` flag (logging "disabled" and
skipping the bus when off) and is exposed as a singleton via
`getHathorEventPublisher` / `createHathorEventPublisher` /
`resetHathorEventPublisher`.

### @hathor/database

The persistence layer (`libs/hathor/database/src` + a `prisma/` schema). It
exports a Prisma-client wrapper (`getHathorClient`, `createHathorClient`,
`connect`/`disconnect`, `transaction`, `executeRaw`, `queryRaw`, `isConnected`)
plus a set of hand-mirrored string-literal union types (`WorldStatus`,
`WorldGenre`, `EntityType`, `QuestStatus`, `SimulationType`,
`ValidationSeverity`, etc.) so consumers can type against the schema **before**
running `prisma:generate`. The fuller generated model exports are present in
`index.ts` but commented out, gated on code generation — an honest "available
after generation" seam rather than a fake export.

### @hathor/client

The TypeScript SDK over Hathor's HTTP APIs (`libs/hathor/client/src`), a
tsup-built package. `HathorClient` (`client.ts`) composes three API resources —
`WorldResource`, `NarrativeResource`, `SimulationResource` (under `src/api/`) —
over a pluggable `HttpTransport` with a typed error hierarchy (`HathorError`,
`NetworkError`, `TimeoutError`, `NotFoundError`, `ValidationError`,
`RateLimitError`, …). Beyond raw API calls it ships `helpers/` with real
client-side logic: world-state snapshots and relationship maps, quest generation
from templates (`QUEST_TEMPLATES`, `generateQuestChain`), and lore validation
(`validateWorldLore`). It also carries contract tests
(`contracts/hathor-openapi.contract.spec.ts`,
`hathor-cross-service.contract.spec.ts`) that keep the client aligned with the
service's OpenAPI surface.

### @hathor/training-data

Phase 85–86 flywheel producer for the NPC/world domain
(`libs/hathor/training-data/src`): `HathorTrainingDataPipeline` turns eleven
`HathorTrainingKind` signals — `npc-dialogue`, `npc-emotion`,
`npc-memory-relevance`, `economy-simulation`, `political-simulation`,
`cultural-evolution`, `narrative-quality`, and peers — into governance-gated
(`governanceGrantId`), anonymized `HathorTrainingRecord`s delivered to a
pluggable `HathorTrainingSink`.
