# Cybele — Systems Deep Dive

> The `libs/cybele/` area: nineteen Nx libraries implementing the **Ghana real
> estate, construction, and proptech domain** — from geodesy and pro-forma math
> through site selection, structural design, prefab housing, and an API gateway.

## What this area is

Cybele is Oshun's **built-environment domain**: the physical-space counterpart
to Freya's luxury-goods supply side. Unlike a thin CRUD service, the
`libs/cybele/` tree is a deep, expert-grounded body of domain logic specialised
for the Ghanaian market — its constants, standards, and data are real
(`GHANA_CONCRETE_MIXES` keyed to GS 298 / BS EN 771-3 in
`libs/cybele/materials/src/concrete.ts`, AASHTO-1993 flexible-pavement design in
`libs/cybele/infrastructure/src/roads.ts`, BS 8110 / Eurocode 2 RC-beam design
in `libs/cybele/design/src/structural.ts`, and the ~1.8M-unit regional housing
deficit table in `libs/cybele/prefab/src/affordability.ts`). The recurring
header comment "Ghana Real Estate & Construction" in `@cybele/core` is the
through-line for the whole area.

The nineteen libraries form a layered stack rather than a flat list. At the base
sit the **foundations**: `@cybele/core` (branded ID types, Zod validators, type
guards, serializers), `@cybele/common` (pure WGS84/UTM geodesy, date and money
math, Ghana GPS digital-address parsing, carbon/ESG), and `@cybele/db` (the
Drizzle Postgres schema plus PostGIS/TimescaleDB migrations). On top of those
sit the **domain engines** — one library per business capability: `property`,
`construction`, `materials`, `design`, `finance`, `financials`, `market-intel`,
`prefab`, `proptech`, `site-analysis`, `infrastructure`, `hospitality`, and
`industrial-parks`. Above the engines, `@cybele/api` is the Hono-based gateway
that exposes them over REST/GraphQL/gRPC/WebSocket, and `@cybele/integration`
carries the cross-domain bridge contracts. `@cybele/testing` supplies fixture
factories and mocks the others share.

The engines are deliberately granular: each is a small package whose `src/`
modules map one-to-one onto sub-capabilities (e.g. `finance` splits into
`mortgage`, `reit`, `proforma`, `crowdfunding`, `alternative-finance`). The
public surface of every library is its `src/index.ts` barrel; a few libraries
also carry additional modules in `src/` that are not re-exported from the
top-level barrel (noted per entity below).

## How it fits the wider system

These libraries are consumed in three ways. First, **`@cybele/api`** composes
the domain engines into a deployable gateway (`createGateway`,
`CYBELE_SERVICE_REGISTRY`) with auth/RBAC, rate limiting, OpenTelemetry tracing,
Prometheus metrics, circuit breakers, and a Kafka event bus — this is the entry
point a running Cybele service would mount. Second, **`@cybele/integration`**
declares the typed bridges to sibling domains — Brigid (industrial
manufacturing), Saraswati (creative authoring), Asase, Freya, and Maat
(governance/risk) — so cross-domain traffic is contract-checked rather than ad
hoc. Third, the wire surface for the domain lives in the separate
`@contracts/cybele` package under `libs/contracts/` (documented in the contracts
area), keeping Zod boundary schemas decoupled from this business logic.

The boundary to respect: the foundation libraries (`core`, `common`, `db`) carry
no upstream domain dependencies, the engines depend on those foundations, and
`api` plus `integration` sit at the top composing everything. Walk the "used by"
edges on any node below to see exactly who depends on it.

## Entity reference

### @cybele/api

