# Nyx Domain — Architecture

> Architectural overview of the Nyx cosmic observatory platform: application and
> library package tree, service topology, data flow, and cross-domain
> dependencies.

---

Nyx is the astronomy and cosmic-observatory domain of the Oshun monorepo. It
provides everything needed to build planetarium software, telescope control
systems, satellite trackers, educational astronomy applications, and real-time
sky visualisations. The domain is deliberately near-self-contained: its 75
library packages and 22 applications take their dependencies directly from
third-party packages (`astronomy-engine`, `pg`, `ioredis`, `hono`) and from each
other under the `@nyx/*` namespace, rather than from the `@oshun/*` shared
infrastructure libraries — with one exception: the `api` and `pipelines` apps
declare and import `@oshun/database` for shared Postgres access.

The domain's single external boundary is `@nyx/lilith-integration`, a
cosmic-meditation content library that makes Nyx's astronomical imagery
available inside the Lilith consciousness domain. Everything else — ephemeris
computation, catalog access, real-time updates, WebGL rendering, and pipeline
workers — stays within Nyx.

---

## Design Principles

The following principles shape every architectural decision in the domain.

1. **Computational accuracy** — Ephemeris, coordinate transforms, and time
   systems implement peer-reviewed astronomical algorithms (Meeus, IAU SOFA).
   Accuracy is non-negotiable.
2. **Real-time delivery** — WebSocket channels push position updates, satellite
   passes, and event alerts at configurable intervals.
3. **Modular library composition** — independent libraries provide capabilities
   that compose into Nyx applications and tooling.
4. **Data pipeline separation** — Long-running data ingestion (TLE updates,
   catalog sync, ephemeris generation) runs as independent Kubernetes CronJobs,
   never blocking the API.
5. **Tiered API access** — Public API with rate-limited free tier and
   progressively capable pro/enterprise tiers.

---

## System Architecture

The diagram below shows the major runtime boundaries. All external clients (web
apps, VR/AR, mobile, SDKs) reach the platform through the single `@nyx/api`
process. Data-ingestion pipelines run out-of-band and write precomputed results
into PostgreSQL for the API to read.

```
                    ┌────────────────────────────────┐
                    │            CLIENTS              │
                    │  Star Map  VR  AR  Mobile  SDKs │
                    └──────────────┬─────────────────┘
                                   │
       ┌───────────────────────────┴──────────────────────┐
       ▼                                                  ▼
┌────────────────────────────────┐          ┌──────────────────┐
│  @nyx/api  (single process)    │          │  Web Clients     │
│  HTTP (Hono+OpenAPI) + WS /ws  │          │  (Vite + React + │
│  Port 3000 (PORT)              │          │   Three.js)      │
└──────┬─────────────────────────┘          └──────────────────┘
       │
       ┌───────────────┴───────────────────────────────┐
       │              SERVICE LAYER                     │
       │  EphemerisService │ ObjectsService              │
       │  EventsService    │ SatellitesService           │
       └───────────────┬───────────────────────────────┘
                       │
       ┌───────────────┴───────────────────────────────┐
       │              LIBRARY LAYER                     │
       │  @nyx/ephemeris  @nyx/coordinates  @nyx/time   │
       │  @nyx/messier    @nyx/events       @nyx/types  │
       │  @nyx/orbital    @nyx/constellations            │
       │  @nyx/realtime-satellites                       │
       └───────────────┬───────────────────────────────┘
                       │
       ┌───────────────┴───────────────────────────────┐
       │              DATA LAYER                        │
       │  PostgreSQL (pg) │ Redis (rate limit) │ Files  │
       └────────────────────────────────────────────────┘
                                      ▲
                                      │
                         ┌────────────┴──────┐
                         │   DATA PIPELINES   │
                         │   (Node workers /  │
                         │   Kubernetes       │
                         │   CronJobs)        │
                         │  TLE Updater       │
                         │  Catalog Syncer    │
                         │  Ephemeris Gen     │
                         │  Event Calculator  │
                         └───────────────────┘
```

The REST API and WebSocket server run inside the single `@nyx/api` process and
share `PORT` (default 3000); `apps/nyx/api/src/index.ts` attaches the WebSocket
server to the same HTTP server.

---

## Application Layer (22 Applications)

`apps/nyx` contains six top-level applications plus two directory groups
(`education`, `tools`) of individually packaged sub-applications — 22 packaged
apps in total.

