# okeson453/crashwave architecture

> Architecture diagram of the GitHub repository okeson453/crashwave, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-21). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/okeson453/crashwave
- Repository: https://github.com/okeson453/crashwave

## Overview

#### Purpose and Runtime Entry
A TypeScript/Node.js 20+ service automates observation and controlled participation in BC.Game Crash rounds, with Telegram operator control, deterministic safeguards, settlement, and analytics. Process composition and startup are centered on `src/index.ts`, `src/app/composition.ts`, and `src/app/spec-upgrade-wiring.ts`. Configuration is loaded and validated before runtime assembly through `src/config/loader.ts` and `src/config/schema.ts`.

#### Command, Lifecycle, and Safety Control
Telegram is the primary operator boundary: authenticated commands enter through `src/telegram/gateway.ts` and `src/telegram/router.ts`, while platform-level tenant routing is in `src/platform/telegram-router.ts`. The core orchestrator coordinates domain services over an event bus in `src/core/orchestrator.ts`, `src/core/event-bus/bus.ts`, and `src/core/event-bus/events.ts`. Session state is explicit and guarded by `src/core/state-machine/machine.ts`; emergency stops, single-instance locking, recovery, and session supervision prevent unsafe concurrent or automatic continuation (`src/core/emergency-stop.ts`, `src/core/instance-lock.ts`, `src/core/recovery-manager.ts`).

#### Game Observation and Browser Boundary
The system observes game rounds through an adapter abstraction, separating game data acquisition from execution policy: `src/game/adapter.ts`, `src/game/observer.ts`, and `src/game/adapters/aggregator.ts`. Browser automation is isolated behind session, profile, and health management in `src/browser/manager.ts`, `src/browser/session.ts`, and `src/browser/health.ts`. Protocol/WebSocket parsing forms a second game-input path in `src/protocol/session-handshake.ts` and `src/protocol/ws-payload-schemas.ts`. Proxy, TLS, and HTTP/2 behavior are similarly encapsulated under `src/network/proxy-manager.ts` and `src/network/tls/ja4-fingerprint.ts`.

#### Decision and Betting Execution
Round data feeds prediction/entry decisions and a deterministic risk gate. The prediction subsystem builds features and evaluates signals through `src/prediction/feature-engine.ts`, `src/prediction/prediction-engine.ts`, and `src/prediction/entry-decision-service.ts`; it also contains historical datasets, backtesting, and model registry components. Authorized entries pass through coordination, idempotency, execution safeguards, placement, confirmation, and cash-out control: `src/betting/betting-coordinator.ts`, `src/betting/idempotency.ts`, `src/betting/executor.ts`, `src/betting/live-executor.ts`, and `src/betting/cashout.ts`. Risk state and policy enforcement are bounded in `src/betting/risk-engine.ts` and `src/risk/velocity-controller.ts`.

#### Financial Truth, Settlement, and Persistence
PostgreSQL/TimescaleDB is the durable system of record, Redis supports runtime coordination/cache concerns, and repositories isolate storage access (`src/persistence/client.ts`, `src/persistence/redis-client.ts`, `src/persistence/transaction.ts`). Schema evolution establishes relational, time-series, tenant/RLS, audit, outbox, billing, and double-entry settlement controls under `migrations/001_init_relational.sql`, `migrations/008_tenancy.sql`, and `migrations/017_double_entry_settlement.sql`. Operational balances and daily limits are tracked in `src/ledger/balance-tracker.ts` and `src/ledger/daily-entries.ts`. Authoritative post-round settlement, drift detection, and boot reconciliation are handled by `src/settlement/authoritative-settlement-engine.ts`, `src/settlement/drift-guard.ts`, and `src/settlement/boot-reconcile.ts`.

#### Multi-Tenant Platform and Payments
The platform layer adds tenant context, quotas, container lifecycle, secrets, subscriptions, and payment integrations: `src/platform/control-plane.ts`, `src/platform/tenant-manager.ts`, and `src/platform/tenant-context.ts`. Stripe subscription webhooks are processed by `src/platform/billing/stripe-webhook.ts`; Paystack virtual-account/payment handling is in `src/platform/payments/paystack-client.ts` and `src/platform/payments/webhook-handler.ts`. Background workers perform daily billing and settlement reconciliation in `src/background-workers/daily-billing-worker.ts` and `src/background-workers/settlement-reconciler.ts`.