The Cybele **API gateway and service mesh** (`libs/cybele/api/src`).
`gateway.ts` builds a Hono application mounted at `/api/v1` with route groups
per business capability (`/properties`, `/construction`, `/leases`,
`/materials`, `/finance`, `/market-intel`) plus a full production middleware
pipeline: JWT auth + RBAC (`auth.ts`, `ROLE_PERMISSIONS`), tiered rate limiting
(`rate-limit.ts`), OpenTelemetry tracing (`tracing.ts`), Prometheus metrics
(`metrics.ts`), circuit breakers (`circuit-breaker.ts`), structured logging, and
`/health` checks. It also ships a Kafka publisher/consumer with dead-letter
handling (`kafka.ts`, `CYBELE_KAFKA_TOPICS`), a GraphQL schema
(`graphql/schema.ts`), a WebSocket server with channel-authorization
(`websocket/server.ts`), gRPC proto definitions (`grpc/definitions.ts`), an
OpenAPI spec (`openapi/cybele-api.yaml`), and concrete route repositories
including a `DrizzlePropertyRepository` and an `InMemoryConstructionLedger` with
on-chain EVM input derivation.

### @cybele/common

The domain-agnostic **utility foundation** (`libs/cybele/common/src`), a
pure-math package with no external runtime deps. `geo.ts` implements real WGS84
geodesy (haversine, bounding boxes, UTM Zone 30N ↔ WGS84 projection, polygon
operations, and Ghana GPS digital-address parsing) against WGS84 ellipsoid
constants; `math.ts`, `dates.ts`, and `ids.ts` provide money/number math, date
helpers, and ID utilities; and `carbon-esg.ts` adds carbon/ESG accounting. The
barrel (`index.ts`) re-exports `math`, `dates`, `geo`, and `ids`; `carbon-esg`
lives in the package with its own test.

### @cybele/construction

The **construction-management engine** (`libs/cybele/construction/src`). Its
barrel exports `scheduling` (Critical Path Method forward/backward pass, PERT,
look-ahead, WBS — all per PMI PMBOK in `scheduling.ts`), `cost` (earned-value),
`quality`, `progress`, `resource`, and `procurement`. The package also contains
field-technology modules not re-exported from the top barrel: `drone.ts`
(flight-plan generation, photogrammetric point clouds, volumetric earthwork),
`ar-lidar.ts` (AR-glasses BIM overlay, LiDAR-to-BIM, as-built deviation), and
`drone-inference.ts` — a swappable YOLO / RT-DETR backend abstraction with a
deterministic `FixtureDroneInferenceBackend` for tests and an
`OnnxDroneInferenceBackend` that dynamic-imports `onnxruntime-node` for real
image inference.

### @cybele/core

The **domain-type foundation** (`libs/cybele/core/src`), titled "Ghana Real
Estate & Construction" in its header. `types.ts` defines branded ID types
(`PropertyId`, `PlotId`, `BuildingId`, `LeaseId`, `ContractorId`, `FundId`, …)
with factory functions plus the domain enums (`PropertyStatus`, `GhanaRegion`,
`LandTenure`, `ZoningClass`, `ValuationMethod`, …); `validators.ts` provides the
matching Zod schemas; and `guards.ts` and `serializers.ts` supply runtime type
guards and (de)serialization. It is the lowest-level shared vocabulary every
other Cybele library builds on.

### @cybele/db

The **persistence layer** (`libs/cybele/db/src` + `drizzle/`). `schema.ts`
defines the Drizzle/Postgres tables — property status/type enums, spatial
columns with explicit decimal precision/scale for coordinates, areas, and money
— and relations; `connection.ts` and `redis-config.ts` provide the DB/Redis
clients; `seed.ts` seeds reference data. The nine numbered SQL migrations under
`drizzle/` are real and domain-specific: initial schema, TimescaleDB IoT
hypertables, partitioning, PostGIS plot boundaries, building spatial hierarchy,
construction WBS, rent schedules, prefab design/orders/assembly, and competitor
developments.

### @cybele/design

The **architectural and engineering design engine** (`libs/cybele/design/src`).
The barrel exports `structural` (RC beam/column design per BS 8110 / Eurocode 2
with Ghana climate wind loads in `structural.ts`), `mep` (mechanical/electrical/
plumbing), `sustainability` (green-building scoring), `bim`, `drawings`, and
`design-intelligence`. The package also carries two modules beyond the barrel:
`digital-twin.ts` (a BIM-to-digital-twin pipeline with IoT binding and
predictive-maintenance analytics) and `generative.ts` (parametric generative
floor-plan/facade/massing design with constraint satisfaction tuned to Ghana's
climate and regulations).

