# Maya Domain — Technical Specifications

> Technical specification of the Maya virtual-universe domain **as implemented
> in code today**. Maya is an early-stage domain: the libraries below all exist
> on disk with real source, but they sit at different depths. This document
> describes the domain objects, enums, evaluation logic, schemas, services,
> build targets, and integration points that the source actually defines.
> Sections that describe a roadmap rather than shipped code are explicitly
> labelled `(planned)`.

---

This document is a precise inventory of Maya's implemented surface: the Rust
types, TypeScript schemas, enumerations, and evaluation functions that exist in
source today. It is the authoritative reference for engineers integrating with
or extending Maya. Content is organized by library, starting with the Rust
engine workspace, then the seven TypeScript readiness facades, and finally the
TypeScript service libraries.

---

## Library Inventory

Maya has **17 libraries under `libs/maya/`**. There is no `apps/maya/` or
`services/maya/`. The libraries fall into three implementation shapes:

| Library           | Shape                            | Source size            | Status      |
| ----------------- | -------------------------------- | ---------------------- | ----------- |
| `engine-core`     | Rust Cargo workspace + TS facade | 28 crates, ~1074 files | Implemented |
| `client`          | TypeScript library               | ~30 source modules     | Implemented |
| `database`        | TypeScript library               | ~30 source modules     | Implemented |
| `documentation`   | TypeScript library               | ~30 source modules     | Implemented |
| `games`           | TypeScript library               | ~100 source modules    | Implemented |
| `inspirations`    | TypeScript library               | ~75 source modules     | Implemented |
| `server`          | TypeScript library               | ~27 source modules     | Implemented |
| `testing`         | TypeScript library               | ~48 source modules     | Implemented |
| `tooling`         | TypeScript library               | ~48 source modules     | Implemented |
| `genesis-terrain` | TypeScript readiness facade      | 1 source module        | Implemented |
| `genesis-urban`   | TypeScript readiness facade      | 1 source module        | Implemented |
| `genesis-flora`   | TypeScript readiness facade      | 1 source module        | Implemented |
| `physics`         | TypeScript readiness facade      | 1 source module        | Implemented |
| `renderer`        | TypeScript readiness facade      | 1 source module        | Implemented |
| `scene`           | TypeScript readiness facade      | 1 source module        | Implemented |
| `world`           | TypeScript readiness facade      | 1 source module        | Implemented |

**"Readiness facade"** is a precise description, not a euphemism. Each of the
seven single-module libraries exports a domain-specific TypeScript evaluation
function (`evaluateMaya*`) plus the input/output/issue types it operates on.
Their own `package.json` `description` fields say so verbatim — e.g.
`@maya/physics` is _"TypeScript facade for Maya physics simulation readiness
across cloth, fluid, destruction, and particles"_. They contain real scoring
formulas, not stubs, but they evaluate readiness rather than run the simulation.
The runtime engines they describe live as **Rust crates inside `engine-core`**
(`maya-physics`, `maya-renderer`, `maya-world`, etc.).

---

## Technology Stack

The table below records the precise dependency versions and Cargo configuration
used by the engine workspace. This is the ground truth for any engineer setting
up the Rust toolchain.

| Layer                | Technology                                                    |
| -------------------- | ------------------------------------------------------------- |
| Engine kernels       | Rust — `engine-core` Cargo workspace, 28 crates               |
| Math                 | Rust, `glam` 0.29 (SSE2 on x86_64, NEON on aarch64)           |
| Concurrency          | Rust, `crossbeam-channel` / `crossbeam-deque` / `parking_lot` |
| Serialization        | Rust, `serde` / `serde_json` / `bincode`                      |
| Hot-reload           | Rust, `notify` 7 + `libloading` 0.8                           |
| TypeScript libraries | TypeScript (ES modules), Node.js                              |
| Testing              | Vitest (TS), `cargo test` (Rust)                              |
| Build system         | Nx `nx:run-commands` executors wrapping `tsc` / `cargo`       |

The `engine-core` Cargo workspace pins `edition = "2021"`, `version = "0.1.0"`,
`license = "Apache-2.0"`, resolver 2, and a release profile with `lto = true`,
`codegen-units = 1`, `opt-level = "s"`.

> The earlier draft of this document listed `wgpu`, `Rapier`, Havok, PhysX,
> Jolt, `cpal`, `symphonia`, `wasm-bindgen`, and a custom UDP protocol as stack
> entries. None of those crates appear in the `engine-core` workspace
> `Cargo.toml`. The renderer, physics, and audio crates are currently
> backend-agnostic Rust modules; they do not yet bind a concrete GPU, physics,
> or audio vendor SDK. They are documented below as what they are.

---

## Engine Core — Rust Workspace (`@maya/engine-core`)

`libs/maya/engine-core/` is a Cargo workspace of **28 member crates** plus a
thin TypeScript facade (`src/index.ts`). The Nx `build`/`check`/`test`/`lint`
targets currently compile a subset of ten crates (`maya-kernel`,
`maya-renderer`, `maya-scene`, `maya-world`, `maya-resource`, `maya-ecs`,
`maya-math`, `maya-plugin-api`, `maya-jobs`, `maya-time`); the remaining crates
build via `pnpm cargo:build` / `cargo build --workspace`.

### Workspace Members

The table below lists every crate, its Rust file count, and its responsibility.
Crates with more files carry more domain logic; `maya-embodiment` at 153 files
is the single deepest crate.

| Crate                    | Rust files | Responsibility                                                 |
| ------------------------ | ---------: | -------------------------------------------------------------- |
| `maya-plugin-api`        |          1 | Plugin trait, capability, and error contracts                  |
| `maya-kernel`            |          5 | Plugin registry, hot-reload watcher, dependency resolver       |
| `maya-ecs`               |          6 | Archetype-based Entity-Component-System                        |
| `maya-jobs`              |          4 | Chase-Lev work-stealing job pool                               |
| `maya-fibers`            |          4 | Cooperative `async`-driven coroutine executor                  |
| `maya-alloc`             |          6 | Bump / scratch / frame / pool / stack allocators               |
| `maya-math`              |          4 | `glam` re-export plus `Transform` / `Aabb` / `Ray` / `Color`   |
| `maya-spatial`           |          4 | Loose octree, SAH BVH, balanced k-d tree                       |
| `maya-scene`             |          2 | Scene graph                                                    |
| `maya-resource`          |          4 | Resource/asset handles                                         |
| `maya-hot-reload`        |          5 | Asset/script hot-reload support                                |
| `maya-serialize`         |          5 | Serialization helpers                                          |
| `maya-reflect`           |          8 | Reflection / type metadata                                     |
| `maya-events`            |          5 | In-engine event bus                                            |
| `maya-world`             |         25 | Chunk-based world partitioning, streaming, LOD, origin rebase  |
| `maya-time`              |         19 | Fixed-timestep clock, calendar, seasons, rollback, time travel |
| `maya-renderer`          |         95 | Frame-graph render pipeline and visual-feature modules         |
| `maya-physics`           |         59 | Backend-agnostic physics: collision, constraints, cloth, fluid |
| `maya-audio`             |         60 | HRTF / ambisonics / occlusion / propagation spatial audio      |
| `maya-atmosphere`        |         75 | Physically based sky, clouds, weather, water surfaces          |
| `maya-embodiment`        |        153 | Avatar morphing, animation, IK, retargeting, networking        |
| `maya-souls`             |         76 | LLM dialogue, memory, personality, autonomous NPC behaviour    |
| `maya-nexus`             |         77 | Client-server topology, sessions, replication, social systems  |
| `maya-immersion`         |         76 | VR/XR device abstraction, hand tracking, haptics               |
| `maya-genesis-terrain`   |         61 | Procedural terrain noise, erosion, biomes, LOD                 |
| `maya-genesis-urban`     |        139 | Procedural roads, blocks, zoning, buildings, infrastructure    |
| `maya-genesis-flora`     |         61 | Procedural L-system / space-colonization vegetation            |
| `maya-integration-tests` |          1 | Cross-crate integration tests                                  |

