# Bellona Domain - Developer Guide

Bellona is the Build & Engine Integration domain. It manages cross-engine build
pipelines, asset packaging, content-addressable caching, and engine-specific
bridge services that allow assets to flow between game engines (Unity, Unreal,
Godot, Blender) and the Oshun platform.

---

## Prerequisites

### Required Software

| Software   | Minimum Version | Purpose                                  |
| ---------- | --------------- | ---------------------------------------- |
| Node.js    | >= 18.0.0       | Runtime for all Bellona services         |
| pnpm       | >= 9.0.0        | Package manager (monorepo workspace)     |
| Docker     | >= 24.0         | Local infrastructure (Redis, PostgreSQL) |
| TypeScript | ^6.0.3          | Type checking and compilation            |

### Optional (for engine bridge development)

| Software       | Version   | Purpose                                       |
| -------------- | --------- | --------------------------------------------- |
| Unity Editor   | >= 2022.3 | Testing `bridge-unity`                        |
| Unreal Engine  | >= 5.3    | Testing `bridge-unreal`                       |
| Godot          | >= 4.2    | Testing `bridge-godot`                        |
| Blender        | >= 4.0    | Testing `bridge-blender`                      |
| CMake          | >= 3.20   | Building the C++ SDK (`libs/bellona/sdk-cpp`) |
| C++17 compiler |           | Required for `sdk-cpp`                        |

---

## Project Structure

```
apps/bellona/
  build-api/          # Build orchestration API (content-addressable cache, event handling)
  build-worker/       # Background worker that executes build jobs
  render-api/         # GPU render queue API with output validation
  bridge-unity/       # Unity engine bridge service
  bridge-unreal/      # Unreal Engine bridge service
  bridge-godot/       # Godot engine bridge service
  bridge-blender/     # Blender engine bridge service
  cli/                # Command-line interface for build, export, sync operations

libs/bellona/
  client/             # TypeScript API client (@oshun/bellona-client)
  database/           # Prisma schema and generated client (@bellona/database)
  interchange-models/ # Cross-engine interchange format (scene, material, animation converters)
  sdk-cpp/            # C++ SDK for engine plugin development
  xr/                 # XR platform support (VisionOS, Quest)
```

### Key Dependencies

- `@oshun/logging` - Structured logging (pino)
- `@oshun/event-bus` - Cross-domain event system (Redis Streams)
- `@oshun/cache` - Caching primitives
- `@bellona/event-handlers` - Domain-specific event handler setup
- `commander` - CLI framework (in `apps/bellona/cli`)
- `chalk`, `ora`, `inquirer` - CLI UX utilities

---

## Local Development Setup

### 1. Start Infrastructure

Bellona requires PostgreSQL and Redis for its build-api and worker services.

```bash
# From the monorepo root
docker compose -f docker/docker-compose.dev.yml up -d
```

This starts PostgreSQL (port 5432) and Redis (port 6379).

### 2. Set Environment Variables

Bellona services read the following environment variables:

| Variable                  | Default                  | Used By                 |
| ------------------------- | ------------------------ | ----------------------- |
| `REDIS_URL`               | `redis://localhost:6379` | build-api, build-worker |
| `BELLONA_DATABASE_URL`    | (see root `.env`)        | database lib            |
| `BUILD_CACHE_MEMORY_SIZE` | `104857600` (100 MB)     | build-api               |
| `BUILD_CACHE_MAX_SIZE`    | `10737418240` (10 GB)    | build-api               |

The root `.env` file provides `BELLONA_DATABASE_URL` pointing to the `bellona`
database on the local PostgreSQL instance.

### 3. Generate Prisma Client

```bash
cd libs/bellona/database
npx prisma generate
npx prisma db push   # Apply schema to local DB (development only)
```

### 4. Install Dependencies

```bash
# From monorepo root
pnpm install
```

### 5. Seed the Database (optional)

```bash
cd libs/bellona/database
npx tsx prisma/seed.ts
```

For test data:

```bash
npx tsx prisma/seed-test.ts
```

---

## Running Services

### Build API

The build API is the central orchestration service. It initializes the
content-addressable build cache and sets up cross-domain event handlers.