### @cybele/finance

The **real-estate deal-finance engine** (`libs/cybele/finance/src`). Its core is
genuine financial math: `proforma.ts` implements `computeNPV`, a Newton-Raphson
`computeIRR` with bisection fallback (converging on `|NPV| < 1e-8`), plus
sensitivity and Monte-Carlo development modelling. Surrounding modules cover
`mortgage`, `reit` (NAV calculations reusing `computeIRR`), `crowdfunding`, and
`alternative-finance` (rent-to-own scheme design). This is the deal/instrument
layer — distinct from `@cybele/financials`, which models enterprise economics.

### @cybele/financials

The **enterprise/portfolio financial-modelling engine**
(`libs/cybele/financials/src`). Where `finance` prices individual deals, this
library models the development business: `proforma-models.ts` defines structured
`CostBreakdown` (land, acquisition, construction, contingency, professional
fees, permits, financing, marketing, legal) and `ReturnMetrics` (ROC, ROE,
equity multiple, IRR); `cost-models.ts` adds cost estimation; `synergies.ts`
models inter-company transfer pricing and business-unit synergies; and
`financials-extended.ts` extends the set. The barrel re-exports all four.

### @cybele/hospitality

The **hospitality / hotel-operations engine** (`libs/cybele/hospitality/src`).
`revenue.ts` computes standard hotel KPIs — ADR, RevPAR, occupancy, TRevPAR,
GOPPAR — normalising any input period to a per-night basis (`computeHotelKPIs`);
`operations.ts` handles operational management; and `hospitality-extended.ts`
adds further capability. All three are exported from the barrel; the package is
tagged `type:facilities`.

### @cybele/industrial-parks

The **industrial-park planning and operations engine**
(`libs/cybele/industrial-parks/src`). `planning.ts` models park zoning
(`ParkZone` with manufacturing/logistics/services/amenities/green-space/
substation/water-treatment types, building-coverage and power-allocation
constraints) and plot subdivision (`ParkPlot` with frontage/depth and lease
rates); `operations.ts` covers park operations and `warehouse.ts` covers
warehousing. The barrel exports planning, operations, and warehouse.

### @cybele/infrastructure

The **civil-infrastructure engineering engine**
(`libs/cybele/infrastructure/src`). `roads.ts` implements the AASHTO-1993
flexible-pavement design method — solving the structural-number equation
iteratively, with subgrade resilient modulus estimated from CBR
(`MR = 2555·CBR^0.64`) and drainage coefficients chosen for Ghana's tropical
climate. `civil-works.ts` covers earthworks/drainage and `procurement.ts` covers
infrastructure procurement. The barrel exports roads, civil-works, and
procurement.

### @cybele/integration

The **cross-domain bridge layer** (`libs/cybele/integration/src`). It defines
the typed contracts and bridge classes connecting Cybele to five sibling
domains: `brigid-bridges.ts` (industrial manufacturing — prefab factory
automation, SCADA, data-center power, predictive maintenance, with a stateful
`BrigidFactoryAutomationBridge`), `saraswati-bridges.ts` (creative authoring),
`asase-bridges.ts`, `freya-bridges.ts`, and `maat-bridges.ts` (governance/risk —
portfolio oversight, financial consolidation, compliance, enterprise risk). Each
bridge carries a `BridgeHealthCheck`/status model. The barrel re-exports all
five.

### @cybele/market-intel

The **market-intelligence and analytics engine**
(`libs/cybele/market-intel/src`). `pricing.ts` builds quarterly hedonic-style
price indices from `PropertyTransaction` records (median price-per-sqm by
district/type, base period = 100); `supply.ts` models supply/absorption;
`economic-indicators.ts` tracks Ghana macro drivers (construction costs,
interest rates, infrastructure investment, urbanization, FDI, housing demand)
into a unified macro dashboard; and `market-extended.ts` adds further analytics.
The barrel exports pricing, supply, market-extended, and economic-indicators.