Phase 40 §40.22–40.28 packages present as TypeScript libraries under
`libs/maya/` (not engine-core crates): `genesis-nca` (Neural Cellular Automata
growth), `genesis-tiling` (Wang/aperiodic-monotile tiling), `genesis-physarum`
(slime-mold transport networks), `genesis-sketch` (sketch-to-terrain),
`genesis-neural-flora` (neural L-systems), `genesis-scene-agent` (LLM-agent
scene orchestration), plus `future-input` (BCI/EMG emerging-input abstraction,
§40.28).

### `maya-kernel` — Engine Kernel

The kernel is the engine's boot-and-plugin manager. It orchestrates three
subsystems that handle the plugin lifecycle from installation through frame
dispatch:

- **`PluginRegistry`** / **`PluginSlot`** — loaded-plugin set, lifecycle states,
  capability-to-plugin mapping, registration and removal.
- **`HotReloadWatcher`** (`HotReloadConfig`, `HotReloadEvent`) — monitors plugin
  library files on disk via the `notify` crate and triggers reload.
- **`DependencyResolver`** — topological sort of plugins by declared
  dependencies, with circular-dependency detection.
- **`NativePluginLoader`** — dynamic native plugin loading.
- **`KernelError`** — error enum wrapping `PluginError` from `maya-plugin-api`.

The kernel exposes APIs for registering Rust-native and dynamic plugins, running
a frame loop with phased plugin dispatch, hot-reloading at safe points, and
delivering inter-plugin messages over `crossbeam-channel`.

### `maya-ecs` — Entity-Component-System

An archetype-based ECS inspired by `bevy_ecs` / `hecs` / `legion`. The archetype
model stores entities with identical component signatures together in the same
table, so iterating a component type is a tight linear memory scan:

- **`Entity`** — generational index `{ index, generation }`; `EntityAllocator`
  with free-list for O(1) spawn/despawn and stale-reference detection;
  `EntityLocation` tracks archetype placement.
- **`Archetype`** / `ArchetypeId` / `ArchetypeKey` — components stored in
  archetype tables with Structure-of-Arrays layout.
- **`BlobVec`** — type-erased per-component column.
- **`ComponentId`** / `ComponentInfo` / `ComponentRegistry` — component
  registration metadata.
- **`World`** — `spawn` / `spawn2` / `spawn3`, `despawn`, `add_component`,
  `remove_component`, `get_component(_mut)`, `has_component`, and `query` /
  `query_mut` / `query2` / `query2_mut` / `query3` iteration over matching
  archetypes.

### `maya-jobs` — Work-Stealing Job System

The job system distributes CPU-bound work across all available cores using a
Chase-Lev work-stealing algorithm. Each worker thread owns a local LIFO deque
and steals FIFO from peers when idle, maximising cache locality for short-lived
work while preventing starvation.

Multi-threaded job pool on Chase-Lev work-stealing deques (`crossbeam-deque`). N
worker threads each own a local LIFO deque; a global injector accepts work from
any thread; idle workers steal FIFO from peers. Public surface: `JobPool` /
`JobPoolConfig` / `Scope`, `JobHandle` / `JobGroup` / `JobPriority`,
`JobCounter`. Supports fire-and-forget spawn, DAG dependencies via atomic
counters, job groups, scoped stack-borrowing execution, parallel-for, and active
waiting that participates in work-stealing.

### `maya-fibers` — Cooperative Coroutines

Fibers provide a cooperative scheduling layer for long-running async work (such
as network calls and asset loading) that must coexist with the synchronous
real-time tick loop. Suspension happens only at `.await`, so no preemption is
needed.

Tick-driven executor over Rust `async`/`await` (stackless coroutines). Public
surface: `FiberExecutor` / `ExecutorConfig` / `TickStats`, `FiberId` /
`FiberPriority` / `FiberState`, `Signal` / `CountedSignal`, and
`fiber::{ yield_now, wait_ticks }`.

### `maya-alloc` — Memory Allocators

General-purpose allocators for the engine's different allocation lifetimes. Each
strategy eliminates a class of heap fragmentation or GC pressure:

- `BumpAllocator` (+ `BumpSavedState`) — fast bump allocation that resets at a
  frame boundary.
- `ScratchArena` — nested save/restore scopes for temporary scratch memory.
- `FrameArena` — double-buffered ping-pong for per-frame data that outlives a
  single scope.
- `Pool` — paged pool with generational handles and a hierarchical free-slot
  bitmask for O(1) alloc/free of fixed-size objects.
- `StackAllocator` — marker-based LIFO.
- `DoubleEndedStack` — bottom-up + top-down in one buffer.

### `maya-math` — Math Library

Re-exports the full `glam` crate as the math backend and adds `Transform`
(position + rotation + scale for scene-graph nodes), `Rect`, `Aabb`, `Ray` /
`Ray2d`, and `Color` (linear RGBA with conversion helpers). A `prelude` module
re-exports the common `glam` types.

### `maya-spatial` — Spatial Acceleration

Three complementary spatial data structures serve different query patterns: the
octree handles dynamic objects that move each frame, the BVH optimises static
geometry ray tests, and the k-d tree answers point-set proximity queries.

- `octree::Octree` — loose octree for dynamic scenes; insert/remove/update plus
  AABB / sphere / ray queries.
- `bvh::Bvh` — bounding volume hierarchy with binned SAH construction for static
  geometry and efficient ray intersection.
- `kdtree::KdTree` — balanced k-d tree for nearest-neighbour, k-NN, and range
  queries over point sets.

### `maya-world` — Chunk World Partitioning

The world crate is the spatial backbone for large and infinite worlds. It
manages a chunk grid where each chunk progresses through a lifecycle FSM, and
provides streaming, LOD, culling, origin rebasing, instancing, and migration
tooling.

Modules: `async_ops`, `bounds`, `chunk`, `config`, `coord`, `culling`, `error`,
`grid`, `instancing`, `level`, `lod`, `lod_manager`, `merge_diff`, `migration`,
`pipeline`, `provider`, `query`, `rebase`, `serialization`, `streaming`,
`state`, `template`, `validation`, `version`.

Key types: `ChunkCoord` (integer 3D address), `WorldConfig` /
`WorldConfigBuilder` / `WorldBounds`, `Chunk<T>`, `WorldGrid<T>` / `GridStats`,
`ChunkRegion` / `RegionIter`, `StreamingManager` / `FocusPoint` /
`StreamingUpdate`, `StreamingPipeline` / `PipelineConfig` / `StreamingStats` /
`TickResult`, `LodCalculator` / `LodAssignment`, `OriginRebase` / `RebaseConfig`
/ `RebaseEvent` / `WorldPosition`, `InstanceManager` / `WorldInstance` /
`InstanceSnapshot`, `ChunkProvider` / `CallbackProvider` / `ChunkRequest` /
`ChunkResponse`.

#### `ChunkState` Lifecycle FSM (`maya-world/src/state.rs`)

Every chunk moves through a defined sequence of states. The FSM ensures that
chunks are never accessed before their data is ready, and that unloading is
cleanly sequenced:

```
Unloaded ──► Loading ──► Active ⇄ Frozen ──► Unloading ──► Unloaded
```

| State       | Meaning                                                |
| ----------- | ------------------------------------------------------ |
| `Unloaded`  | Not loaded; no data in memory.                         |
| `Loading`   | Being asynchronously loaded from storage or generated. |
| `Active`    | Fully loaded and actively simulated/rendered.          |
| `Frozen`    | Temporarily suspended — data in memory but not ticked. |
| `Unloading` | Being asynchronously saved/unloaded.                   |

`ChunkState` provides a transition-validity check that prevents illegal state
changes at runtime.

### `maya-time` — Time and Simulation

Time management covers the fixed-timestep accumulator loop, calendar and
in-world seasons, determinism, time dilation, rollback, and debug time travel.
The list of modules gives a complete picture of what is implemented:

Fixed-timestep accumulator loop (the _Fix Your Timestep!_ pattern). Modules:
`accumulator`, `calendar`, `clock`, `day_night`, `debug_step`, `deterministic`,
`dilation`, `event_scheduler`, `fixed_timestep`, `historical`, `interpolation`,
`rollback`, `seasons`, `speed_control`, `stats`, `temporal_debug`,
`time_travel`, `time_zones`. Key types: `FixedTimestep` (`from_hz`,
`with_max_accumulation`), `SimulationClock`, `FrameTick`, `FrameStats`,
`StepAccumulator`.

### `maya-renderer` — Render Pipeline

The renderer organises all visual features as nodes in a directed acyclic render
graph. The graph compiler infers resource lifetimes and pass ordering from each
pass's declared reads and writes, eliminating manual barrier management.

Frame-graph render pipeline. `render_graph` provides automatic resource
management over a DAG of render passes: `RenderGraph`, `TextureDesc`,
`TextureFormat`, `ResourceUsage` flags, `add_pass` builder, `compile`. The crate
has **~94 feature modules** including `adaptive_resolution`, `anti_aliasing`,
`area_light_shadows`, `async_compute`, `auto_lod`, `auto_quality`, `backend`,
`bindless`, `bloom_energy_conservation`, `cascaded_shadow_maps`,
`chromatic_aberration`, `clear_coat_materials`, `cloth_shading`,
`anisotropic_materials`. These are backend-agnostic Rust modules; no concrete
GPU API binding (Vulkan/Metal/DX12/WebGPU) is present in the crate's
dependencies.

### `maya-physics` — Physics

The physics crate uses a backend registry rather than committing to a single
solver, so the simulation API is stable while the underlying implementation can
be swapped. The public surface covers the full range of phenomena a game world
needs:

Backend-agnostic physics layer. Public surface includes `PhysicsBackendRegistry`
(capability-based backend selection), `PhysicsSceneConfig` (gravity, timestep,
CCD, GPU simulation, large-world), `CollisionLayerSet` (object layers,
broadphase layers, pairwise matrix), `PhysicsMaterialSet` (reusable surface
materials, friction/restitution), `ConstraintSet` (hinge / slider / ball / fixed
/ spring joints), `RagdollArticulation` (skeleton-to-body mapping, pose
round-trip), `VehicleConfig` (wheeled / tracked / hover drivetrains),
`BuoyancySimulator`, `PhysicsInterpolator` (fixed-step snapshot interpolation),
`PhysicsDebugVisualizer`, `CollisionEventDispatcher` (begin/persist/end events),
`PhysicsAnimationBlender`, and cloth solvers `MassSpringCloth`, `PbdCloth`,
`GpuClothSolver`. Crate source covers cloth (PBD, wind, tearing, self-collision,
LOD), fluid (FLIP, GPU, bubbles, rigid interaction, cache), destruction
(Voronoi, prefractured, cleanup, audio), and secondary motion (hair/fur,
rope/cable, jiggle, inflatable).

### `maya-audio` — Spatial Audio

The audio crate implements spatial sound processing through successive layers:
source spatialization (HRTF or ambisonics), occlusion (direct-path blocking,
grazing obstruction, frequency-dependent transmission), and room propagation
(portal routing, opening propagation through apertures).

Layered spatial-audio engine: binaural HRTF rendering for mono point sources
(analytic dataset), personalized HRTF estimation from ear/head scan descriptors,
ambisonics encoding (ACN ordering, SN3D/N3D normalization, first/second/third
order), VR binaural rendering with headset profiles and head-pose transforms,
distance-rolloff spatial-gain models, Doppler pitch shift, occlusion analysis
(direct-path blocking, grazing obstruction, frequency-dependent transmission),
portal room-to-room routing, opening propagation through apertures, VR
head-tracking with predicted display time.

### `maya-atmosphere` — Sky, Weather, Water

The atmosphere crate's top-level entry point computes sky radiance from first
principles. The ~75 crate modules cover every atmospheric phenomenon from aurora
rendering to ocean caustics.

`PhysicallyBasedAtmosphereScatteringSystem` samples sky radiance from an
observer position, view direction, and sun direction. Crate modules include
`accurate_celestial_positioning`, `alien_sky_configurations`,
`artificial_lighting_at_night`, `aurora_rendering`,
`blizzard_visibility_effects`, `boat_wake_and_trails`, `caustics_rendering`,
`cloud_coverage_control`, `cloud_god_rays`, `cloud_lighting_shadows`,
`cloud_lod_performance`, `cloud_movement_evolution`, `cloud_noise_generation`,
`cloud_preset_library`, and more (~75 files spanning clouds, weather, and water
surfaces).

### `maya-embodiment` — Avatars (153 files)

The avatar system is built around a parametric body morphing system that drives
rig bindings and clothing-fit metrics from a set of shape descriptors. The
animation stack layers on top, providing IK, motion matching, retargeting,
compression, and secondary motion.

`ParametricBodyMorphingSystem` combines descriptor-driven sliders, rig bindings,
body measurements, clothing-fit metrics, and corrective passes
(`ParametricBodyMorphRequest`, `BodyMorphShape`). Crate modules cover
`accessory_attachment_points`, `accessory_wearables`, `aging_weathering`, and a
deep animation stack: `animation_additive`, `animation_blending`,
`animation_compression`, `animation_foot_ik`, `animation_full_body_ik`,
`animation_hand_ik`, `animation_look_aim_ik`, `animation_montage`,
`animation_motion_matching`, `animation_pose_search`, `animation_procedural`,
`animation_retargeting`, plus accessibility testing tools.

### `maya-souls` — AI NPCs (76 files)

The NPC AI stack is built on a provider-neutral chat-completion layer so that
the same personality and behaviour logic works with any LLM backend. The
`llm_integration` module defines all request/response types; behaviour, memory,
and social modules build on top of it.

`llm_integration` module is a provider-neutral chat-completion layer:

- `MayaLlmProviderKind` — provider enum (normalizes Claude / GPT / local
  Llama-style APIs).
- `MayaLlmMessageRole`, `MayaLlmFinishReason`, `MayaLlmToolChoice`,
  `MayaLlmMessagePart` — message-shape enums.
- `MayaLlmMessage`, `MayaLlmToolDefinition`, `MayaLlmRequest`,
  `MayaLlmResponse`, `MayaLlmChoice`, `MayaLlmUsage` — request/response model.
- `MayaLlmProviderCapabilities`, `MayaLlmProviderConfig`,
  `MayaLlmIntegrationConfig`, `MayaLlmTransportRequest` /
  `MayaLlmTransportResponse` — provider configuration and transport.
- `MayaLlmIntegrationLayer<TTransport>` — transport-generic integration layer
  with `MayaLlmProviderStats` / `MayaLlmIntegrationStats`.
- `MayaLlmIntegrationError` — error enum.

Other crate modules: `big_five_personality`, `behavior_tree_system`,
`goap_planning`, `episodic_memory`, `emotional_memory`,
`emotional_state_machine`, `emotional_decay_transitions`,
`memory_consolidation`, `memory_embedding`, `memory_forgetting_curves`,
`memory_importance_scoring`, `memory_persistence`, `memory_retrieval`,
`memory_search`, `conversation_branching`, `conversation_context`,
`conversation_steering`, `character_arc_tracking`, `character_knowledge_base`,
`character_personality_prompt`, `character_voice_consistency`,
`community_dynamics_simulation`, `cultural_norm_enforcement`,
`daily_schedule_routine_system`, `faction_group_membership`,
`family_kinship_system`, `forbidden_topic_guardrails`,
`friendship_rivalry_dynamics`, `influence_persuasion_systems`,
`job_occupation_behaviors`, `mood_system`, `motivation_goal_system`,
`multimodal_input_handling`, `need_satisfaction_behaviors`,
`npc_interruption_handling`, `npc_to_npc_autonomous_interactions`,
`nvidia_ace_integration`, `opinion_formation_change`, and more.

