# Bellona Domain Architecture

> **Canonical source:** the canonical architecture document for this domain is
> [`deep-dive/architecture.md`](./deep-dive/architecture.md), rendered in the
> docs center. This file is its operational companion (service topology, APIs,
> schemas, runtime detail) — reconciled by linking, not duplicated (§2, §13).

> Comprehensive architectural documentation for the Bellona Build and Bridge
> Platform.

## System Overview

Bellona is the build orchestration, asset interchange, and game engine bridge
platform within the Oshun monorepo. It provides the infrastructure to connect
the Oshun creative ecosystem with external game engines and creative tools
including Unity, Unreal Engine, Godot, Blender, and Houdini. The domain handles
asset compilation, format conversion, project generation, and real-time
bidirectional synchronization between Oshun services and engine editor
instances.

Bellona sits at the boundary between the Oshun platform and the external game
development toolchain. Assets created in Hathor (worldbuilding) or generated by
Isis (generative AI) flow through Bellona to reach their final engine-native
formats.

## Service Architecture

### Apps (8 services)

```
                         +------------------+
                         |   bellona CLI     |
                         |   (Commander)     |
                         +--------+---------+
                                  |
                 +----------------+----------------+
                 |                                  |
        +--------v---------+              +---------v--------+
        |   build-api      |              |   render-api     |
        |   (Port 4005)    |              |   (Redis cache)  |
        |   @oshun/cache   |              |   GPU queue mgmt |
        |   @oshun/event-bus              +------------------+
        +--------+---------+
                 |
        +--------v---------+
        |   build-worker   |
        |   Job queue poll |
        |   4 job types:   |
        |   - asset-bake   |
        |   - validate     |
        |   - engine-proj  |
        |   - export-pkg   |
        +------------------+

   +---------------+  +----------------+  +----------------+  +----------------+
   | bridge-unity  |  | bridge-unreal  |  | bridge-godot   |  | bridge-blender |
   | ws://9004     |  | ws://9003      |  | ws://9002      |  | ws://9001      |
   | /unity        |  | /unreal        |  | /godot         |  | /blender       |
   +---------------+  +----------------+  +----------------+  +----------------+
```

#### build-api (Port 4005)

The central build orchestration API. Manages build and export job submission,
status tracking, and content-addressable artifact caching.

- **Framework**: Node.js with `@oshun/logging`
- **Cache**: Redis-backed content-addressable build cache with compression,
  deduplication, and PubSub (100MB memory cache, 10GB max)
- **Events**: `@oshun/event-bus` for cross-domain communication (Bellona source
  domain, 24h event TTL, exponential retry with dead-letter queue)
- **Queue Adapters**: In-memory build/export job queues (production would use
  Redis/Bull)
- **Health**: Exposes health status including cache hit rate and total entries
- **Dependencies**: `@oshun/logging`, `@oshun/event-bus`, `@oshun/cache`,
  `@bellona/event-handlers`

#### build-worker

Background job processor that polls a queue and dispatches to specialized worker
functions. Publishes cross-domain events via `@bellona/event-publisher` on job
start, progress, and completion.

- **Job Types**: `asset-bake`, `validate`, `engine-project-generate`,
  `export-package`
- **Worker Management**: Configurable concurrency, poll interval, heartbeat,
  graceful shutdown with timeout
- **Event Publishing**: Publishes `bellona.build.started`,
  `bellona.build.progress`, `bellona.build.completed`, `bellona.export.started`,
  `bellona.export.ready` events
- **Dependencies**: `@bellona/event-publisher`

#### render-api

GPU render job management service with Redis-backed caching, output validation,
and GPU device queue management.

- **Cache**: `RenderCacheService` with Redis PubSub and metrics
- **Validation**: `OutputValidator` for render output quality checks
- **GPU Queue**: `GpuRenderQueue` with GPU device allocation, queued job
  management
- **Types**: Supports render engines, output formats, quality presets, animation
  settings, frame ranges, resolutions
- **Dependencies**: `@oshun/logging`

#### cli

Commander-based CLI tool (`bellona`) for game development workflow automation.

- **Commands**: `build`, `export`, `sync`, `config`, `health`, `project`,
  `detect`
- **Quick Aliases**: `b` (build), `e` (export)
- **Features**: Project detection (auto-detect engine projects in directory),
  `bellona.yaml` configuration, profile management, JSON output mode, API key
  auth