```bash
# Development (hot reload)
pnpm nx serve bellona-build-api

# Or directly:
cd apps/bellona/build-api
pnpm dev   # tsx watch src/main.ts
```

The build API listens for events via the event bus (Redis Streams) and manages
in-memory build/export job queues. In production, these queues would use
Redis/BullMQ.

### Build Worker

```bash
pnpm nx serve bellona-build-worker
```

### Render API

The render API manages GPU render jobs with queue management and output
validation.

```bash
pnpm nx serve bellona-render-api
```

### Engine Bridges

Each bridge connects a specific game engine to the Oshun platform:

```bash
# Unity bridge
pnpm nx serve bellona-bridge-unity

# Unreal bridge
pnpm nx serve bellona-bridge-unreal

# Godot bridge
pnpm nx serve bellona-bridge-godot

# Blender bridge
pnpm nx serve bellona-bridge-blender
```

### CLI

The CLI provides command-line access to build, export, sync, and project
management operations.

```bash
# Development (hot reload)
pnpm nx dev @bellona/cli

# After building
pnpm nx build @bellona/cli
pnpm nx start @bellona/cli

# Available commands
bellona build     # Trigger a build
bellona export    # Export assets
bellona sync      # Sync with engine
bellona project   # Manage projects
bellona health    # Check service health
bellona config    # Manage configuration
```

---

## Building

### Build All Bellona Projects

```bash
pnpm nx run-many --target=build --projects=tag:scope:bellona
```

### Build Individual Projects

```bash
# Build API (tsc)
pnpm nx build bellona-build-api

# CLI (tsc with dependsOn: ^build)
pnpm nx build @bellona/cli

# Render API (@nx/js:tsc)
pnpm nx build bellona-render-api

# C++ SDK (CMake)
cd libs/bellona/sdk-cpp
mkdir build && cd build
cmake ..
make
```

---

## Testing

### Test Runner Configuration

Bellona uses a mix of Jest and Vitest depending on the project:

| Project      | Runner | Config File                                |
| ------------ | ------ | ------------------------------------------ |
| build-api    | Jest   | `apps/bellona/build-api/jest.config.ts`    |
| render-api   | Jest   | `apps/bellona/render-api/jest.config.ts`   |
| build-worker | Jest   | `apps/bellona/build-worker/jest.config.ts` |
| bridge-unity | Jest   | `apps/bellona/bridge-unity/jest.config.ts` |
| cli          | Vitest | (runs via `vitest run`)                    |
| database lib | Vitest | `libs/bellona/database/vitest.config.ts`   |

### Running Tests

```bash
# Test all Bellona projects
pnpm nx run-many --target=test --projects=tag:scope:bellona

# Test individual projects
pnpm nx test bellona-build-api
pnpm nx test @bellona/cli

# Test the database library
pnpm nx test @bellona/database
```

### Test the C++ SDK

```bash
cd libs/bellona/sdk-cpp/build
ctest
```

### Linting

```bash
pnpm nx run-many --target=lint --projects=tag:scope:bellona

# Individual project
pnpm nx lint bellona-build-api
```

### Type Checking

```bash
# CLI has a dedicated typecheck target
pnpm nx typecheck @bellona/cli
```

---

## Database Schema

The Bellona database (`libs/bellona/database/prisma/schema.prisma`) uses
PostgreSQL and contains these key models:

| Model           | Purpose                                                         |
| --------------- | --------------------------------------------------------------- |
| `Build`         | Build job record (status, platforms, assets, worker assignment) |
| `BuildArtifact` | Output files from builds (path, checksum, storage location)     |
| `BuildLog`      | Structured build log entries                                    |
| `ExportJob`     | Export job records (format, engine target, download URL)        |
| `EngineProject` | Engine project generation records                               |
| `BridgeSession` | Active engine bridge sessions (connection status, sync state)   |
| `SyncConflict`  | Sync conflicts between local and remote asset versions          |
| `BuildWorker`   | Registered build workers with capabilities                      |
| `AssetCache`    | Cached asset metadata for quick lookups                         |
| `BuildTemplate` | Reusable build configuration templates                          |
| `AuditLog`      | Change tracking for all entities                                |