### `maya-nexus` — Multiplayer (77 files)

The multiplayer crate models a three-tier topology: gateways admit clients and
negotiate protocol versions; simulation nodes own authoritative state for a
spatial authority domain; clients send commands and consume snapshots and
events. All communication travels over typed envelopes — the implementation is
transport-agnostic so the underlying network layer can be swapped.

Deterministic client-server networking core. Topology model: **gateways** admit
clients, negotiate protocol versions, and issue session tickets; **simulation
nodes** own authoritative session state for an authority domain; **clients**
send commands and consume snapshots/events; **cluster snapshots** expose
topology, load, and reservations.

Key types: `NexusAuthorityDomainId`, `NexusServerNodeDescriptor` /
`NexusServerNodeRole` (`Gateway`, `Simulation`), `NexusCluster` /
`NexusClusterConfig`, `NexusClientRuntime` / `NexusClientConfig`,
`NexusProtocolVersion`, `NexusInMemoryLink`. The implementation is
transport-agnostic — typed envelopes and a session lifecycle, on top of which
the ~77 crate modules add `interest_management`, `client_prediction`,
`entity_interpolation`, `lag_compensation`, `delta_compression`,
`bandwidth_adaptation`, `authoritative_simulation`, `load_balancing`,
`capacity_scaling`, `mesh_topology`, `edge_server_deployment`,
`cross_region_connectivity`, `cross_world_identity` /
`cross_world_asset_transfer` / `cross_world_events` /
`cross_world_friend_visibility`, `friend_system` / `friend_request_flow`,
`guild_clan_system` / `guild_ranks_permissions` / `guild_management_tools` /
`guild_events_activities`, `party_group_system` / `party_invite_joining`,
`block_mute_system`, `featured_world_system`, `activity_feed`,
`metaverse_navigation_system`, and persistence modules
(`building_construction_persistence`, `economic_state_persistence`,
`inventory_persistence`, `npc_state_persistence`,
`incremental_world_save_system`).

### `maya-immersion` — VR/XR (76 files)

The XR crate wraps every supported headset behind platform-agnostic Rust types.
External SDK dependencies are hidden behind abstract structs/traits — only
`glam`, `serde`, and `bitflags` are compile-time dependencies — so the vendor
SDK integrations are scaffolded interfaces rather than linked libraries.

Device modules: `openxr_runtime_integration`, `meta_quest_sdk`,
`steamvr_integration`, `apple_vision_pro`, `pico_sdk`, `playstation_vr2`,
`htc_vive_focus`, `device_capability_detection`, `controller_abstraction`,
`button_axis_mapping`, `haptic_feedback_abstraction`,
`device_runtime_switching`, `device_specific_optimizations`, `feature_fallback`,
`device_debugging_tools`. Hand-tracking modules: `native_hand_tracking`,
`hand_skeleton`, `finger_joint_tracking`, `gesture_recognition`,
`pinch_grab_detection`.

### `maya-genesis-terrain` / `-urban` / `-flora` — Procedural Generation Crates

These three Rust crates are the **runtime procedural generators** that produce
terrain, cities, and vegetation at world scale. Each crate's module count
reflects its complexity: urban generation (139 files) is the deepest because it
covers the full pipeline from road networks down to individual building facades.

- **`maya-genesis-terrain`** — deterministic multi-octave height synthesis
  (improved Perlin, simplex), cellular Worley masks, domain warping, ridged
  multifractal, Swiss turbulence, hybrid multifractal, real-world DEM import
  (SRTM `.HGT`, ASTER GeoTIFF), heightmap compositing, planetary cube-sphere
  terrain, quadtree terrain LOD with screen-space CLOD.
- **`maya-genesis-urban`** — L-system road grammar, tensor-field road alignment,
  organic/grid/radial road-pattern synthesis, hybrid topology composition,
  terrain-adaptive road placement with cut/fill estimation, road hierarchy
  classification, intersection generation, highway interchange generation. (139
  files — the deepest genesis crate.)
- **`maya-genesis-flora`** — deterministic L-system tree generation (3D turtle
  interpretation, branch-state stacking, stochastic successors, tropism
  steering), space-colonization growth, species presets, branch mesh generation,
  bark texture synthesis, leaf placement/billboarding, leaf cluster generation,
  seasonal leaf color (driven by `maya-time` seasonal state), tree growth
  animation.

### TypeScript Facade (`engine-core/src/index.ts`)

The thin TypeScript facade at the top of the engine workspace provides a
readiness check for a virtual-environment capture session. It exposes one
evaluation function, the types it consumes, and the readiness enum it returns.

`MayaEngineCoreReadiness = 'ready' | 'needs-attention' | 'blocked'`.

`createMayaEngineCoreVirtualEnvironmentFrame(input)` evaluates a virtual
environment for capture-stage readiness. Input
(`MayaEngineCoreVirtualEnvironmentInput`): `environmentId`, `label`,
`targetFrameRateFps`, `maxFrameLatencyMs`, `cameraTracked`, `genlockAligned`,
`drawCallCount`, `triangleCount`, `streamingCellCount`, `materials`
(`MayaEngineCorePbrMaterial[]`), `lights` (`MayaEngineCoreRenderLight[]`).

The two main input array types carry the following fields:

- `MayaEngineCorePbrMaterial` — `materialId`, `label`, `baseColorLinear` (linear
  RGB triple), `metallic`, `roughness`, `normalMapPresent`,
  `roughnessMapPresent`, `metallicMapPresent`, `texelDensityPxPerMeter`.
  Physically valid when colour channels ∈ [0,1], `metallic` ∈ [0,1], `roughness`
  ∈ [0.02,1], and `texelDensityPxPerMeter ≥ 512`.
- `MayaEngineCoreRenderLight` — `lightId`, `label`, `type`
  (`'directional' | 'area' | 'point' | 'image-based'`), `intensityLux`,
  `colorTemperatureKelvin`, `castsShadows`.

Output (`MayaEngineCoreVirtualEnvironmentFrame`): `readiness`,
`pbrCoverageRatio`, `lightingCoverageRatio`, `syncCoverageRatio`,
`realtimeFrameRatio`, `estimatedFrameLatencyMs`, `estimatedFrameRateFps`,
`issues`. Issue types: `camera-untracked`, `genlock-unaligned`,
`pbr-material-invalid`, `pbr-texture-incomplete`, `lighting-incomplete`,
`frame-budget-exceeded`. Estimated frame latency = base 4 ms + draw-call cost

- triangle cost + streaming-cell cost + material cost + shadow-light cost.

---

## Readiness-Evaluation Facade Libraries

The seven single-module libraries —
`libs/maya/{genesis-terrain,genesis-urban,genesis-flora,physics,renderer, scene,world}`
— share a uniform design pattern. Understanding the pattern once lets you read
any of the seven without surprises:

- Each library exports a single `evaluateMaya*` function.
- The function takes a `*Input` description type (configuration of the engine
  feature to be evaluated).
- Each issue carries a discriminated `issueType` union and
  `severity: 'warning' | 'blocking'`.
- The `*Evaluation` output carries per-aspect coverage ratios, latency/memory
  estimates, and an `issues` array.
- Readiness is `'blocked'` if any blocking issue exists, `'needs-attention'` if
  only warnings exist, else `'ready'`.

They evaluate engine configuration; the corresponding runtimes are `engine-core`
Rust crates.

### `@maya/genesis-terrain`

`evaluateMayaGenesisTerrainEnvironment(input)` scores terrain generation
readiness. The input is broken into config blocks, each evaluated separately.

- `MayaGenesisTerrainScale` —
  `'set-extension' | 'regional-backlot' | 'hero-landscape'`.
- `MayaGenesisTerrainBiomeMode` —
  `'earthlike' | 'alien' | 'fantasy' | 'painted-override'`.