- **API URL**: Defaults to `http://localhost:3020`, configurable via
  `BELLONA_API_URL`
- **Dependencies**: `commander`, `chalk`, `dotenv`

#### bridge-unity (WebSocket Port 9004)

WebSocket bridge for Unity Engine integration using `@bellona/bridge-core`.

- **Endpoint**: `ws://localhost:9004/unity`
- **Commands**: `unity:get-scene-info`, `unity:create-game-object`,
  `unity:destroy-game-object`, `unity:add-component`,
  `unity:set-component-property`, `unity:load-scene`, `unity:unload-scene`,
  `unity:instantiate-prefab`, `unity:set-transform`, `unity:play-animation`,
  `unity:set-animator-parameter`, `unity:apply-force`, `unity:raycast`,
  `unity:send-message`

#### bridge-unreal (WebSocket Port 9003)

WebSocket bridge for Unreal Engine integration.

- **Endpoint**: `ws://localhost:9003/unreal`
- **Commands**: `unreal:get-world-info`, `unreal:spawn-actor`,
  `unreal:destroy-actor`, `unreal:set-actor-property`,
  `unreal:call-blueprint-function`, `unreal:load-level`, `unreal:unload-level`,
  `unreal:set-material-parameter`, `unreal:sequencer-control`,
  `unreal:execute-console-command`, `unreal:take-screenshot`

#### bridge-godot (WebSocket Port 9002)

WebSocket bridge for Godot Engine integration.

- **Endpoint**: `ws://localhost:9002/godot`
- **Commands**: `godot:get-scene-tree`, `godot:create-node`,
  `godot:set-node-property`, `godot:call-node-method`, `godot:load-scene`,
  `godot:load-resource`, `godot:emit-signal`, `godot:execute-gdscript`,
  `godot:get-project-settings`

#### bridge-blender (WebSocket Port 9001)

WebSocket bridge for Blender integration with session tracking and cross-domain
event publishing.

- **Endpoint**: `ws://localhost:9001/blender`
- **Commands**: `blender:get-scene-info`, `blender:create-object`,
  `blender:import-asset`, `blender:export-asset`, `blender:set-frame`,
  `blender:render`
- **Events**: Publishes `bellona.session.started` and `bellona.session.ended`
  events with session duration, commands executed, and disconnect reason
- **Dependencies**: `@bellona/bridge-core`, `@bellona/event-publisher`

## Library Architecture

### Core Infrastructure (7 libraries)