### Top-Level Applications (6)

These are the runtime entry points that users and external consumers interact
with directly.

| Application        | Package               | Path                      | Type    | Framework                 |
| ------------------ | --------------------- | ------------------------- | ------- | ------------------------- |
| **API**            | `@nyx/api`            | `apps/nyx/api`            | Server  | Hono + OpenAPI + `ws`     |
| **Star Map**       | `@nyx/star-map`       | `apps/nyx/star-map`       | Web App | Vite + React + Three.js   |
| **VR Planetarium** | `@nyx/vr-planetarium` | `apps/nyx/vr-planetarium` | Web App | React-Three-Fiber + WebXR |
| **AR Sky**         | `@nyx/ar-sky`         | `apps/nyx/ar-sky`         | Web App | React-Three-Fiber + WebXR |
| **Mobile**         | `@nyx/mobile`         | `apps/nyx/mobile`         | Web App | React + `idb-keyval`      |
| **Pipelines**      | `@nyx/pipelines`      | `apps/nyx/pipelines`      | Worker  | Node.js                   |

The API server listens on `PORT` (default 3000) for both HTTP and WebSocket
traffic. The pipelines health/metrics server is gated by `METRICS_ENABLED`.

### Education Applications (`apps/nyx/education`, 12)

Twelve individually packaged education apps live under this directory: five
courses (`@nyx/fundamentals-course`, `@nyx/solar-system-course`,
`@nyx/stellar-course`, `@nyx/galactic-course`, `@nyx/cosmology-course`), two
challenges (`@nyx/star-identification`, `@nyx/orbital-mechanics`), and five
interactive demos (`@nyx/hr-diagram`, `@nyx/spectroscopy`,
`@nyx/distance-ladder`, `@nyx/light-speed`, `@nyx/gravity-well`).

### Tools Applications (`apps/nyx/tools`, 4)

Four specialised tools: `@nyx/astrophotography`, `@nyx/light-curves`,
`@nyx/observation-planner`, and `@nyx/orbit-determination`.

---

## Library Layer (75 Packages)

`libs/nyx` ships 75 published packages. Several library groups (`catalogs`,
`renderer`, `realtime`, `analysis`, `audio`, `education`, `integrations`,
`widgets`, `visualization`) are directories of individual packages rather than
single packages — e.g. there is no `@nyx/catalogs` package; the catalogs group
contains `@nyx/messier`, `@nyx/gaia`, `@nyx/hipparcos`, and others.

### Core / Foundation (6)

These six packages form the shared foundation that every other `@nyx/*` library
depends on. Any new library in the domain will typically start by importing from
these.

| Package            | Path                   | Purpose                                                                                 |
| ------------------ | ---------------------- | --------------------------------------------------------------------------------------- |
| `@nyx/types`       | `libs/nyx/types`       | TypeScript type system (coordinates, celestial, time, observer, orbital, visualization) |
| `@nyx/constants`   | `libs/nyx/constants`   | Physical and astronomical constants                                                     |
| `@nyx/coordinates` | `libs/nyx/coordinates` | Coordinate system transforms                                                            |
| `@nyx/time`        | `libs/nyx/time`        | Julian Date, sidereal time, Delta-T, time scales                                        |
| `@nyx/utils`       | `libs/nyx/utils`       | Angular separation, magnitude math, formatting                                          |
| `@nyx/database`    | `libs/nyx/database`    | Zod schema models and Knex migrations                                                   |

### Astronomical Computation (8)

These libraries implement the domain's mathematical core — from raw orbital
elements to eclipse predictions and historical sky reconstruction.

| Package               | Path                      | Purpose                                                                                                                            |
| --------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `@nyx/ephemeris`      | `libs/nyx/ephemeris`      | Solar-system position computation                                                                                                  |
| `@nyx/orbital`        | `libs/nyx/orbital`        | Kepler/n-body mechanics, perturbations, Lagrange points                                                                            |
| `@nyx/positional`     | `libs/nyx/positional`     | Topocentric correction, refraction, rise/set                                                                                       |
| `@nyx/events`         | `libs/nyx/events`         | Eclipse / conjunction / occultation / transit / meteor / aurora / satellite-pass / supermoon / deep-sky prediction + calendar sync |
| `@nyx/constellations` | `libs/nyx/constellations` | Multi-cultural constellation database + artwork                                                                                    |
| `@nyx/mythology`      | `libs/nyx/mythology`      | Constellation mythology data                                                                                                       |
| `@nyx/time-travel`    | `libs/nyx/time-travel`    | Historical/future sky reconstruction                                                                                               |
| `@nyx/sky-clock`      | `libs/nyx/sky-clock`      | Sky-event materialiser, observer-location bucketing                                                                                |