- Config blocks: `MayaGenesisTerrainHeightfieldConfig` (resolution, size, noise
  octaves, heightmap, domain warping, compositing layers, spherical patch);
  `…ClimateBiomeConfig` (global climate, temperature gradient,
  precipitation/moisture, Whittaker biomes, boundary blending, altitude zones,
  microclimate, seasonal variation); `…ErosionHydrologyConfig` (hydraulic,
  thermal, wind/coastal erosion, river network, sediment transport, flow map,
  cave/overhang); `…StreamingLodConfig` (LOD hierarchy, streaming planner,
  virtual texturing, crack-free morphing, resident-tile ratio, preload
  coverage); `…MaterialExportConfig` (height/slope material blend, biome
  preview, texture coverage, collision mesh, render export).
- Issue types: `terrain-disabled`, `determinism-missing`,
  `heightfield-coverage-low`, `climate-biome-coverage-low`,
  `erosion-hydrology-coverage-low`, `streaming-lod-coverage-low`,
  `material-export-coverage-low`, `generation-budget-exceeded`,
  `memory-budget-exceeded`.

### `@maya/genesis-urban`

`evaluateMayaGenesisUrbanEnvironment(input)` scores urban generation readiness,
from road network down to render export.

- `MayaGenesisUrbanScale` — `'street-set' | 'district' | 'city-backdrop'`.
- `MayaGenesisUrbanArchetype` —
  `'new-york' | 'tokyo' | 'hong-kong' | 'dubai' | 'solarpunk' | 'cyberpunk' | 'alien-megacity'`.
- Config blocks: `…RoadNetworkConfig`, `…ParcelZoningConfig`, `…BuildingConfig`
  (building-type selection, massing grammar, facade grammar, roof generation,
  interior layout, style archetype, generated vs target building count),
  `…InfrastructureConfig` (power / water / sewage / telecom / transit / civic
  services), `…RenderExportConfig` (material assignment, signage props, lighting
  placement, LOD streaming, CityJSON export, renderer handoff, texture
  coverage).
- Issue types: `urban-disabled`, `determinism-missing`, `road-network-low`,
  `parcel-zoning-low`, `building-generation-low`, `infrastructure-low`,
  `render-export-low`, `generation-budget-exceeded`, `memory-budget-exceeded`.

### `@maya/genesis-flora`

`evaluateMayaGenesisFloraLandscape(input)` scores vegetation generation
readiness across tree generation, biome distribution, ecology simulation, and
render export.

- `MayaGenesisFloraScale` — `'hero-tree' | 'forest-set' | 'landscape-backdrop'`.
- `MayaGenesisFloraBiome` —
  `'temperate-forest' | 'wetland' | 'meadow' | 'urban-park' | 'tropical-jungle' | 'alien-biome' | 'enchanted-forest'`.
- Config blocks: `…TreeGenerationConfig` (L-system trees, space-colonization
  trees, species presets, branch mesh, bark textures, leaf billboards, generated
  vs target tree count); `…DistributionConfig` (biome rules, slope/altitude
  constraints, moisture, sunlight, density maps, Poisson sampling, clustering,
  undergrowth, grass/meadow, wetland/aquatic); `…EcologyConfig` (competition
  model, succession simulation, seasonal growth, soil/water/carbon, biodiversity
  metrics, health visualization, save/restore); `…RenderExportConfig`;
  `…ExoticBiomeConfig` (bioluminescent, crystalline, gaseous, silicon-based,
  carnivorous megaflora, symbiotic colonies, alien preset library).
- Issue types: `flora-disabled`, `determinism-missing`, `tree-generation-low`,
  `distribution-low`, `ecology-low`, `render-export-low`, `exotic-biome-low`,
  `generation-budget-exceeded`, `memory-budget-exceeded`.

### `@maya/physics`

`evaluateMayaPhysicsSimulation(input)` scores physics simulation readiness. The
input describes the active simulation type and backend, plus optional per-domain
configs for cloth, fluid, destruction, and particles.

- `MayaPhysicsSimulationType` —
  `'cloth' | 'fluid' | 'destruction' | 'particles'`.
- `MayaPhysicsBackend` — `'cpu' | 'gpu' | 'hybrid'`.
- Per-domain optional config: `MayaPhysicsClothConfig` (vertex count, constraint
  iterations, pin coverage, self-collision, wind coupling, LOD); `…FluidConfig`
  (particle count, grid cells, surface reconstruction, foam/spray, viscosity
  model, container boundary); `…DestructionConfig` (shard count, support-graph
  coverage, runtime fracture, debris budget, dust particles, persistence);
  `…ParticleConfig` (emitter count, max particles, GPU simulation, collision
  events, lifetime bound, LOD).
- Output adds `solverCoverageRatio`, `collisionCoverageRatio`, `cacheSyncRatio`,
  `renderSyncRatio`, `realtimeStepRatio`, `estimatedStepLatencyMs`,
  `estimatedStepRateHz`.
- Issue types: `simulation-disabled`, `solver-coverage-low`,
  `collision-coverage-low`, `cache-sync-low`, `render-sync-low`,
  `frame-budget-exceeded`, `domain-config-missing`, `determinism-missing`.

### `@maya/renderer`

`evaluateMayaRendererPass(input)` scores renderer readiness across three
independently evaluated config blocks: global illumination, virtualized
geometry, and neural rendering.

- `MayaRendererGiMode` —
  `'probe-grid' | 'radiance-cache' | 'hybrid-raytraced' | 'path-traced'`.
- `MayaRendererNeuralRepresentation` —
  `'none' | 'nerf' | 'gaussian-splatting' | 'hybrid'`. Required dataset view
  counts: `nerf` 48, `gaussian-splatting` 96, `hybrid` 128.
- Config blocks: `MayaRendererGiConfig` (mode, diffuse bounces, specular
  samples/pixel, probe ray count, radiance-cache entries, emissive injection,
  leak prevention, temporal denoising); `…VirtualizedGeometryConfig` (mesh
  shader, cluster count, requested/resident cluster pages, triangle count,
  streaming budget, working set, fallback mesh, occlusion culling);
  `…NeuralRenderingConfig` (enabled, representation, training converged, dataset
  view count, target resolution scale, inference latency, model memory, temporal
  stability score, reconstruction quality score).
- Output adds `giCoverageRatio`, `virtualizedGeometryRatio`,
  `neuralRenderingRatio`, `realtimeFrameRatio`, `estimatedFrameLatencyMs`,
  `estimatedFrameRateFps`, `estimatedMemoryMb`, `estimatedQualityScore`.
- Issue types: `gi-coverage-low`, `virtualized-geometry-low`,
  `neural-rendering-low`, `neural-rendering-disabled`,
  `neural-training-incomplete`, `neural-inference-slow`,
  `frame-budget-exceeded`, `memory-budget-exceeded`, `quality-target-missed`.

### `@maya/scene`

`evaluateMayaSceneVirtualSet(input)` scores scene readiness — whether all
required assets are loaded, the scene graph is valid, nodes are tracked for
capture, and persistent state is bound.

- `MayaSceneAssetType` —
  `'model' | 'texture' | 'material' | 'lighting' | 'audio' | 'script'`.
- `MayaSceneAsset` — `assetId`, `label`, `type`, `required`, `loaded`,
  `persistentCacheReady`, `integrityVerified`, `byteSize`, `dependencies`.
- `MayaSceneNode` — `nodeId`, `label`, optional `parentNodeId`, optional
  `assetId`, `active`, `transformValid`, `trackedForCapture`,
  `persistentStateBound`.
- `MayaSceneStatePersistence` — `snapshotId`, `enabled`, `schemaVersion`,
  `dirtyNodeCount`, `conflictCount`, `recoveryPointReady`,
  `replicatedToCaptureSession`.
- Output: `requiredAssetCoverageRatio`, `dependencyCoverageRatio`,
  `sceneGraphCoverageRatio`, `captureTrackingRatio`, `persistenceCoverageRatio`,
  `estimatedLoadLatencyMs`.
- Issue types: `required-asset-missing`, `asset-dependency-missing`,
  `asset-integrity-missing`, `scene-graph-invalid`, `capture-tracking-low`,
  `state-persistence-low`, `load-budget-exceeded`.