| Library                       | Purpose                                                                                                                                                                                    |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@bellona/bridge-core`        | WebSocket server/client framework with typed events, command routing, message encoding, heartbeat, reconnection, request/response pattern                                                  |
| `@bellona/adapters`           | Engine adapter infrastructure: `BaseBridge`, `CommandQueue`, `CommandExecutor`, `StateManager`, `ProcessLauncher`, `VersionManager`, middleware system                                     |
| `@bellona/client`             | TypeScript SDK (`BellonaClient`) with build, export, and engine sync helpers. Supports `triggerBuild`, `exportForUnity/Unreal/Godot`, `syncAssets`, `bidirectionalSync`, `resolveConflict` |
| `@bellona/database`           | Prisma ORM schema and generated client for the `bellona` PostgreSQL schema                                                                                                                 |
| `@bellona/interchange`        | Universal 3D asset interchange: GLTF/GLB, USD/USDA/USDC/USDZ, FBX import/export, transform pipelines, validation, batch conversion, LRU asset cache                                        |
| `@bellona/interchange-models` | Zod schemas and TypeScript types for interchange data structures                                                                                                                           |
| `@bellona/integration`        | Cross-domain integration: `HathorArtifactConsumer` (lore content), `LoreToEngineCompiler`, `IsisAssetConsumer` (generated content), `AssetConverter`                                       |

### Engine Adapters (7 libraries)

| Library            | Purpose                                                                                                                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `@bellona/godot`   | Godot 4.0-4.2 adapter: WebSocket bridge, `.tscn` scene files, `project.godot` management, version discovery                               |
| `@bellona/unreal`  | Unreal 5.0-5.3 adapter: Remote Control API bridge, `.uproject` files, FBX import, MetaHuman integration, Live Link, LOD/collision/physics |
| `@bellona/unity`   | Unity 2022-2023 adapter: WebSocket bridge, prefab management, FBX import                                                                  |
| `@bellona/blender` | Blender 3.6-4.0 adapter: `bpy` integration, GLTF/FBX/Blend import/export                                                                  |
| `@bellona/houdini` | Houdini 19.5+ adapter (Beta): HDA assets, USD pipeline                                                                                    |
| `@bellona/davinci` | DaVinci Resolve integration                                                                                                               |
| `@bellona/openusd` | OpenUSD pipeline: USD SDK, composition, variant management, MaterialX shader support                                                      |

### Specialized Systems (8 libraries)

| Library                       | Purpose                                                                                                                                                                                          |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@bellona/gameplay-systems`   | Production gameplay systems: input handling (keyboard/mouse/gamepad/touch/VR), save/load with cloud sync, inventory, combat with abilities/effects, AI behavior trees/utility AI/GOAP/perception |
| `@bellona/metahuman`          | MetaHuman pipeline: identity management, mesh types, LODs, face rig, body customization                                                                                                          |
| `@bellona/mocap`              | Motion capture: multi-vendor streaming (OptiTrack, Vicon, Xsens, Rokoko), skeleton retargeting, BVH/C3D/TRC parsing, animation clip generation, keyframe reduction                               |
| `@bellona/virtual-production` | Virtual production: camera tracking (Ncam, Mo-Sys, OptiTrack, Vicon), LED wall control, ICVFX compositing, genlock/timecode sync                                                                 |
| `@bellona/xr`                 | XR support: visionOS (Apple Vision Pro), Meta Quest (2/Pro/3), WebXR. Hand tracking, eye tracking, spatial anchors, scene understanding                                                          |
| `@bellona/audio`              | Audio processing for game engines                                                                                                                                                                |
| `@bellona/video`              | Video processing for game engines                                                                                                                                                                |
| `@bellona/sdk-cpp`            | C++ SDK for native engine plugin integration                                                                                                                                                     |

### Event System (2 libraries)

| Library                    | Purpose                                                                                                                                                                                                                |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@bellona/event-publisher` | Type-safe event publishing: `publishSessionStarted`, `publishSessionEnded`, `publishBuildStarted`, `publishBuildProgress`, `publishBuildCompleted`, `publishExportStarted`, `publishExportReady`, `publishAssetSynced` |
| `@bellona/event-handlers`  | Cross-domain event subscriptions: handles `hathor.world.published`, `isis.asset.generated`, `yemaya.build.requested`, `yemaya.export.requested`. Includes metrics collection and stats tracking                        |

## Data Flow

### Build Pipeline

```
   Yemaya/Hathor/Isis               Bellona                        Engine
   ─────────────────     ──────────────────────────     ─────────────────────

   yemaya.build          build-api
   .requested  ───────>  enqueue build job
                              │
                         build-worker
                              │ poll queue
                              │
                              ├─ asset-bake
                              │  (texture/mesh/shader
                              │   compilation)
                              │
                              ├─ validate
                              │  (format checks,
                              │   compatibility)
                              │
                              ├─ engine-project-generate
                              │  (Unity/Unreal/Godot
                              │   project files)
                              │
                              └─ export-package
                                 (ZIP/TAR/UNITYPACKAGE/
                                  UASSET/GODOT_PCK)
                                      │
                         bellona.build ──────────> S3 artifact storage
                         .completed
```

### Bridge Synchronization

```
   Engine Editor                 Bridge Service              Oshun Platform
   ─────────────          ──────────────────────     ─────────────────────

   Unity/Unreal/          bridge-{engine}            @bellona/integration
   Godot/Blender               │                         │
        │                      │                          │
        │  WebSocket     ┌─────┴─────┐                    │
        ├──connect────>  │ handshake  │                    │
        │                │ ping/pong  │                    │
        │  commands      │ heartbeat  │                    │
        ├──────────────> │ routing    │                    │
        │                └─────┬─────┘                    │
        │                      │                          │
        │                bellona.session                   │
        │                .started ──────────────────────>  │
        │                      │                          │
        │               asset sync                        │
        │               push/pull ────────────────────>   │
        │                      │                          │
        │                bellona.asset                     │
        │                .synced ──────────────────────>   │
        │                      │                          │
        │  disconnect    bellona.session                   │
        ├──────────────> .ended ───────────────────────>   │