### Catalog Packages (`libs/nyx/catalogs`, 28)

Each astronomical catalog gets its own package, giving it isolated ownership of
its data format, identifier syntax, and query helpers. This design means that
adding a new catalog (say, an updated Gaia data release) requires changes only
to that one package.

The catalog group breaks down as follows:

- **Star catalogs:** `@nyx/hipparcos`, `@nyx/gaia`, `@nyx/tycho`,
  `@nyx/bright-stars`, `@nyx/simbad`, `@nyx/star-query`
- **Deep-sky objects** (`deep-sky/`): `@nyx/messier`, `@nyx/ngc-ic`,
  `@nyx/nebulae`, `@nyx/clusters`, `@nyx/snr`, `@nyx/pulsars`,
  `@nyx/neutron-stars`, `@nyx/black-holes`, `@nyx/quasars`,
  `@nyx/gravitational-waves`, `@nyx/supernovae`, `@nyx/ned`, `@nyx/sdss`
- **Exoplanets:** `@nyx/nasa-exoplanets`, `@nyx/open-exoplanets`
- **Solar system** (`solar-system/`): `@nyx/planets`, `@nyx/moons`,
  `@nyx/horizons`, `@nyx/mpc`, `@nyx/neo`, `@nyx/comets`
- **Spacecraft:** `@nyx/spacecraft`

### Renderer Packages (`libs/nyx/renderer`, 12)

The renderer group provides a layered WebGL/Three.js pipeline for drawing the
sky. Each package handles a specific visual layer; they compose together inside
the star-map and VR/AR applications.

`@nyx/renderer-core`, `@nyx/renderer-background`, `@nyx/renderer-stars`
(published as `@nyx/star-colors`), `@nyx/renderer-planets`,
`@nyx/renderer-galaxies`, `@nyx/renderer-nebulae`, `@nyx/renderer-clusters`,
`@nyx/renderer-exotic`, `@nyx/renderer-hdr`, `@nyx/renderer-lod`,
`@nyx/renderer-scale`, `@nyx/renderer-post-processing`.

### Real-Time, Analysis, Widgets, Audio, Education, Integrations, Visualization

The remaining library groups address specific application concerns:

- **Real-time** (`realtime/`): `@nyx/realtime-satellites`,
  `@nyx/realtime-solar`, `@nyx/realtime-neo`, `@nyx/realtime-events` — live
  position feeds updated from TLE data and NOAA solar weather.
- **Analysis** (`analysis/`): `@nyx/galaxy-classification`, `@nyx/habitability`,
  `@nyx/visualization` — ML classification, habitable-zone scoring, and chart
  generation.
- **Widgets** (`widgets/`): `@nyx/widget-iss-tracker`, `@nyx/widget-moon-phase`,
  `@nyx/widget-star-map` — self-contained embeddable UI components.
- **Audio** (`audio/`): `@nyx/audio-sonification`, `@nyx/audio-ambient` —
  astronomical data mapped to sound and ambient cosmic soundscapes.
- **Education** (`education/`): `@nyx/lesson-framework`, `@nyx/quiz-system` —
  shared infrastructure used by the 12 education apps.
- **Integrations** (`integrations/`): `@nyx/telescope`, `@nyx/stellarium`,
  `@nyx/planetarium` — hardware control and planetarium-software interop.
- **Visualization** (`visualization/`): `@nyx/galaxy-distribution`

### Clients and Cross-Domain (3)

Three packages bridge Nyx to the outside world: two typed API clients for
external consumers, and one cross-domain integration package.

| Package                   | Path                          | Purpose                                    |
| ------------------------- | ----------------------------- | ------------------------------------------ |
| `@nyx/client`             | `libs/nyx/client`             | Hand-written typed HTTP client             |
| `@nyx/api-client`         | `libs/nyx/api-client`         | Client with OpenAPI-generated types        |
| `@nyx/lilith-integration` | `libs/nyx/lilith-integration` | Cosmic-meditation content bridge to Lilith |

`libs/nyx/client-python` is a Python client package (no TypeScript sources).
`libs/nyx/docs` holds design documents and is not a published package.