### `@maya/world`

`evaluateMayaWorldVirtualEnvironment(input)` scores overall world readiness:
streaming, time-of-day, weather, atmosphere, and water surface configuration are
each scored against coverage thresholds.

- `MayaWorldEnvironmentScale` —
  `'stage-volume' | 'exterior-set' | 'open-world-backdrop'`.
- `MayaWorldWeatherMode` —
  `'clear' | 'rain' | 'snow' | 'fog' | 'thunderstorm' | 'sandstorm' | 'alien-sky'`.
- Config blocks: `MayaWorldStreamingConfig` (chunk streaming, LOD manager,
  culling pipeline, origin rebase, validation/repair, save/restore, active vs
  target chunk count, resident-chunk ratio, validation issue count);
  `…TimeOfDayConfig` (sun position, sun/moon rendering, day/night cycle,
  latitude day length, per-zone time, time lock, calendar/season, time
  acceleration); `…WeatherConfig` (state machine, forecast, transitions,
  precipitation particles, fog/mist, storm/wind, surface wetness, snow
  accumulation, visibility coverage, active hazard count); `…AtmosphereConfig`
  (physically based scattering, Rayleigh/Mie, volumetric clouds, cloud
  lighting/shadows, sky preset, celestial events, night sky, HDRI export, sky
  texture coverage); `…WaterSurfaceConfig` (ocean, lake/pond, river flow,
  reflections/refractions, caustics, ripples/foam); `…RenderExportConfig`.
- Issue types: `world-disabled`, `determinism-missing`, `streaming-low`,
  `time-of-day-low`, `weather-low`, `atmosphere-low`, `water-surface-low`,
  `render-export-low`, `frame-budget-exceeded`, `memory-budget-exceeded`.

---

## Data Persistence (`@maya/database`)

The `database` library provides domain schemas and a data-access layer as plain
TypeScript — it has **no Drizzle ORM dependency**. Each schema module defines
plain TypeScript interfaces, enums, a `*Validator` class, and a
`generate*TablesDDL()` function that emits SQL DDL strings. The barrel
`src/index.ts` re-exports them all.

### Core Schemas

The table below maps each schema module to its most important enums and types.
Every module follows the same pattern: enums define the legal values, interfaces
define the record shape, a `*Validator` enforces business rules, and
`generate*TablesDDL()` emits the corresponding SQL.

| Schema module                | Key enums / types                                                                  |
| ---------------------------- | ---------------------------------------------------------------------------------- |
| `user-account-schema`        | `UserAccountStatus`; `MayaUserAccountSchema`, `UserAccountAuditEvent`              |
| `avatar-data-schema`         | `AvatarBodyType`, `AvatarSlot`; `AvatarCustomization`                              |
| `inventory-item-schema`      | `ItemRarity`, `ItemCategory`, `RARITY_VALUE_MULTIPLIERS`; `ItemSchema`             |
| `world-zone-schema`          | `WorldVisibility`, `ZoneType`; `WorldSchema`, `ZoneSchema`, `Vec3`, `BoundingBox`  |
| `building-object-schema`     | `BuildingPermission`; `PlacedObjectSchema`, `BuildingSchema`, `ObjectTransform`    |
| `npc-ai-state-schema`        | `NpcPersistenceLevel`; `NpcStateSchema`, `NpcScheduleEntry`                        |
| `quest-progression-schema`   | `QuestStatus`; `QuestDefinition`, `PlayerProgressionSchema`, `xpRequiredForLevel`  |
| `social-relationship-schema` | `RelationshipType`; `SocialRelationshipRecord`, `GuildSchema`, `GuildMemberRecord` |
| `economy-transaction-schema` | `TransactionStatus`, `TransactionType`; `EconomyTransactionRecord`, ledger entry   |
| `analytics-event-schema`     | `AnalyticsEventCategory`; `AnalyticsEventRecord`, `SessionRecord`                  |
| `moderation-report-schema`   | `ReportCategory`, `ReportStatus`, `AUTO_FLAG_REVIEW_THRESHOLD`                     |
| `asset-metadata-schema`      | `AssetType`, `AssetStatus`; `AssetMetadataRecord`, `AssetVersionRecord`            |
| `permission-access-schema`   | `SystemRole`, `Permission`, `ROLE_DEFAULT_PERMISSIONS`; `AccessControlEntry`       |
| `audit-log-schema`           | `AuditAction`, `DEFAULT_AUDIT_RETENTION`; `AuditLogRecord`                         |
| `schema-migration-system`    | `MigrationStatus`; `MayaSchemaMigrationManager`, `MigrationDefinition`             |

#### `WorldSchema` / `ZoneSchema` (`world-zone-schema.ts`)

The world and zone schemas are the central persistence types for the game world.
A world is the top-level container; zones are the spatial subdivisions within it
(open world, dungeon instances, lobbies, arenas, housing). The validator
enforces the naming and coordinate limits shown in the comments below:

```typescript
enum WorldVisibility {
  Public,
  Private,
  FriendsOnly,
  Unlisted,
}
enum ZoneType {
  OpenWorld,
  Instance,
  Lobby,
  Housing,
  Arena,
  Dungeon,
  Hub,
}

interface WorldSchema {
  worldId: string;
  creatorId: string;
  name: string;
  description: string;
  visibility: WorldVisibility;
  maxPlayers: number;
  currentPlayers: number;
  tags: string[];
  thumbnailUrl: string | null;
  rating: number;
  createdAt: Date;
  updatedAt: Date;
}

interface ZoneSchema {
  zoneId: string;
  worldId: string;
  type: ZoneType;
  name: string;
  spawnPoint: Vec3;
  bounds: BoundingBox;
  npcSpawnConfig: Record<string, unknown>;
  weatherConfig: Record<string, unknown>;
  createdAt: Date;
}
```

`WorldSchemaValidator` enforces: world name 1–80 chars, description ≤ 2000
chars, ≤ 20 tags of ≤ 32 chars each, coordinates within ±1,000,000.

### Data-Access Layer

The data-access layer provides the query and transaction infrastructure that
sits between the schema modules and the database. Key types:

`MayaRepository` (with `FilterOperator`, `SortOrder`, `QueryFilter`, `SortSpec`,
`PaginationSpec`, `QueryResult`, `RepositoryStats`); query builders
`SelectBuilder` / `InsertBuilder` / `UpdateBuilder` / `DeleteBuilder` (emit
`BuiltQuery`); `MayaTransaction` / `MayaTransactionManager`
(`TransactionIsolationLevel`, `DEFAULT_TRANSACTION_OPTIONS`,
`TransactionTimeoutError`); `MayaCacheLayer` (`CacheStrategy`, Redis-style
`RedisClient` interface, `CacheEntry`, `CacheStats`); `MayaReadReplicaRouter`
(`ReadReplicaPolicy`, `ReplicaNode`, `NoHealthyReplicaError`); `MayaShardRouter`
(`ShardKey`, `ShardRange`, `ShardConfig`, `ShardMigrationPlan`).

### Operations and Compliance

The operations layer handles data lifecycle concerns — archival, backup, GDPR,
and monitoring — as standalone managers with their own type surfaces:

`MayaDataArchiver` (`ArchivalPolicy`, `ArchivalJob`, `ArchivalJobStatus`);
`MayaDatabaseBackup` (`BackupType`, `BackupStatus`, `BackupManifest`,
`RestoreOptions`); `MayaPitrManager` point-in-time recovery (`WalSegment`,
`PitrTarget`, `PitrRecoveryPlan`, `PitrProgress`); `MayaDataExporter`
(`ExportFormat`, `ExportStatus`); `MayaGdprManager` (`GdprRequestType`,
`GdprRequestStatus`, `DataCategory`, `ErasurePlan`); `MayaDataAnonymizer`
(`AnonymizationRule`, `AnonymizationConfig`, `AnonymizationReport`);
`MayaDataRetentionManager` (`RetentionPolicy`, `RetentionRun`,
`RetentionRunStatus`); `MayaDatabaseMonitor` (`DatabaseMetric`,
`SlowQueryRecord`, `DatabaseHealthReport`); `MayaQueryOptimizer` (`QueryPlan`,
`QueryOptimizationSuggestion`).