### Key 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
- `JobType`: ASSET_BAKE, VALIDATE, ENGINE_PROJECT_GENERATE, EXPORT_PACKAGE

---

## Common Development Tasks

### Adding a New Engine Bridge

1. Create the app directory:

   ```
   apps/bellona/bridge-<engine>/
     src/
       main.ts
     project.json
     package.json
     tsconfig.json
     tsconfig.app.json
   ```

2. Define `project.json` following the pattern of existing bridges (e.g.,
   `bridge-unity`). Use tags `["scope:bellona", "type:app"]`.

3. Add the engine to the `EngineType` enum in
   `libs/bellona/database/prisma/schema.prisma`:

   ```prisma
   enum EngineType {
     UNITY
     UNREAL
     GODOT
     BLENDER
     WEB
     YOUR_ENGINE  // Add here
   }
   ```

4. Run `npx prisma generate` in `libs/bellona/database/` to regenerate the
   Prisma client.

5. Implement the bridge service in `src/main.ts`. It should handle WebSocket or
   gRPC connections from the engine plugin, asset synchronization, and conflict
   resolution.

6. Add converter support in `libs/bellona/interchange-models/` for any
   engine-specific formats.

7. Register the bridge in the path mappings in `tsconfig.base.json` if it
   exports a library.

### Adding a New Build Job Type

1. Add the job type to the `JobType` enum in the Prisma schema:

   ```prisma
   enum JobType {
     ASSET_BAKE
     VALIDATE
     ENGINE_PROJECT_GENERATE
     EXPORT_PACKAGE
     YOUR_JOB_TYPE  // Add here
   }
   ```

2. Regenerate the Prisma client:

   ```bash
   cd libs/bellona/database && npx prisma generate
   ```

3. In `apps/bellona/build-worker/`, create a new executor for the job type that
   implements the job processing logic.

4. Register the executor in the worker's job dispatcher so it routes the new job
   type to your executor.

5. Add the corresponding CLI command in `apps/bellona/cli/src/commands/` if
   users need to trigger this job type from the command line.

### Adding a New CLI Command

1. Create a new file in `apps/bellona/cli/src/commands/`:

   ```typescript
   import { Command } from 'commander';

   export function registerMyCommand(program: Command): void {
     program
       .command('my-command')
       .description('Description of what this command does')
       .option('-f, --flag <value>', 'option description')
       .action(async (options) => {
         // Implementation
       });
   }
   ```

2. Register the command in `apps/bellona/cli/src/index.ts`.

---

## Debugging Tips

### Build API Not Starting

- Verify Redis is running: `docker ps | grep redis`
- Check `REDIS_URL` environment variable is set correctly
- The build API continues without event handlers if Redis connection fails (logs
  a warning)

### Prisma Client Issues

- Run `npx prisma generate` after any schema changes
- For a fresh start: `npx prisma db push --force-reset`
- Check `BELLONA_DATABASE_URL` points to a running PostgreSQL instance

### Event Bus Connection Failures

The build API uses `@oshun/event-bus` with Redis Streams. If events are not
flowing:

- Check Redis connectivity
- Verify the `sourceDomain` is set to `'bellona'`
- Check consumer group name (`bellona-build-api`)
- Review dead letter queue: events that fail processing 3 times are moved to DLQ

### CLI Not Connecting to API

- Ensure the build API is running first
- Check the API URL configuration in `apps/bellona/cli/src/utils/client.ts`
- Run `bellona health` to verify connectivity

### Bridge Session Issues

- Bridge sessions track heartbeats; stale sessions indicate connection drops
- Check `lastHeartbeat` timestamps in the `bridge_sessions` table
- Sync conflicts are stored in `sync_conflicts` and require manual resolution if
  not auto-resolved

### Performance Debugging

- The build cache reports hit rates via `getHealthStatus()` in the build API
- Monitor cache stats: `hitRate`, `totalEntries`
- Memory cache size defaults to 100 MB; adjust `BUILD_CACHE_MEMORY_SIZE` if
  needed
- Build logs are stored in the `build_logs` table with level, source, and step
  fields for granular filtering