---

## API Server Internal Architecture

The API server's source tree shows how each concern is isolated into its own
layer. Middleware runs first for every request, services hold the business
logic, and the WebSocket subsystem lives in its own directory.

```
apps/nyx/api/src/
├── index.ts                  # Bootstrap: HTTP + WebSocket servers
├── app.ts                    # Hono application, middleware chain
├── middleware/
│   ├── api-key-auth.ts       # Tiered API key auth (free/pro/enterprise)
│   ├── error-handler.ts      # RFC 7807 Problem Details
│   ├── rate-limit.ts         # 60/300/1000/5000 rpm by tier
│   └── request-id.ts         # X-Request-ID propagation
├── routes/
│   ├── objects.ts            # GET /api/v1/objects
│   ├── ephemeris.ts          # GET /api/v1/ephemeris
│   ├── events.ts             # GET /api/v1/events
│   └── satellites.ts         # GET /api/v1/satellites
├── schemas/                  # Zod-OpenAPI schemas
├── services/
│   ├── ephemeris-service.ts  # Position calculation orchestration
│   ├── objects-service.ts    # Catalog query engine
│   ├── events-service.ts     # Event prediction engine
│   └── satellites-service.ts # TLE propagation and pass prediction
└── websocket/
    ├── index.ts              # WS exports + setupNyxWebSocket helper
    ├── server.ts             # WebSocket server (NyxWSServer)
    ├── handlers.ts           # Per-channel message handlers
    ├── services.ts           # Update scheduler and broadcaster
    ├── subscriptions.ts      # Subscription channel parsing/validation
    └── types.ts              # Channel and message type definitions
```

Middleware runs in a fixed chain defined in `app.ts`:
`secureHeaders → CORS → logger → timing → prettyJSON → requestId` applies to all
routes; then on `/api/*`, `apiKeyAuth → rateLimit` runs next; and
`onError(errorHandler)` is registered globally for RFC 7807 responses.

The API services are backed by bundled catalog libraries and sample data:
`objects-service` maps `ALL_MESSIER_OBJECTS` from `@nyx/messier`,
`events-service` serves an in-module sample list, and `satellites-service` uses
`@nyx/realtime-satellites` with vendored TLE data.

---

## Pipeline Architecture

The pipelines application runs four independent Node.js workers. Each worker can
be invoked directly for one-off runs or scheduled as a Kubernetes CronJob for
production ingestion — this separation means a slow catalog sync never delays an
API response.

```
apps/nyx/pipelines/src/
├── index.ts               # Daemon entry: PIPELINES registry + health server
├── tle-updater.ts         # Fetch TLE data, refresh satellite orbital state
├── catalog-syncer.ts      # Sync Gaia/Hipparcos catalog data into object tables
├── ephemeris-generator.ts # Pre-compute solar-system positions
├── event-calculator.ts    # Predict conjunctions/eclipses → celestial_events table
└── common/                # Shared logger (pino), metrics (prom-client), health server
```

Each pipeline is an independent Node.js entry point listed in the `PIPELINES`
registry; pipelines can run directly or as Kubernetes CronJobs. The
`event-calculator` walks pairs of visible bodies with the `@nyx/events`
conjunction scanner and Bessel-element eclipse predictors and upserts results
into the `celestial_events` table via `pg`. A shared health/metrics server
(`common/health-server.ts`) exposes liveness/readiness endpoints and is gated by
the `METRICS_ENABLED` environment variable.

---

## WebGL Star Map Architecture

The star map client (`apps/nyx/star-map`, ~189 source files) is the largest
application in the domain and the primary surface through which most users
experience Nyx. It is a Vite + React + Three.js application that draws on:

- The `libs/nyx/renderer/*` package group (`@nyx/renderer-core`,
  `@nyx/renderer-stars`, `@nyx/renderer-planets`, and others) for WebGL
  rendering of stars, planets, nebulae, galaxies, and clusters.
- `@nyx/constellations` — constellation line geometry and multi-cultural data.
- Feature modules under `src/` for navigation, planning, collections,
  spacecraft, satellites, mythology, time-travel, filters, tonight-view,
  journal, audio, meditation, NEO, and bookmarks.

---

## VR and AR Architecture

Both `vr-planetarium` and `ar-sky` are React-Three-Fiber applications that use
WebXR through `@react-three/xr`. They share the ephemeris and real-time solar
libraries with the star map but render into immersive 3D sessions instead of a
flat canvas:

- `vr-planetarium` depends on `@nyx/ephemeris`, `@nyx/realtime-solar`,
  `@react-three/postprocessing`, and the React-Three ecosystem.
- `ar-sky` depends on `@nyx/realtime-solar` and `@react-three/xr`, with `src/`
  modules for scene composition, overlays, labels, and object identification.

---

## Design Patterns

### Layered Computation

Position calculation follows a strict pipeline: raw orbital elements →
light-time correction → aberration → precession/nutation → apparent position →
topocentric correction → atmospheric refraction → alt/az. Each step is a pure
function in `@nyx/ephemeris` or `@nyx/positional`, making it independently
testable.

### Pipeline-Computed Data

Long-running ingestion and prediction (TLE refresh, catalog sync, ephemeris
generation, event calculation) runs in the separate `@nyx/pipelines` workers,
never blocking the API request path. The `event-calculator` persists computed
events into the `celestial_events` table for later read access. A detailed
multi-layer caching design is documented in `libs/nyx/docs/caching-strategy.md`.

### Per-Catalog Packages

Each astronomical catalog is its own package under `libs/nyx/catalogs/*`
(`@nyx/hipparcos`, `@nyx/gaia`, `@nyx/messier`, `@nyx/ngc-ic`, `@nyx/mpc`, and
others), each owning the data, identifier parsing, and query helpers for that
catalog. The API's `objects-service` composes these packages — for example
mapping `@nyx/messier` into the unified API object shape. The `@nyx/database`
schema additionally defines normalised `celestial_objects`, `stars`, `galaxies`,
and related tables plus a `catalog_cross_references` table for resolving objects
across catalogs.

### Tiered API Access

API key tier determines rate limits (`RATE_LIMIT_TIERS` —
anonymous/free/pro/enterprise) and WebSocket connection/subscription budgets
(`DEFAULT_TIER_LIMITS`). Anonymous access is permitted with the most restrictive
limits.

---

## Cross-Domain Integration

Nyx is intentionally self-contained: the API and pipeline applications take
their dependencies directly (`pg`, `ioredis`, `pino`, `prom-client`, `hono`,
`astronomy-engine`) and from `@nyx/*` workspace packages rather than from
`@oshun/*` shared libraries. This keeps Nyx deployable independently of the rest
of the monorepo and prevents coupling to shared infrastructure that may change
for reasons unrelated to astronomy.

The one explicit cross-domain package is `@nyx/lilith-integration`. The boundary
exists because Lilith (the consciousness domain) benefits from cosmic imagery
and meditation content, but it should not be coupled directly to ephemeris
computations or catalog data. The integration package acts as a stable
translation layer: it exposes curated content collections (visualizations,
breath patterns, parallels between inner and outer space) that Lilith can
consume without knowing anything about astronomical algorithms. Data that
crosses this boundary flows one way only — from Nyx's static content into
Lilith's session manager.

The `@nyx/orbital` library additionally includes a `kalika-relativity` module, a
thin touchpoint with the Kalika mathematics/physics domain for relativistic
orbital mechanics.

> Earlier revisions of this document also listed `@oshun/auth`, `@oshun/cache`,
> `@oshun/event-bus` (Kafka), `@oshun/logging`, `@oshun/metrics`,
> `@oshun/domain-nyx`, and an `@oshun/contracts` `NyxEventTypes` contract. None
> of those appear in the Nyx `package.json` files or source, and there is no
> Kafka publisher; those entries have been removed. `@oshun/database` is the one
> shared infrastructure library Nyx still depends on — `apps/nyx/api` and
> `apps/nyx/pipelines` declare it and import it across the pipeline workers
> (`catalog-syncer`, `ephemeris-generator`, `event-calculator`, `tle-updater`)
> and the API key-auth middleware.

---

## Source Grounding

This architecture document was reconstructed from source: the 75
`libs/nyx/**/package.json` files, the 22 `apps/nyx/**/package.json` files,
`apps/nyx/api/src/*` (app, index, middleware, routes, websocket),
`apps/nyx/pipelines/src/*`, `libs/nyx/database/src/{schema,migrations}/*`,
`libs/nyx/lilith-integration/src/lilith-integration.ts`, `libs/nyx/README.md`,
`deploy/nyx/*`, and `TODOS/phase-21.md`.