---

## Server Infrastructure (`@maya/server`)

TypeScript Node.js service modules, barrelled through `src/index.ts`. The server
library owns the game server runtime: the central simulation loop, session and
player connection management, all live-service services, and operational
tooling. Modules include: `game-server-application`, `world-simulation-loop`,
`player-connection-management`, `authentication-integration`,
`authentication-service`, `session-management`, `anti-cheat-measures`,
`server-side-physics`, `ai-npc-simulation`, `economy-service`,
`economy-transactions`, `event-broadcasting`, `server-clustering`,
`zone-handoff-protocol`, `server-metrics-monitoring`,
`server-administration-tools`, `server-hot-reload`,
`service-mesh-configuration`, `social-graph-service`, `matchmaking-service`,
`achievement-service`, `leaderboard-service`, `content-moderation-service`,
`asset-storage-service`, `analytics-service`, `user-management-service`,
`inventory-service`, `payment-processing-integration`,
`email-service-integration`.

### `WorldSimulationLoop` (`world-simulation-loop.ts`)

The simulation loop is the heartbeat of the game server. It implements the
classic _Fix Your Timestep!_ accumulator pattern with a spiral-of-death
prevention cap on maximum substeps per real-time frame. The configuration and
tick types are:

```typescript
interface SimulationLoopConfig {
  fixedTimestep_ms: number; // 16.67 for 60 Hz
  maxSubsteps: number; // cap per real-time frame
  catchUpFactor: number; // 0–1, fraction of accumulated time consumed
}

interface SimulationTick {
  tickNumber: number;
  simTime_ms: number;
  deltaTime_ms: number;
  isCatchUp: boolean;
}
```

`WorldSimulationLoop` registers `TickCallback`s and drives them off a
`setInterval` handle, tracking an accumulator, sim time, and tick count.

---

## Client SDK (`@maya/client`)

TypeScript library, barrelled through `src/index.ts`. The client SDK is the
entry point for all platform-facing concerns: it wraps platform differences
behind the enums and states below so game code is platform-agnostic.

- **Platform abstraction** — `platform-abstraction-layer.ts` defines
  `MayaClientPlatformCapability` (`multi-window`, `single-window`,
  `display-control`, `local-storage`, `notifications`, `messaging`,
  `external-links`, `xr-session`, `haptics`, `keyboard-input`, `pointer-input`,
  `touch-input`, `controller-input`, `offline-cache`), `MayaClientWindowState`
  (`hidden`, `visible`, `minimized`, `maximized`, `fullscreen`, `closed`),
  `MayaClientXrSessionState` (`idle`, `ready`, `running`, `stopping`,
  `stopped`).
- **Build targets** — `windows-desktop-build`, `macos-desktop-build`,
  `linux-desktop-build`, `android-mobile-build`, `ios-mobile-build`,
  `webgpu-browser-build`, `webxr-browser-build`, `meta-quest-standalone-build`,
  `steamvr-build`, `apple-vision-pro-build`.
- **Distribution** — `app-store-distribution`, `play-store-distribution`,
  `steam-distribution`, `meta-quest-store-distribution`, `ci-cd-build-pipeline`,
  `launcher-integration`, `automatic-updates`.
- **Runtime** — `client-application-framework`, `asset-loading-and-caching`,
  `input-handling-system`, `window-display-management`,
  `configuration-management`, `user-settings-persistence`,
  `offline-mode-support`, `mod-and-plugin-loading`, `client-side-validation`,
  `client-performance-profiling`, `client-debugging-tools`,
  `crash-reporting-and-diagnostics`.

---

## Game Framework (`@maya/games`)

TypeScript library, barrelled through `src/index.ts`, organised into 19
sub-directory modules: `stats`, `progression`, `skills`, `abilities`,
`inventory`, `items`, `equipment`, `crafting`, `gathering`, `survival`, `loot`,
`mmo`, `classes`, `party`, `companions`, `quests`, `combat`, `hathor`.

### Combat (`games/src/combat/`)

Real-time RPG combat built around a health-damage core. The health system
defines the combatant lifecycle (Healthy through Defeated); the damage
calculation system feeds into it from above.

`health-damage-system.ts` defines `HealthStateKind` (`Healthy`, `Wounded`,
`Critical`, `Downed`, `Defeated`) and `HealthDamageEventKind`
(`CombatantSynced`, `DamageApplied`, `HealingApplied`, `CombatantDowned`,
`CombatantRevived`, …); it consumes `damage-calculation-system.ts`
(`DamageType`, `DamageSourceKind`, `DamageOutcome`, `DamageCalculationResult`)
and the `stats` module's `CharacterStatSystem` / `ResourcePool`. Other combat
modules: `weapon-system`, `melee-combat-system`, `ranged-combat-system`,
`combo-attack-chain-system`, `blocking-parrying-system`, `dodge-roll-system`,
`cover-system`, `projectile-physics-system`, `status-effect-system`,
`ai-combat-behavior-system`, `group-combat-tactics-system`,
`combat-difficulty-scaling-system`, `combat-analytics-system`.

### MMO (`games/src/mmo/`)

MMO social and content systems: `guild-system`, `guild-rank-permissions-system`,
`guild-bank-storage-system`, `guild-housing-halls-system`,
`dungeon-instancing-system`, `raid-encounter-system`,
`boss-mechanics-framework`, `world-boss-spawning-system`, `pvp-system`,
`battleground-arena-system`, `ranking-matchmaking-system`,
`auction-house-system`, `mail-system`, `achievement-system`,
`seasonal-content-system`.

### Survival (`games/src/survival/`)

Survival gameplay systems covering player needs, base building, and the
environment: `hunger-thirst-system`, `temperature-exposure-system`,
`sleep-rest-system`, `disease-illness-system`, `food-drink-item-system`,
`tool-durability-system`, `base-building-system`, `building-upgrade-system`,
`structure-placement-validation`, `base-defense-raid-system`,
`shelter-mechanics-system`, `environmental-hazard-system`,
`resource-node-system`, `wildlife-hunting-system`, `pet-taming-system`.

### Quests (`games/src/quests/`)

Quest lifecycle from definition through consequence tracking:
`quest-definition-system`, `quest-objective-system`, `quest-chain-system`,
`quest-tracking-system`, `quest-marker-system`, `quest-reward-system`,
`quest-outcome-system`, `quest-consequence-system`, `quest-faction-reputation`,
`quest-dialogue-integration`, `quest-procedural-generation`,
`quest-radiant-system`, `quest-sharing-system`, `quest-state-persistence`,
`quest-debugging-tools`.

### Hathor Integration (`games/src/hathor/`)

The Hathor boundary is one-directional: Maya's game systems _consume_ Hathor
worldbuilding data; Hathor does not depend on Maya. This allows Maya worlds to
be culturally grounded without coupling the narrative layer to the engine.

Modules: `hathor-world-data-import`, `hathor-cultural-rules-integration`,
`hathor-religion-belief-integration`, `hathor-language-naming-integration`,
`hathor-economic-model-integration` — import of worldbuilding data from the
Hathor domain into Maya's game systems.

---

## Inspiration Library (`@maya/inspirations`)

TypeScript reference-data library, barrelled through `src/index.ts`.
`reference-types.ts` defines the shared vocabulary used to type all reference
data:

- `CityReferenceDensity` — `low`, `moderate`, `high`, `hyper-dense`
- `CityReferenceGridPattern` — `commissioners-grid`, `diagonal-grid`,
  `organic-waterfront`, `hill-adapted-grid`, `campus-superblock`
- `CityReferenceTransitMode`, `CityReferenceLandUse`,
  `CityReferenceLightingTime`, `CityReferenceClimateProfile`,
  `CityReferenceMeasurement`