### @cybele/materials

The **building-materials engine** (`libs/cybele/materials/src`), grounded in
Ghana standards. `concrete.ts` carries `GHANA_CONCRETE_MIXES` (C15/C20/…
mix-design proportions per cubic metre, per GS 298 / GS EN 206-1 with w/c ratios
and target strengths) plus block-test result types; `steel.ts`, `paint.ts`,
`tiles.ts`, and `furniture.ts` model their material classes, and
`cross-material.ts` handles cross-material concerns. The barrel exports all six.

### @cybele/prefab

The **prefabricated/modular-housing engine** (`libs/cybele/prefab/src`).
`affordability.ts` carries real Ghana regional housing-deficit data
(`GHANA_HOUSING_DEFICIT`, sourced to GSS 2021 PHC / UN-Habitat / GREDA, ~1.8M
national units) and computes affordability indices (price-to-income, DTI
mortgage test) and prefab development ROI/IRR. `modules.ts` defines the module
library, with `production`, `logistics`, and `assembly` covering manufacture and
on-site assembly. The barrel exports modules, production, affordability,
logistics, and assembly.

### @cybele/property

The **property and asset-management engine** (`libs/cybele/property/src`).
`valuation.ts` implements multiple RICS-style methods — comparative sales
(recency/proximity-weighted comparables), income capitalisation, DCF, cost
approach, reconciliation, and a simplified AVM; `lease.ts`, `tenant.ts`, and
`maintenance.ts` handle leasing, tenancy, and maintenance; `analytics.ts` adds
portfolio analytics. The package also includes `iot.ts` — an IoT smart-building
platform (occupancy sensing, HVAC/lighting optimization, leak/elevator/parking
management). The barrel exports lease, tenant, maintenance, valuation, and
analytics.

### @cybele/proptech

The **property-technology engine** (`libs/cybele/proptech/src`).
`blockchain-title.ts` implements an on-chain land-title registry with NFT
tokenization (ERC-721 / ERC-3643 T-REX), smart-contract leases, and
cryptographic transfer verification using `node:crypto` ECDH/sign primitives,
layered over a real `wallet.ts` (keccak256, EIP-191 digests, `recoverAddress`,
`verifyMessage`); its `TitleTenure` enum models Ghana-specific tenures
(Stool_Land, Family_Land, Vested). `listing.ts`/`listing-extended.ts`,
`crm.ts`/`crm-extended.ts`, `transactions.ts`, and `digital-experience.ts` cover
listings, lead CRM, transactions, and digital customer experience. The barrel
exports all of these.

### @cybele/site-analysis

The **site-selection and analysis engine** (`libs/cybele/site-analysis/src`),
the largest engine by file count. `selection.ts` runs multi-criteria decision
analysis (MCDA) with sensitivity and highest-and-best-use analysis per RICS,
composing `infrastructure`, `demographics`, `risk`, and `land-registry`
(zoning-compliance and land-dispute-risk scoring); `ai-selection.ts` adds
ML-style gradient-boosted site scoring, NLP search parsing, and price-
appreciation prediction. The package additionally carries real external-data
provider abstractions — `dem-provider`, `ndvi-provider`, `borehole-provider`,
`epa-monitoring-provider`, and `competitor-repository` — each with its own spec.
The barrel exports gis, demographics, infrastructure, risk, land-registry, and
selection.

### @cybele/testing

The **shared test-utility library** (`libs/cybele/testing/src`), tagged
`type:testing`. `fixtures.ts` provides typed fixture factories built on
`@cybele/core` branded-ID makers and domain enums (constructing `Property`,
`ResidentialProperty`, `GhanaAddress`, `GeoLocation`, `GeoPolygon`, etc.), and
`mocks.ts` supplies reusable mocks. The barrel re-exports both, giving the other
Cybele libraries a single import for domain-accurate test data.