#### Analytics, Notifications, and Operations
Persisted round/bet outcomes feed descriptive metrics, anomaly detection, recommendations, and reports through `src/analytics/engine.ts`, `src/analytics/learning/anomaly.ts`, and `src/analytics/reports/daily.ts`. Notifications route to Telegram via `src/notifications/notification-router.ts` and `src/notifications/telegram.ts`. Health, logs, traces, metrics, and live alerts are provided by `src/observability/health/monitor.ts`, `src/observability/metrics/registry.ts`, and `src/observability/alerts/live-alerts.ts`. Docker deployments provision the application with PostgreSQL/Redis plus Prometheus and Grafana assets under `docker/docker-compose.yml`, `docker/prometheus/prometheus.yml`, and `docker/grafana/`.

Main entry points: [`src/core/orchestrator.ts`](https://github.com/okeson453/crashwave/blob/master/src/core/orchestrator.ts) (Round orchestrator), [`src/betting/betting-coordinator.ts`](https://github.com/okeson453/crashwave/blob/master/src/betting/betting-coordinator.ts) (Bet execution), [`src/game/adapter.ts`](https://github.com/okeson453/crashwave/blob/master/src/game/adapter.ts) (Game observation), [`src/persistence/client.ts`](https://github.com/okeson453/crashwave/blob/master/src/persistence/client.ts) (PostgreSQL / TimescaleDB)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime &amp; Control"]
  node_startup["Startup composition<br/>Node runtime<br/>[composition.ts]"]
  node_config["Config validation<br/>configuration boundary<br/>[loader.ts]"]
  node_telegram["Telegram gateway<br/>operator boundary<br/>[gateway.ts]"]
  node_tenant_router["Tenant routing<br/>platform router<br/>[telegram-router.ts]"]
  node_orchestrator["Round orchestrator<br/>application coordinator<br/>[orchestrator.ts]"]
  node_event_bus["Event bus<br/>domain events<br/>[bus.ts]"]
  node_session_safety["Session safety<br/>state and recovery<br/>[machine.ts]"]
end

subgraph group_game["Game &amp; Decision"]
  node_game_adapter["Game observation<br/>game adapter<br/>[adapter.ts]"]
  node_protocol["Protocol input<br/>WebSocket parser"]
  node_browser["Browser automation<br/>browser boundary<br/>[manager.ts]"]
  node_prediction["Prediction &amp; entry<br/>decision engine"]
  node_risk["Risk gate<br/>risk policy<br/>[risk-engine.ts]"]
  node_betting["Bet execution<br/>execution workflow"]
end

subgraph group_finance["Settlement &amp; Platform"]
  node_persistence[("PostgreSQL / TimescaleDB<br/>system of record<br/>[client.ts]")]
  node_redis[("Redis<br/>runtime coordination<br/>[redis-client.ts]")]
  node_ledger["Operational ledger<br/>balance tracking<br/>[balance-tracker.ts]"]
  node_settlement["Authoritative settlement<br/>settlement engine"]
  node_platform["Tenant control plane<br/>multi-tenant platform<br/>[control-plane.ts]"]
  node_payments["Billing &amp; payments<br/>payment integrations<br/>[stripe-webhook.ts]"]
end

subgraph group_ops["Operations"]
  node_analytics["Analytics &amp; reports<br/>analytics pipeline<br/>[engine.ts]"]
  node_notifications["Telegram notifications<br/>notification delivery"]
  node_observability["Observability<br/>health and alerts<br/>[monitor.ts]"]
end

node_config -->|"validates before assembly"| node_startup
node_startup -->|"wires"| node_orchestrator
node_telegram -->|"commands"| node_tenant_router
node_tenant_router -->|"tenant-scoped control"| node_orchestrator
node_orchestrator -->|"publishes / consumes"| node_event_bus
node_orchestrator -->|"lifecycle guard"| node_session_safety
node_orchestrator -->|"observes rounds"| node_game_adapter
node_protocol -->|"alternate round input"| node_game_adapter
node_game_adapter -->|"round data"| node_prediction
node_prediction -->|"entry proposal"| node_risk
node_risk -->|"authorized entry"| node_betting
node_betting -->|"place and cash out"| node_browser
node_betting -->|"execution records"| node_persistence
node_betting -->|"balance effects"| node_ledger
node_game_adapter -->|"round outcome"| node_settlement
node_settlement -->|"authoritative entries"| node_ledger
node_settlement -->|"settlement truth"| node_persistence
node_orchestrator -->|"runtime coordination"| node_redis
node_platform -->|"tenant context"| node_tenant_router
node_payments -->|"subscription and payment status"| node_platform
node_payments -->|"billing records"| node_persistence
node_persistence -->|"round and bet outcomes"| node_analytics
node_analytics -->|"reports and recommendations"| node_notifications
node_orchestrator -->|"operator alerts"| node_notifications
node_orchestrator -->|"health, logs, metrics"| node_observability

click node_startup "https://github.com/okeson453/crashwave/blob/master/src/app/composition.ts"
click node_config "https://github.com/okeson453/crashwave/blob/master/src/config/loader.ts"
click node_telegram "https://github.com/okeson453/crashwave/blob/master/src/telegram/gateway.ts"
click node_tenant_router "https://github.com/okeson453/crashwave/blob/master/src/platform/telegram-router.ts"
click node_orchestrator "https://github.com/okeson453/crashwave/blob/master/src/core/orchestrator.ts"
click node_event_bus "https://github.com/okeson453/crashwave/blob/master/src/core/event-bus/bus.ts"
click node_session_safety "https://github.com/okeson453/crashwave/blob/master/src/core/state-machine/machine.ts"
click node_game_adapter "https://github.com/okeson453/crashwave/blob/master/src/game/adapter.ts"
click node_protocol "https://github.com/okeson453/crashwave/blob/master/src/protocol/session-handshake.ts"
click node_browser "https://github.com/okeson453/crashwave/blob/master/src/browser/manager.ts"
click node_prediction "https://github.com/okeson453/crashwave/blob/master/src/prediction/entry-decision-service.ts"
click node_risk "https://github.com/okeson453/crashwave/blob/master/src/betting/risk-engine.ts"
click node_betting "https://github.com/okeson453/crashwave/blob/master/src/betting/betting-coordinator.ts"
click node_persistence "https://github.com/okeson453/crashwave/blob/master/src/persistence/client.ts"
click node_redis "https://github.com/okeson453/crashwave/blob/master/src/persistence/redis-client.ts"
click node_ledger "https://github.com/okeson453/crashwave/blob/master/src/ledger/balance-tracker.ts"
click node_settlement "https://github.com/okeson453/crashwave/blob/master/src/settlement/authoritative-settlement-engine.ts"
click node_platform "https://github.com/okeson453/crashwave/blob/master/src/platform/control-plane.ts"
click node_payments "https://github.com/okeson453/crashwave/blob/master/src/platform/billing/stripe-webhook.ts"
click node_analytics "https://github.com/okeson453/crashwave/blob/master/src/analytics/engine.ts"
click node_notifications "https://github.com/okeson453/crashwave/blob/master/src/notifications/notification-router.ts"
click node_observability "https://github.com/okeson453/crashwave/blob/master/src/observability/health/monitor.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_startup,node_config,node_telegram,node_tenant_router,node_orchestrator,node_event_bus,node_session_safety toneBlue
class node_game_adapter,node_protocol,node_browser,node_prediction,node_risk,node_betting toneAmber
class node_persistence,node_redis,node_ledger,node_settlement,node_platform,node_payments toneMint
class node_analytics,node_notifications,node_observability toneRose
```

## Components

### Runtime & Control

- [Startup composition](https://github.com/okeson453/crashwave/blob/master/src/app/composition.ts): Node runtime · Builds and wires the service after configuration validation. · `src/app/composition.ts`
- [Config validation](https://github.com/okeson453/crashwave/blob/master/src/config/loader.ts): configuration boundary · `src/config/loader.ts`
- [Telegram gateway](https://github.com/okeson453/crashwave/blob/master/src/telegram/gateway.ts): operator boundary · Authenticated operator commands enter here. · `src/telegram/gateway.ts`
- [Tenant routing](https://github.com/okeson453/crashwave/blob/master/src/platform/telegram-router.ts): platform router · `src/platform/telegram-router.ts`
- [Round orchestrator](https://github.com/okeson453/crashwave/blob/master/src/core/orchestrator.ts): application coordinator · Coordinates lifecycle and domain services through events. · `src/core/orchestrator.ts`
- [Event bus](https://github.com/okeson453/crashwave/blob/master/src/core/event-bus/bus.ts): domain events · `src/core/event-bus/bus.ts`
- [Session safety](https://github.com/okeson453/crashwave/blob/master/src/core/state-machine/machine.ts): state and recovery · Guards lifecycle, emergency stop, locking, and recovery. · `src/core/state-machine/machine.ts`

### Game & Decision

- [Game observation](https://github.com/okeson453/crashwave/blob/master/src/game/adapter.ts): game adapter · Abstracts round acquisition from execution policy. · `src/game/adapter.ts`
- [Protocol input](https://github.com/okeson453/crashwave/blob/master/src/protocol/session-handshake.ts): WebSocket parser · `src/protocol/session-handshake.ts`
- [Browser automation](https://github.com/okeson453/crashwave/blob/master/src/browser/manager.ts): browser boundary · Manages browser sessions, profiles, and health. · `src/browser/manager.ts`
- [Prediction & entry](https://github.com/okeson453/crashwave/blob/master/src/prediction/entry-decision-service.ts): decision engine · Builds features, evaluates signals, and selects entries. · `src/prediction/entry-decision-service.ts`
- [Risk gate](https://github.com/okeson453/crashwave/blob/master/src/betting/risk-engine.ts): risk policy · Enforces deterministic risk state and velocity controls. · `src/betting/risk-engine.ts`
- [Bet execution](https://github.com/okeson453/crashwave/blob/master/src/betting/betting-coordinator.ts): execution workflow · Coordinates idempotent placement, confirmation, and cash-out. · `src/betting/betting-coordinator.ts`

### Settlement & Platform

- [PostgreSQL / TimescaleDB](https://github.com/okeson453/crashwave/blob/master/src/persistence/client.ts): system of record · Durable relational, audit, outbox, and settlement data. · `src/persistence/client.ts`
- [Redis](https://github.com/okeson453/crashwave/blob/master/src/persistence/redis-client.ts): runtime coordination · `src/persistence/redis-client.ts`
- [Operational ledger](https://github.com/okeson453/crashwave/blob/master/src/ledger/balance-tracker.ts): balance tracking · Tracks balances and daily limits. · `src/ledger/balance-tracker.ts`
- [Authoritative settlement](https://github.com/okeson453/crashwave/blob/master/src/settlement/authoritative-settlement-engine.ts): settlement engine · Settles rounds and detects reconciliation drift. · `src/settlement/authoritative-settlement-engine.ts`
- [Tenant control plane](https://github.com/okeson453/crashwave/blob/master/src/platform/control-plane.ts): multi-tenant platform · Manages tenant context, quotas, containers, and secrets. · `src/platform/control-plane.ts`
- [Billing & payments](https://github.com/okeson453/crashwave/blob/master/src/platform/billing/stripe-webhook.ts): payment integrations · Processes Stripe subscriptions and Paystack payments. · `src/platform/billing/stripe-webhook.ts`

### Operations

- [Analytics & reports](https://github.com/okeson453/crashwave/blob/master/src/analytics/engine.ts): analytics pipeline · Produces metrics, anomaly detection, recommendations, and reports. · `src/analytics/engine.ts`
- [Telegram notifications](https://github.com/okeson453/crashwave/blob/master/src/notifications/notification-router.ts): notification delivery · `src/notifications/notification-router.ts`
- [Observability](https://github.com/okeson453/crashwave/blob/master/src/observability/health/monitor.ts): health and alerts · Provides health monitoring, metrics, and live alerts. · `src/observability/health/monitor.ts`

## Connections

- Config validation → Startup composition: validates before assembly
- Startup composition → Round orchestrator: wires
- Telegram gateway → Tenant routing: commands
- Tenant routing → Round orchestrator: tenant-scoped control
- Round orchestrator → Event bus: publishes / consumes
- Round orchestrator → Session safety: lifecycle guard
- Round orchestrator → Game observation: observes rounds
- Protocol input → Game observation: alternate round input
- Game observation → Prediction & entry: round data
- Prediction & entry → Risk gate: entry proposal
- Risk gate → Bet execution: authorized entry
- Bet execution → Browser automation: place and cash out
- Bet execution → PostgreSQL / TimescaleDB: execution records
- Bet execution → Operational ledger: balance effects
- Game observation → Authoritative settlement: round outcome
- Authoritative settlement → Operational ledger: authoritative entries
- Authoritative settlement → PostgreSQL / TimescaleDB: settlement truth
- Round orchestrator → Redis: runtime coordination
- Tenant control plane → Tenant routing: tenant context
- Billing & payments → Tenant control plane: subscription and payment status
- Billing & payments → PostgreSQL / TimescaleDB: billing records
- PostgreSQL / TimescaleDB → Analytics & reports: round and bet outcomes
- Analytics & reports → Telegram notifications: reports and recommendations
- Round orchestrator → Telegram notifications: operator alerts
- Round orchestrator → Observability: health, logs, metrics