The library ships parameter sets for real-world cities (Manhattan, Hong Kong,
Tokyo/Neo-Tokyo, Dubai, Singapore, European historic cities, Paris/London/Rome,
Middle Eastern and African and Southeast Asian urban patterns), fictional
universes (Blade Runner LA 2049, Night City, Mega-City One, Matrix mega-city,
Ghost in the Shell New Port City, Coruscant, Mass Effect Citadel, Halo New
Mombasa, Final Fantasy Midgar, Game of Thrones / Lord of the Rings / Elder
Scrolls cities, Mirror's Edge), biome references (temperate forest, tropical
rainforest, desert/dune, tundra/arctic, mountain/alpine, ocean/coastal,
cave/underground, bioluminescent, crystal/mineral, magical/enchanted forest,
corrupted/tainted biomes), and style guides (original cyberpunk / fantasy,
organic-biomechanical, character / vehicle / prop, audio, UI/UX). It also
includes Yemaya integration test fixtures.

---

## Testing Infrastructure (`@maya/testing`)

TypeScript test-harness library, barrelled through `src/index.ts`, in three
groups:

- **Unit testing** — `unit-test-framework-setup`, `engine-core-unit-tests`,
  `renderer-unit-tests`, `physics-unit-tests`, `audio-unit-tests`,
  `networking-unit-tests`, `ai-unit-tests`, `economy-unit-tests`,
  `procedural-generation-tests`, `serialization-tests`, `math-library-tests`,
  `data-structure-tests`, `api-contract-tests`, `coverage-reporting`,
  `mutation-testing`.
- **Integration testing** — `integration-test-framework`,
  `client-server-integration-tests`, `database-integration-tests`,
  `authentication-flow-tests`, `multiplayer-scenario-tests`,
  `economy-transaction-tests`, `ugc-upload-download-tests`,
  `world-streaming-tests`, `save-load-tests`, `cross-platform-tests`,
  `vr-device-tests`, `performance-benchmark-tests`, `e2e-scenario-tests`,
  `chaos-engineering-tests`, `load-testing`.
- **Visual testing** — `screenshot-comparison-testing`,
  `render-regression-tests`, `perceptual-diff-tooling`,
  `cross-platform-visual-parity`, `hdr-tone-mapping-tests`,
  `post-processing-tests`, `particle-effect-tests`, `material-preview-tests`,
  `shader-validation-tests`, `lighting-validation-tests`,
  `animation-playback-tests`, `vr-stereo-rendering-tests`,
  `ui-screenshot-tests`, `automated-visual-qa`, `visual-test-reporting`.

---

## Development Tooling (`@maya/tooling`)

TypeScript tooling library, barrelled through `src/index.ts`, in three groups:

- **World editor** — `world-editor-application`, `viewport-navigation`,
  `selection-transform-tools`, `property-inspector-panel`, `hierarchy-outliner`,
  `asset-browser`, `terrain-editing-tools`, `foliage-painting-tools`,
  `lighting-setup-tools`, `material-editor`, `particle-effect-editor`,
  `animation-preview`, `audio-setup-tools`, `play-in-editor-mode`,
  `collaborative-editing`.
- **Profiling and debugging** — `frame-profiler`, `gpu-profiler-integration`,
  `memory-profiler`, `network-profiler`, `physics-debugger`, `audio-debugger`,
  `ai-debugger`, `render-debugger`, `console-logging`, `variable-watch-system`,
  `breakpoint-system`, `replay-time-travel-debug`, `crash-dump-analysis`,
  `telemetry-collection`, `performance-regression-testing`.
- **Asset tools** — `asset-converter-cli`, `texture-compression-tools`,
  `mesh-optimization-tools`, `lod-generation-tools`,
  `collision-generation-tools`, `navmesh-generation-tools`,
  `lightmap-baking-tools`, `audio-processing-tools`, `asset-validation-tools`,
  `asset-comparison-tools`, `asset-dependency-analyzer`, `asset-size-reporter`,
  `asset-migration-tools`, `batch-processing-tools`, `localization-tools`.

---

## Documentation Library (`@maya/documentation`)

TypeScript library, barrelled through `src/index.ts`, in two groups:

- **API documentation** — `typedoc-generation`, `api-reference-website`,
  `code-example-embedding`, `interactive-api-explorer`,
  `versioned-documentation`, `changelog-generation`, `deprecation-tracking`,
  `migration-guides`, `search-functionality`, `documentation-testing`,
  `localization-support`, `pdf-export`, `offline-documentation`,
  `api-diff-tools`, `documentation-ci-cd`.
- **Tutorials and guides** — `getting-started-guide`, `first-world-tutorial`,
  `avatar-customization-guide`, `building-basics-tutorial`,
  `scripting-introduction`, `multiplayer-guide`, `vr-development-guide`,
  `ai-npc-tutorial`, `procedural-generation-guide`, `asset-pipeline-guide`,
  `economy-setup-guide`, `optimization-guide`, `deployment-guide`,
  `best-practices-guide`, `video-tutorial-series`.

---

## Build System

Maya integrates with Nx via the `nx:run-commands` executor. The `engine-core` Nx
project exposes six cargo targets; TypeScript libraries each expose four
standard targets.

| Project              | `project.json` name | Build command                                  |
| -------------------- | ------------------- | ---------------------------------------------- |
| `engine-core`        | `maya-engine-core`  | `cargo build --release -p …` (10-crate subset) |
| TypeScript libraries | per-library         | `tsc -p tsconfig.lib.json`                     |

`engine-core` (`project.json`, tags `scope:maya`, `type:rust`, `layer:engine`)
exposes `check`, `build`, `test`, `test:integration`, `lint` (clippy), and
`format` (`cargo fmt --check`) targets, each `cd`-ing into
`libs/maya/engine-core` and invoking cargo. The whole workspace is also
buildable via the `package.json` scripts `cargo:check`, `cargo:build`,
`cargo:test`, `cargo:test:integration`, `cargo:clippy`, `cargo:fmt`.

TypeScript libraries each define `build`, `lint`, `typecheck`, and `test`
targets that wrap `tsc`, `eslint src --ext .ts`, and `vitest run`.

---

## Cross-Domain Integration

Maya's integration surface today is intentionally narrow. The Hathor integration
is implemented: `games/src/hathor/*` imports world data, cultural rules,
religion/belief, language/naming, and economic-model data from Hathor into
Maya's game systems. The boundary is one-directional by design — Hathor owns the
cultural and narrative data; Maya consumes it. This prevents the engine from
becoming entangled with narrative decisions and keeps both domains independently
deployable.

The Yemaya integration surface is present as test fixtures
(`inspirations/src/yemaya-integration-test-fixtures.ts`), establishing the
data-handoff shape for future creative-asset integration. No event-bus, storage,
queue, or other shared-package imports were found in Maya source; any broader
integration with other Oshun domains is **(planned)**.

---

## Status Summary

- **Deepest implementation:** `engine-core` Rust workspace — 28 crates, ~1074
  files; the renderer, physics, audio, atmosphere, embodiment, souls, nexus,
  immersion, and genesis crates each carry 60–153 source files of domain logic.
- **Substantial TypeScript libraries:** `games` (~100 modules), `inspirations`
  (~75), `testing` and `tooling` (~48 each), `client`, `database`, `server`,
  `documentation` (~30 each) — all real domain code with enums, schemas,
  validators, and services.
- **Readiness facades:** the seven single-module libraries (`genesis-terrain`,
  `genesis-urban`, `genesis-flora`, `physics`, `renderer`, `scene`, `world`)
  plus `engine-core/src/index.ts` are real but evaluate readiness rather than
  run the engine.
- **Not present:** `apps/maya/`, `services/maya/`; concrete GPU / physics /
  audio vendor SDK bindings inside the Rust crates; a custom UDP netcode
  protocol; UGC scripting sandbox, economy/governance/modding services as
  shipped code. Those remain `(planned)`.
