Domain libraries · entity catalog

hathor library

Authored subsystem deep-dive for hathor, layered on the code-linked entity catalog — what each system is, why it exists, and how it fits.

authored deep-dive
21entities4layers20deep-dives

On this page

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 catalog (21)#

The 21 tracked Nx projects in hathor, each a code-linked entity node — package, type, source path, declared targets, and its internal dependency graph (depends-on / used-by, resolved from the package manifests, §6/§8), read from the project graph. Grouped by architectural layer; walk the dependency links to travel the system. 20 of these carry an authored deep-dive (what / why / how it fits); the rest are generated scaffolds awaiting one.

clients (1)#

lib

@hathor/client

#

TypeScript client SDK for Hathor world simulation APIs

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.

buildtestlint
layer: clientsscope: hathorowner: @GreyChimp

data (1)#

lib

@hathor/database

#

Database schema and Prisma client for Hathor world simulation services

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.

buildtestlintdb:seeddb:seed:testprisma:generateprisma:migrate:deploy
layer: datascope: hathorowner: @GreyChimp

domain (17)#

lib

@hathor/characters

#

Facade (shim): CGI character packet contract only — character modeling logic lives in @hathor/domain-models (character) and @hathor/pre-production. Do not add logic here; see README.

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 CharacterReferences) 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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/domain-models

#

Engine-agnostic domain models for worldbuilding, narrative, and simulation systems

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/ideation

#

Ideation pipeline domain model: capture, lineage, revisions, option sets, selection, promotion (see docs/domains/hathor-ideation-proposal.md)

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/llm-npc

#

LLM-powered NPC system with personality, memory, and behavior

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.

buildtestlinttypecheck
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/lore-compiler

#

Hathor lore compiler for generating engine-ready and film-ready artifacts

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).

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/narrative

#

Narrative systems for worldbuilding: quests, dialogues, story graphs, and journal/codex systems

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/narrative-generation

#

LLM narrative generation pipelines: Neith tension/motif planning as the planner, governed LLM writers for quest narrative, story beats, and NPC backstory

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.

testlinttypecheck
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/pre-production

#

Pre-production tools for scriptwriting, storyboarding, and production planning

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/quests

#

Facade (shim): scene-dependency packet contract only — quest logic lives in @hathor/narrative (quest). Do not add logic here; see README.

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/simulation

#

Hathor simulation engines for economy, politics, and culture evolution

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).

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/sophia-integration

#

Integration layer between Hathor world simulation and Sophia knowledge services

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).

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/theory

#

Game design theory, narrative theory, and cinematography tools for Hathor worldbuilding

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/timeline

#

Facade (shim): narrative scene-order packet contract only — timeline logic lives in @hathor/domain-models (timeline). Do not add logic here; see README.

A narrative scene-order facade (libs/hathor/timeline/src/index.ts). It reconciles story order against shoot order: createHathorTimelineSceneOrderPacket sorts HistoricalEvents 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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
library

@hathor/training-data

#

Anonymized NPC and simulation training data collectors for Hathor

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 HathorTrainingRecords delivered to a pluggable HathorTrainingSink.

buildtestlinttypecheck
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/validation

#

Validation utilities for timeline consistency, causality, taxonomy, and lore contradiction detection

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp
lib

@hathor/world

#

Facade (shim): CGI scene-definition contract only — worldbuilding logic lives in @hathor/domain-models (culture/geography/location/timeline). Do not add logic here; see README.

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.

buildtestlint
layer: domainscope: hathorowner: @GreyChimp

integration (2)#

lib

@hathor/event-handlers

#

Cross-domain event handlers for Hathor world-building system

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.

buildtestlinttypecheck
layer: integrationscope: hathorowner: @GreyChimp
lib

@hathor/event-publisher

#

Event publisher for the Hathor (World Builder) domain

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.

buildtestlint
layer: integrationscope: hathorowner: @GreyChimp