```

### Cross-Domain Integration

```
   Hathor (Worldbuilding)           Bellona                   Target Engine
   ──────────────────────    ──────────────────────    ──────────────────────

   hathor.world.published    HathorArtifactConsumer
   (lore, quests,     ────>  │
    dialogue, NPCs)          LoreToEngineCompiler
                             │ compile to engine
                             │ format (GDScript,
                             │ Blueprint, C#)    ────>  Engine-native files

   Isis (Generative AI)
   ──────────────────────

   isis.asset.generated      IsisAssetConsumer
   (textures, 3D     ────>  │
    models, audio)           AssetConverter
                             │ convert textures,
                             │ models, audio for  ────> Engine-native assets
                             │ target engine
```

## Database Schema

PostgreSQL database with Prisma ORM. Connection URL:
`BELLONA_DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/bellona`

### Models

| Model           | Purpose                                                      | Key Fields                                                                               |
| --------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
| `Build`         | Build job tracking with status, priority, platform targeting | `status`, `priority`, `targetPlatforms[]`, `optimizationLevel`, `assetIds[]`, `workerId` |
| `BuildArtifact` | Output files from builds with S3 storage references          | `platform`, `path`, `size`, `checksum`, `storageBucket`, `storageKey`                    |
| `BuildLog`      | Debug/info/warning/error log entries per build               | `level`, `message`, `source`, `step`                                                     |
| `ExportJob`     | Export job with format targeting and download management     | `format` (ZIP/TAR_GZ/UNITYPACKAGE/UASSET/GODOT_PCK), `targetEngine`, `downloadUrl`       |
| `EngineProject` | Engine project generation records                            | `engine`, `engineVersion`, `modules[]`, `plugins[]`, `platforms[]`                       |
| `BridgeSession` | WebSocket bridge session tracking                            | `engine`, `status` (CONNECTED/DISCONNECTED/SYNCING/ERROR), `syncDirection`, `lastSyncAt` |
| `SyncConflict`  | Asset version conflicts during sync                          | `assetId`, `localVersion`, `remoteVersion`, `resolution`                                 |
| `BuildWorker`   | Worker registration with capabilities                        | `jobTypes[]`, `platforms[]`, `engines[]`, `concurrency`, `status`                        |
| `AssetCache`    | Content-addressable asset metadata cache                     | `assetId`, `type`, `checksum`, `tags[]`, `engineData`                                    |
| `BuildTemplate` | Reusable build configuration templates                       | `platforms[]`, `engines[]`, `optimizationLevel`, `settings`                              |
| `AuditLog`      | Change tracking for all entities                             | `action`, `entityType`, `entityId`, `previousState`, `newState`                          |

### Enums

- **BuildStatus**: PENDING, QUEUED, RUNNING, COMPLETED, FAILED, CANCELLED
- **Platform**: WINDOWS, MACOS, LINUX, IOS, ANDROID, WEBGL, PLAYSTATION, XBOX,
  SWITCH
- **EngineType**: UNITY, UNREAL, GODOT, BLENDER, WEB
- **ExportFormat**: ZIP, TAR_GZ, UNITYPACKAGE, UASSET, GODOT_PCK
- **AssetType**: TEXTURE, MODEL, AUDIO, ANIMATION, MATERIAL, PREFAB, SCRIPT,
  CONFIG, OTHER
- **JobType**: ASSET_BAKE, VALIDATE, ENGINE_PROJECT_GENERATE, EXPORT_PACKAGE

## API Endpoints

### Build API (Port 4005)

| Method | Path                        | Description                |
| ------ | --------------------------- | -------------------------- |
| POST   | `/v1/builds`                | Create build job           |
| GET    | `/v1/builds/:id`            | Get build status           |
| POST   | `/v1/exports`               | Create export job          |
| GET    | `/v1/exports/:id`           | Get export status          |
| GET    | `/v1/exports/:id/artifacts` | List export artifacts      |
| GET    | `/v1/exports/:id/download`  | Download export artifacts  |
| GET    | `/v1/engines`               | List supported engines     |
| POST   | `/v1/convert`               | Asset format conversion    |
| GET    | `/health`                   | Liveness check             |
| GET    | `/ready`                    | Readiness check with cache |

### Bridge WebSocket Commands

All bridges support `handshake` and `ping` commands via `@bellona/bridge-core`.
Engine-specific commands are prefixed with the engine name (e.g.,
`unity:create-game-object`).

## Technology Stack

| Layer          | Technology                                       |
| -------------- | ------------------------------------------------ |
| Runtime        | Node.js (TypeScript)                             |
| API Framework  | Hono (build-api, render-api)                     |
| WebSocket      | `ws` library via `@bellona/bridge-core`          |
| Database       | PostgreSQL with Prisma ORM (schema: `bellona`)   |
| Cache          | Redis (content-addressable build cache)          |
| Object Storage | S3-compatible (MinIO in dev)                     |
| CLI Framework  | Commander.js with chalk                          |
| Event Bus      | `@oshun/event-bus` (Redis Streams)               |
| Logging        | `@oshun/logging`                                 |
| Build          | Nx with `@nx/js:tsc`                             |
| Testing        | Vitest / Jest                                    |
| Native SDK     | C++ via `@bellona/sdk-cpp`                       |
| Asset Formats  | GLTF/GLB, USD/USDA/USDC/USDZ, FBX, OBJ, PLY, STL |

## Deployment Architecture

```
   ┌─────────────────────────────────────────────────────────────┐
   │                        ECS Cluster                          │
   │                                                             │
   │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐  │
   │  │  build-api   │  │  render-api  │  │   build-worker   │  │
   │  │  (Fargate)   │  │  (Fargate)   │  │   (EC2 GPU)      │  │
   │  └──────┬───────┘  └──────┬───────┘  └────────┬─────────┘  │
   │         │                 │                    │            │
   │  ┌──────┴─────────────────┴────────────────────┴────────┐  │
   │  │                     Redis                             │  │
   │  │             (cache + event bus)                        │  │
   │  └──────────────────────┬────────────────────────────────┘  │
   │                         │                                   │
   │  ┌──────────────────────┴────────────────────────────────┐  │
   │  │                   PostgreSQL                           │  │
   │  │              (bellona schema)                           │  │
   │  └───────────────────────────────────────────────────────┘  │
   │                                                             │
   │  ┌─────────────┐ ┌──────────────┐ ┌─────────────────────┐  │
   │  │bridge-unity │ │bridge-unreal │ │ bridge-godot/blender│  │
   │  │ (Fargate)   │ │ (Fargate)    │ │ (Fargate)           │  │
   │  └─────────────┘ └──────────────┘ └─────────────────────┘  │
   └─────────────────────────────────────────────────────────────┘
                              │
                    ┌─────────┴─────────┐
                    │   S3 (MinIO dev)  │
                    │  Build artifacts  │
                    └───────────────────┘
```

- **CI/CD**: Core `ci.yml` pipeline, `deploy-ecs.yml` for deployment,
  `database.yml` for migrations
- **Build Workers**: GPU-capable EC2 instances for render and asset bake jobs
- **Bridge Services**: Lightweight Fargate tasks, one per engine type

## Cross-Domain Dependencies

### Shared Oshun Libraries Used

| Library            | Usage in Bellona                                   |
| ------------------ | -------------------------------------------------- |
| `@oshun/logging`   | Structured logging across all apps and libs        |
| `@oshun/event-bus` | Cross-domain event publishing and subscription     |
| `@oshun/cache`     | Redis cache abstraction for build artifact caching |
| `@oshun/metrics`   | Metrics collection for event handler performance   |

### Domains That Publish Events Consumed by Bellona

| Domain | Event                     | Bellona Handler                       |
| ------ | ------------------------- | ------------------------------------- |
| Hathor | `hathor.world.published`  | Triggers engine project generation    |
| Isis   | `isis.asset.generated`    | Converts and imports generated assets |
| Yemaya | `yemaya.build.requested`  | Enqueues a build job                  |
| Yemaya | `yemaya.export.requested` | Enqueues an export job                |

### Events Published by Bellona

| Event                     | Consumers                           |
| ------------------------- | ----------------------------------- |
| `bellona.session.started` | Analytics, monitoring               |
| `bellona.session.ended`   | Analytics, monitoring               |
| `bellona.build.started`   | Yemaya UI, notifications            |
| `bellona.build.progress`  | Yemaya UI (real-time progress)      |
| `bellona.build.completed` | Yemaya, Hathor (asset availability) |
| `bellona.export.started`  | Yemaya UI                           |
| `bellona.export.ready`    | Yemaya (download notification)      |
| `bellona.asset.synced`    | Analytics, asset tracking           |
