# Saraswati Domain - Features

> Advanced Technology Intelligence (`libs/saraswati/*`; Phase 60)

Saraswati owns advanced technology manufacturing and operations across 17
business units: EVs, batteries, solar, IoT, electronics, pharma, robotics,
drones, telecom, medical devices, fintech hardware, security systems, e-waste,
additive manufacturing, satellite communications, market intelligence, and
financial models. It is a library-and-gateway domain with no `apps/saraswati/*`
services: 24 libraries under `libs/saraswati/` carry the work — three foundation
libraries, 17 business-unit capability libraries, and four cross-business-unit
dashboard libraries — and the gateway composes the boundary for consumers.

The domain boundary is deliberate. Saraswati owns advanced technology _product
families_ and their manufacturing and operations; Brigid owns generic industrial
automation and factory/plant control; Cybele owns physical facilities, real
estate, and civil infrastructure; Oya owns drone flight primitives while
Saraswati owns drone _services_ as a business unit; Galatea owns humanoid
embodied AI while Saraswati owns robotics business units with broader industrial
and commercial scope.

These boundaries matter because each neighbor domain has deeply different
operational concerns. Mixing them would create a single brittle context that
cannot evolve independently. The formal integration contracts in
`@contracts/saraswati` are the only sanctioned crossing points.

## Domain Foundation

Three foundation libraries underpin every business unit. Rather than a single
universal product object, each business unit owns its own concrete entities
(`Vehicle`, `Battery`, `SolarPanel`, `IoTDevice`, `Robot`, `Drone`,
`TelecomTower`, and so on); the foundation supplies the shared types, branded
IDs, persistence, and gateway those entities all build on.

### Core types and branded IDs (`@saraswati/core`)

`@saraswati/core` is the shared type library: TypeScript interfaces, Zod
schemas, type guards, and factory functions for every business-unit entity,
organized into seven type modules (`vehicle`, `energy`, `iot`, `pharma`,
`robotics`, `telecom`, `manufacturing`). It also defines compile-time branded ID
types — `VehicleId`, `BatteryPackId`, `IoTDeviceId`, `DroneId`, `RobotId`,
`TelecomTowerId`, and the rest — so an ID of one kind cannot be passed where
another is expected. Each entity carries its own status enum tuned to its
lifecycle; there is no single cross-domain lifecycle. A vehicle, for example,
moves
`design → prototype → homologation → production → active_fleet → maintenance → end_of_life → decommissioned`,
while a battery pack tracks a separate `secondLifeStatus` (`in_vehicle`,
`second_life_stationary`, `awaiting_assessment`, `recycling`).

### Persistence (`@saraswati/db`)

`@saraswati/db` is the data layer: a Drizzle ORM schema over the `saraswati`
PostgreSQL database, with the PostGIS, TimescaleDB, and pgvector extensions.
Per-business-unit tables hold vehicles, battery cells/modules/packs, solar
panels and installations, IoT devices, PCB designs, pharmaceuticals and batch
records, robots, drones, telecom towers, medical devices, fintech terminals,
security systems, e-waste collections, printers, satellite terminals, and
market/financial records. Three TimescaleDB hypertables hold battery, solar, and
IoT telemetry; PostGIS geometry columns hold locations for charging stations,
vehicles, towers, IoT devices, solar installations, drones, and VSAT terminals.

### Gateway (`@saraswati/gateway`)

`@saraswati/gateway` is the boundary library: a Hono HTTP API mounting all 17
business units, plus GraphQL for cross-business-unit queries, gRPC service
definitions, an MQTT topic hierarchy, WebSocket/SSE streaming, a Kafka event-bus
abstraction, CQRS/event-sourcing primitives, and the shared middleware (JWT auth
and RBAC, per-business-unit rate limiting, Prometheus metrics, tracing,
structured logging, circuit breakers).

### Cross-cutting requirements

Four constraints apply across every business unit and are non-negotiable for
regulated categories. They exist to ensure that regulated decisions can always
be audited, telemetry can always be traced to its source, and financial
projections can always be re-derived from their original inputs.

1. **Evidence integrity** — every regulated-product decision must preserve the
   evidence packet, standard, jurisdiction, reviewer identity, and timestamp.
   Compliance evidence is append-only once a decision is recorded.
2. **Telemetry identity** — ingested telemetry must preserve the source device
   identity and a sequence number for ordering and deduplication, so a reading
   can always be traced to the device and message that produced it.
3. **Versioned configuration** — firmware and device-configuration changes must
   be versioned and auditable; every fielded unit's configuration history is
   reconstructable.
4. **Model assumption provenance** — financial projections must retain their
   input assumptions and model version, so any forecast can be re-derived.

## Electric Vehicles (`@saraswati/ev`)

Covers vehicle design, production, fleet operations, charging, and homologation.
EVs are one of Saraswati's two most compliance-heavy business units (along with
pharma) because type-approval standards differ by country and regional bloc.

### Vehicle designs and the EV lifecycle

A `Vehicle` carries its VIN, `vehicleType` (motorcycle, cargo/passenger/utility
tricycle, minibus, city/intercity bus, light/medium delivery van), `powertrain`
(motor, controller, transmission, drive-cycle efficiency), `chassis` (frame,
suspension, braking, aerodynamics), and its `batteryPackId` pairing to a
`@saraswati/battery` pack. Vehicle status moves
`design → prototype → homologation → production → active_fleet → maintenance → end_of_life → decommissioned`.
Vehicle designs are tracked separately and move through
`draft → in_review → approved → deprecated` at the gateway.

### Homologation and certification

`VehicleCertification` runs the vehicle through type-approval standards —
`HomologationStandard` covers DVLA-Ghana EV approval, UN-ECE R10/R100/R48/
R13-H/R78, the ECOWAS EV standard, IEC 61851, ISO 11451, and ISO 6469. Each
`CertificationRecord` carries a certifying body, issue and expiry dates, a
document reference, and a status (`valid`, `expired`, `pending`, `withdrawn`).
`VehicleCertification` also keeps a `recallHistory` of recall numbers,
descriptions, affected-vehicle counts, and remedy dates.

### Charging operations

`ChargingStation` records cover charger siting and energy delivery: connectors
(`ConnectorType` spans Type 1/2, CCS Combo 1/2, CHAdeMO, GB/T, NACS, and AC
plugs), station power, OCPP network configuration, V2G capability, demand
response, and live port availability. Station locations are stored as PostGIS
geometry. Charging telemetry (session energy, duration, faults) is ingested as a
device stream with source identity preserved.

### Fleet telemetry and maintenance

`FleetVehicle` extends `Vehicle` with a `fleetOperatorId`, driver assignments,
lifetime usage counters, and service scheduling. Vehicle telematics — GPS,
speed, state of charge, estimated range, odometer, charging state — are ingested
continuously and streamed on the `ev_telemetry` WebSocket channel and the
`saraswati.ev.telemetry` Kafka topic. Maintenance scheduling reads
telemetry-driven condition signals against next-service-due thresholds.

## Battery and Energy Storage (`@saraswati/battery`)

Covers cell-to-pack assembly, battery management, energy-storage deployment,
diagnostics, and second-life workflows. Batteries bridge the EV and energy
storage worlds: the same chemistry that powers a vehicle can, at end of its
first automotive life, be repurposed as stationary grid or telecom storage.

### Cells, modules, and packs

The battery hierarchy is three concrete entities: `BatteryCell` (chemistry, form
factor, electrical specs, cycle life, thermal-runaway thresholds, UN 38.3 and
IEC 62133 certification), `BatteryModule` (cell configuration, thermal
management, `BMSSpec`), and `BatteryPack` (module arrangement, cooling, safety
features, second-life state). `BatteryChemistry` spans LFP, NMC, NCA, LCO, LTO,
and sodium-ion. The battery management system (BMS) configuration is a
versioned, auditable artifact under requirement 3.

### Diagnostics and cycle-life tracking

Battery diagnostics ingest charge/discharge cycles, internal resistance, cell
balance, and temperature as telemetry — persisted to the
`saraswati_battery_telemetry` hypertable and streamed on the `battery_alerts`
WebSocket channel. State of health is tracked over the pack's service life;
below 80% is the end-of-life threshold. Safety events (thermal excursions, cell
faults) are recorded against the pack as fault codes.

### Second-life assessment and recycling handoff

When a pack's automotive state of health falls below its first-life threshold,
its `secondLifeStatus` moves to `awaiting_assessment` for evaluation as
stationary energy storage (`second_life_stationary`). A pack that reaches end of
life moves to `recycling` and hands off to the `@saraswati/ewaste` workflow with
its diagnostic history. `EnergyStorageSystem` records the resulting stationary
storage deployments — residential, commercial peak-shaving, telecom backup, grid
services, and off-grid community applications.

## Solar Manufacturing (`@saraswati/solar`)

Covers panel and inverter manufacturing, quality control, solar-home-system
(SHS) kits, and field deployment. Solar is the primary energy access technology
for off-grid rural electrification in the markets Saraswati serves.

### Products and quality control

`SolarPanel` records carry STC and NOCT electrical specs, temperature
coefficients, degradation rates, warranty terms, and certification flags (IEC
61215, IEC 61730, TÜV, Lighting Global). `SolarHomeSystem` packages a panel,
battery, charge controller, and optional inverter into a tiered SHS kit, with an
optional `PAYGOConfig` for pay-as-you-go financing. Manufacturing QA records
flash-test output, electroluminescence defects, and inverter functional tests.

### Site sizing and deployment

Field deployment covers site sizing (matching kit capacity to load), the
installation record, and the deployment location as a PostGIS geometry. Expected
panel output is computed from irradiance and ambient temperature with a NOCT
cell-temperature correction; generation forecasts retain their assumptions and
model version under requirement 4.

### Operations and rural energy programs

Operations and maintenance track installed-system performance via solar
performance telemetry, persisted to the `saraswati_solar_telemetry` hypertable
and streamed on the `solar_live` WebSocket channel. Solar deployments support
rural energy programs where SHS kits provide off-grid electrification; PAYGO
status and generation data feed the reporting that Maat consumes.

## IoT and Smart City Systems (`@saraswati/iot`)

Covers device management, smart-city systems, edge and cloud telemetry, and IoT
operations. IoT is Saraswati's highest-throughput business unit — a city
deployment may have thousands of devices streaming sensor readings every minute.

### Device registry and connectivity

An `IoTDevice` is registered with its identity (EUI-64 or UUID), `deviceType`
(air-quality, water/electricity meters, waste-bin and flood sensors,
street-light controllers, weather and structural monitors, gateways, edge
compute, and more), hardware and firmware versions, and a `ConnectivityProfile`.
The connectivity profile selects from LoRaWAN, NB-IoT, LTE-M, Sigfox, Zigbee,
Z-Wave, BLE, Wi-Fi, Ethernet, 4G/5G cellular, and satellite. Firmware updates
are versioned and auditable (requirement 3).

### Telemetry and sensor health

`SensorReading` records are ingested with a timestamp, device identity, sensor
type, value, and a `quality` flag (`good`, `uncertain`, `bad`, `sensor_error`,
`out_of_range`), plus a sequence number and uplink ID for ordering and
deduplication. Readings are persisted to the `saraswati_iot_telemetry`
hypertable and streamed on the `iot_stream` WebSocket channel. `AlertRule`
definitions raise alerts against a device when a field crosses a threshold.

### Smart city deployments

`SmartCityAsset` records group street lights, waste bins, meters, traffic
lights, parking and noise sensors, and flood gauges into city-scale deployments,
each optionally linked to an `IoTDevice` and tracked through `active`,
`inactive`, `fault`, `maintenance`, and `decommissioned` status.

## Electronics Manufacturing (`@saraswati/electronics`)

Covers contract electronics manufacturing — PCB assembly, surface-mount
technology (SMT), in-circuit and functional test, and box build. This business
unit provides manufacturing services for electronics components used across
Saraswati's own product lines and for third-party customers.

### PCB and SMT workflows

PCB design records and SMT line workflows track the assembly process from bare
board to populated assembly. ESD controls are recorded as part of line
operation. Box-build workflows cover final enclosure assembly and integration.

### Test, rework, and traceability

A `PCB` record carries its layer count, BOM (`BOMItem` lines with reference
designators, MPN, moisture-sensitivity level, RoHS compliance, and approved
alternates), test requirements, and `PcbTestResult` records. In-circuit test
(ICT), automated optical inspection (AOI), X-ray, and functional test (FCT)
results are recorded per unit; failing units route to rework. The
`ElectronicAssembly` record captures enclosure, cable harnesses, and box-build
assembly. Component sourcing and lot traceability link every assembly back to
its component lots, so a defective lot can be traced to every assembly that
consumed it.

## Pharmaceutical Manufacturing (`@saraswati/pharma`)

Covers GMP pharmaceutical manufacturing, quality control, formulations, and
regulatory workflows. Pharmaceuticals are among the most tightly regulated
categories in Saraswati: every batch must be traceable to its process
parameters, and every regulated decision must satisfy requirement 1 (evidence
integrity).

### Formulas, batches, and GMP documentation

A `Pharmaceutical` record carries its INN, dosage form, strength, route, ATC
code, API composition, and excipients. `BatchRecord` documents each
manufacturing batch — batch size, theoretical and actual yield, equipment used
(with OQ/PQ/DQ/IQ qualification), process parameters, and the qualified-person
sign-off. `GMPFacility` records clean rooms (ISO 14644 classification, EU GMP
Annex 1 grade) and qualified equipment.

### QC, stability, and deviations

QC test results are recorded per batch, and `Deviation` records (critical,
major, minor) trigger investigations. A batch is release-ready only when QC has
passed, the batch is in `qc_testing`, and every deviation is closed or minor.

### Regulatory records

Regulatory submissions are tracked as `RegulatorySubmission` records, each with
an authority, submission type, required documents, and a `status` spanning
`not_started`, `in_preparation`, `submitted`, `under_review`,
`additional_info_required`, `approved`, `rejected`, `withdrawn`, and `expired`.
A pharmaceutical's own `regulatoryStatus` follows the same approval progression.
All regulated decisions preserve evidence, standard, jurisdiction, reviewer, and
timestamp under requirement 1.

## Robotics (`@saraswati/robotics`)

Covers household, construction, and waste-sorting robotics as commercial and
industrial business units. The boundary with Galatea (humanoid embodied AI)
means Saraswati robotics focuses on task-specific machines with known operating
envelopes rather than general-purpose embodied intelligence.

### Robot product lines

A `Robot` record carries its `robotType` — household (cleaning, cooking assist,
eldercare), construction (rebar tying, bricklaying, plastering, surveying), and
waste-sorting (optical, magnetic, AI) — along with its actuators, sensors,
navigation mode, AI capabilities, and safety standard (ISO 10218 / ISO 15066).
Waste-sorting robots integrate with the `@saraswati/ewaste` workflow at recovery
facilities.

### Tasks, maintenance, and safety

`RobotTask` records capture each task — type, priority, parameters (work area,
waypoints, speed/force limits), completion percentage, quality score, and
safety-event count. The robotics gateway route enforces a single active task per
robot. Operations telemetry tracks robot state; maintenance is condition-driven,
and safety events are recorded against the unit. Saraswati owns the broader
industrial and commercial robotics scope; Galatea owns humanoid embodied AI.

## Drones (`@saraswati/drones`)

Covers drone services — inspection, delivery, spraying, and survey operations.
These are commercial service offerings built on top of the flight primitives
that Oya owns; Saraswati cares about the business-unit economics, mission
planning, and regulatory compliance, not the low-level flight control.

### Drone services as a business unit

Drone delivery, inspection, agricultural spraying, and survey are operated as
service offerings. Each mission carries its flight path and operating area as
PostGIS geometry. Saraswati owns drone services; Oya owns the underlying flight
and swarm-control primitives that Saraswati's drone operations build on.

### Drones, flight plans, and payloads

A `Drone` record carries its `droneType` (multirotor quad/hexa/octocopter,
fixed-wing, VTOL fixed-wing, single-rotor), GCAA registration, performance
specs, and compliance flags (Remote ID, UTM). `FlightPlan` records capture each
sortie — waypoints, operational area, airspace authorizations, geofencing, and
return-to-home parameters; a flight plan is rejected at the gateway when the
requested altitude exceeds the GCAA 400 m AGL cap. `DronePayload` records cover
cameras, LiDAR, agricultural sprayers, delivery boxes, and cargo hooks.
Drone-tracking telemetry streams on the `drone_tracking` WebSocket channel.

## Telecom Infrastructure (`@saraswati/telecom`)

Covers telecom infrastructure, fiber, towers, rural connectivity, and bandwidth
management. Telecom infrastructure is regulated in Ghana by the NCA, which means
tower siting, construction permits, and radiation compliance are all first-class
domain objects rather than free-form notes.

### Network assets

A `TelecomTower` record carries its `towerType` (monopole, guyed mast, lattice,
rooftop, camouflaged), structural spec, tenants, antennas, backhaul connections,
and power system; tower locations are stored as PostGIS geometry. The
`TowerSite` record covers land lease, access roads, and permits (NCA
construction permit, EPA clearance), with an optional environmental assessment
recording ICNIRP / Ghana EPA radiation compliance.

### Connectivity, bandwidth, and tenant capacity

Rural connectivity programs extend service to underserved areas. Tenant
provisioning is gated on the tower's remaining structural capacity
(`upliftAvailableKg`): the gateway rejects a new tenant whose equipment weight
exceeds it. Telecom is a regulated category — tower siting requires NCA and EPA
clearance before construction.

## Medical Devices and Health Tech (`@saraswati/medical`)

Covers medical-device and health-tech design, regulatory pathway, and
post-market surveillance. Medical devices span four risk classes, and the
regulatory pathway — FDA 510(k)/PMA, EU MDR, WHO prequalification, Ghana FDA —
differs by class and jurisdiction.

### Design history and risk classification

A `MedicalDevice` record carries its `deviceClass` (I, IIa, IIb, III),
classification codes, device-character flags (in-vitro diagnostic, implantable,
sterile, software safety class per IEC 62304), and a `regulatoryPathway` (FDA
510(k)/PMA/De Novo, EU MDR, WHO prequalification, Ghana FDA class I/II/III, ISO
13485). A device of class IIb or III requires a notified body; a class III or
surgically invasive device requires a clinical trial. `ClinicalEvaluation`
records the ISO 14971 risk analysis and benefit-risk conclusion.

### Post-market surveillance

Once deployed, devices are tracked through post-market surveillance: service
records, clinical and field feedback, and adverse-event signals, persisted as
post-market events. All regulated decisions preserve evidence, standard,
jurisdiction, reviewer, and timestamp under requirement 1.

## Fintech Hardware (`@saraswati/fintech-hw`)

Covers POS terminals, kiosks, ATMs, secure elements, PCI certification, key
injection, and payment hardware. Payment hardware interoperates with mobile
money networks and traditional card schemes, making PCI and EMV compliance
non-negotiable even in cash-first markets transitioning to digital payments.

### Payment hardware products

Fintech hardware is four concrete entities: `POSTerminal` (countertop, mobile,
PIN-pad), `ATM` (standalone, drive-through), `Kiosk` (banking, government,
telecom, retail), and `BiometricDevice` (fingerprint, face, iris, vein,
multi-modal). POS terminals and ATMs carry payment-method flags (chip,
magstripe, contactless, QR, mobile money) and EMV certification.

### PCI certification and merchant operations

PCI certification is tracked on the terminal itself — `pciPtsCertNumber` and
expiry, `pciDssCompliant`, EMV L1/L2, and (for ATMs) `pciHsmCertNumber`. Each
biometric device records its false-match, false-non-match, and failure-to-enroll
rates against ISO/IEC 19795. Deployed terminals carry usage counters;
payment-acceptance and merchant support are tracked per device.

## Security Systems (`@saraswati/security`)

Covers CCTV, access control, alarm systems, and AI security analytics. Security
systems are deployed as integrated products; the AI analytics layer processes
surveillance and access streams for event detection rather than simple threshold
alerting.

### Products and installation

A `SecuritySystem` record has a `systemType` (CCTV-only, access-control-only,
intrusion-only, or integrated) and aggregates `SecurityCamera` records (fixed,
PTZ, panoramic, fisheye, thermal), `AccessControlPoint` records (PIN, card,
fingerprint, face, iris, QR auth methods), and alarm zones. CCTV systems track
VMS/NVR, storage capacity, and retention.

### Monitoring, analytics, and alarms

AI security analytics process surveillance and access streams for event
detection. Alarm events are ingested at the gateway and surfaced as active
alarms, and stream on the `security_alarms` WebSocket channel. System status
moves through `active`, `inactive`, `maintenance`, and `alarm`.

## E-Waste and Circular Economy (`@saraswati/ewaste`)

Covers collection, sorting, refurbishing, parts and material recovery,
compliance, and resale and reuse channels. E-waste sits at the end-of-life
intersection of every other Saraswati category: batteries, robots, telecom
equipment, and electronics all flow into this business unit when retired.

### Collection and sorting

An `EWasteItem` record carries its item type, condition, `hazardClass`
(`non_hazardous` through `restricted_export` for Basel-Convention items), an
optional material-composition estimate, and a `processingRoute`
(`refurbishment`, `component_harvest`, `material_recovery`, `safe_disposal`).
E-waste is a regulated category; data-wiping certificates and chain-of-custody
fields are recorded against each item.

### Recovery and chain of custody

`RecoveredMaterial` records the output of recovery — material type, grade,
weight, purity, assay results, and value. Chain of custody is recorded end to
end, so every recovered item or material traces back to its intake; cross-border
movement of recovered material carries a Basel-Convention export permit. The
e-waste workflow is the end-of-life destination for batteries, robots, and other
Saraswati products that hand off at retirement.

## Additive Manufacturing (`@saraswati/additive`)

Covers additive manufacturing — prototyping, spare parts, construction printing,
and distributed production. On-demand additive production reduces the need for
large spare-parts inventories across Saraswati's installed base of equipment.

### Build jobs and parameters

A `PrintJob` record captures print parameters — material, layer height, infill,
shells, speeds, temperatures — sliced dimensions, quality requirements, and a
`status` (`queued`, `printing`, `paused`, `completed`, `failed`, `cancelled`).
`AdditiveManufacturingMaterial` records feedstock properties and stock levels.
Prototyping produces first builds; spare-parts production prints on-demand
replacement parts. Build QA verifies dimensional and material conformance.

### Construction printing and distributed production

Construction printing covers large-format additive for the built environment,
coordinated with Cybele's built-environment intelligence. Distributed production
runs builds across multiple sites, with each job tracking its print site and
parameters.

## Satellite Communications (`@saraswati/satellite`)

Covers VSAT, ground stations, satellite connectivity, and equipment operations.
Satellite connectivity provides service where terrestrial infrastructure is
absent, making it a critical input for rural IoT deployments and telecom
backhaul in underserved areas.

### Ground segment and connectivity

A `VSATTerminal` record carries its antenna type, frequency and modem fields,
service provider, contracted bandwidth, and installation geometry; terminal
locations are stored as PostGIS geometry. `GroundStation` records antennas,
processing capacity, network connections, and NCA certification. `Satellite`
records cover orbit type (LEO, MEO, GEO, HEO), coverage, frequency bands, and
capacity. Satellite connectivity links provide service where terrestrial
infrastructure is absent.

### Equipment operations

Equipment operations track terminal and ground-station status — uptime, signal
level, and last heartbeat — through `active`, `inactive`, `maintenance`, and
`fault` for terminals, and `operational`, `maintenance`, `offline` for ground
stations.

## Market Intelligence (`@saraswati/market-intel`)

Provides market intelligence across all business units. Market data informs
investment decisions, pricing, and competitive positioning; the confidence level
and projection CAGR fields ensure that projected figures are always
distinguishable from observed ones. `MarketDataPoint` records carry a metric, a
`metricCategory` (market size, market share, growth rate, price, demand,
competition, regulatory, technology), a geography and time period, a value, a
confidence level, and — for projected points — a CAGR and competitor fields. The
gateway exposes a Ghana EV-market reference dataset and competitor data. Market
models retain their inputs and assumptions.

## Financials (`@saraswati/financials`)

Provides financial models across all business units: business-unit financial
models and a portfolio roll-up. The financials gateway routes — every endpoint
gated to the `saraswati_manager` role — compute NPV and estimate IRR via a
Newton-Raphson approximation over a cash-flow series. Under requirement 4, every
projection retains its input assumptions and model version, so any financial
output can be re-derived. Financial views are consumed by Maat.

## APIs and Events

### API surface

The gateway (`@saraswati/gateway`) is a Hono application that mounts all 17
business units under `/api/v1/{bu}/` — `/ev`, `/battery`, `/solar`, `/iot`,
`/electronics`, `/pharma`, `/robotics`, `/drones`, `/telecom`, `/medical`,
`/fintech-hw`, `/security`, `/ewaste`, `/additive`, `/satellite`,
`/market-intel`, `/financials`. Each business unit follows the same shape: list
and fetch endpoints, validated create/update endpoints, telemetry ingestion, and
analytics. Alongside the REST routes the gateway exposes a GraphQL endpoint for
cross-business-unit dashboard queries, gRPC service definitions for real-time
robotics/drone/IoT/manufacturing control, an MQTT topic hierarchy, and
WebSocket/SSE channels. System endpoints cover `/health`, `/ready`, `/metrics`,
`/openapi.json`, and circuit-breaker health.

Access is governed by JWT auth and a six-level role hierarchy
(`saraswati_viewer` through `super_admin`); write routes require a minimum role
and scoped users are restricted to their permitted business units.

### Events

Saraswati's eventing has two real surfaces:

- **WebSocket / SSE channels** — eight channels carry live updates:
  `ev_telemetry`, `battery_alerts`, `solar_live`, `iot_stream`,
  `drone_tracking`, `manufacturing_events`, `security_alarms`, and
  `system_health`. A `PubSubBus` fans messages to subscribers; the SSE endpoint
  streams a channel as `text/event-stream`.
- **Kafka event-bus abstraction** — topics follow `saraswati.{bu}.{category}`,
  where `category` is `telemetry`, `commands`, `events`, `alerts`, or `audit`.
  Telemetry topics are high-partition for throughput; event topics are
  log-compacted for event sourcing; audit topics carry a one-year retention for
  compliance. A dead-letter topic catches messages that exhaust their retries.

A CQRS / event-sourcing layer separates command and query paths, appending
domain events to an event store and reconstituting aggregates by replay with
periodic snapshots.

### Persistence

The `saraswati` PostgreSQL database (with PostGIS, TimescaleDB, and pgvector)
holds per-business-unit tables for vehicles, batteries, solar, IoT, electronics,
pharma, robots, drones, telecom, medical devices, fintech hardware, security,
e-waste, additive, satellite, market intelligence, and financial models. Three
TimescaleDB hypertables hold battery, solar, and IoT telemetry with retention
policies and continuous aggregates. PostGIS geometry columns hold locations for
charging stations, vehicles, towers, IoT devices, solar installations, drones,
and VSAT terminals. pgvector embedding columns support PCB defect-detection
clustering, e-waste material classification, and IoT anomaly detection.

## Compliance and Regulatory

Saraswati treats compliance as a first-class, cross-cutting concern because
seven of its categories are regulated: pharma, medical devices, fintech
hardware, EVs, batteries, telecom, and e-waste. Each regulated business unit
carries its own compliance entity rather than a shared one, because the
compliance concepts differ fundamentally — a pharmaceutical batch record is
nothing like a PCI certificate or a tower NCA permit. The list below shows what
each regulated category owns:

- **EVs** — `VehicleCertification` and `CertificationRecord` track
  `HomologationStandard` type approvals (DVLA-Ghana, UN-ECE, ECOWAS, IEC, ISO)
  with certifying body, issue/expiry dates, and document references.
- **Pharma and medical** — `RegulatorySubmission` records track each submission
  to its authority through a nine-state approval lifecycle; a pharmaceutical's
  `regulatoryStatus` and a medical device's `regulatoryPathway` carry the
  device-specific pathway.
- **Fintech hardware** — PCI PTS/DSS/HSM and EMV certification fields are
  tracked on the terminal itself, with certificate numbers and expiry dates.
- **Telecom** — tower siting requires NCA construction permits and Ghana EPA
  clearance with ICNIRP radiation compliance.
- **Batteries and e-waste** — battery cells carry UN 38.3 and IEC 62133
  certification; e-waste `restricted_export` items and cross-border recovered
  material carry Basel-Convention export permits.
- **Evidence integrity** — every regulated decision preserves the evidence,
  standard, jurisdiction, reviewer identity, and timestamp; compliance evidence
  is append-only once recorded.
- **Verification expectations** — changes to regulated domains require contract,
  compliance, audit, and data-retention tests in addition to package-level lint,
  typecheck, and unit tests.

## Cross-Business-Unit Dashboards

Four cross-business-unit libraries aggregate views over the 17 capability
libraries. These libraries do not own business logic; they read from the
capability libraries and compose the aggregated views needed by operators and
managers who work across multiple business units simultaneously.

- **`@saraswati/command`** — the technology operations dashboard: KPI
  aggregation, manufacturing status, supply chain, quality, a financial
  dashboard, a regulatory tracker, and an alert center.
- **`@saraswati/fleet`** — vehicle and drone fleet management: a fleet overview,
  EV fleet health, drone mission control, charging infrastructure, a fleet
  scheduler, fleet analytics, and driver/pilot performance.
- **`@saraswati/factory`** — manufacturing management: an electronics MES, a
  pharma dashboard, battery assembly, solar manufacturing, the print farm,
  production planning, and a non-conformance-report manager.
- **`@saraswati/iot-platform`** — IoT platform device management: a device
  registry, device detail, smart-city operations, a rule engine, an OTA manager,
  and data export.

## EV Powertrain Engineering

`@saraswati/ev` carries powertrain engineering as a first-class capability.
Rather than treating a powertrain as a free-form text description, the domain
models motor types, FOC controller parameters, efficiency maps, regenerative
braking, gear ratios, and thermal limits as structured data. The
`PowertrainConfigurator` auto-configures a complete powertrain from vehicle
requirements — it selects a motor, sizes a controller, optimizes gear ratios,
and produces a `PowertrainConfig` with efficiency and thermal assumptions.
Configurations are versioned so a vehicle's powertrain assumptions can always be
re-derived.

## Cross-Domain Integrations

`@contracts/saraswati` defines five formal integration contracts, each a set of
Zod schemas plus an adapter class. These contracts exist because each
neighboring domain needs specific slices of Saraswati data rather than general
access to all 17 business units. The contract boundary keeps Saraswati's
internal model stable while giving each consumer a typed, versioned interface.

- **Brigid** — Saraswati manufacturing ↔ Brigid industrial automation: factory
  automation for electronics lines, energy-system integration, robotics
  integration, a shared MES event bus, and predictive-maintenance data sharing.
- **Asase** — Saraswati EV fleet / drones / IoT / solar ↔ Asase agriculture:
  delivery EV fleet integration, an agricultural drone connector, a
  soil/weather/crop IoT network, cold-chain monitoring, and solar-powered
  irrigation control.
- **Freya** — Saraswati ↔ Freya e-commerce: last-mile delivery fleet,
  smart-retail IoT, packaging electronics, fintech-hardware deployment for Freya
  POS/kiosks, and warehouse robotics.
- **Cybele** — Saraswati ↔ Cybele construction: construction robotics,
  smart-building IoT, EV-charging-infrastructure planning, rooftop/carport
  solar, data-center equipment provisioning, and construction drone survey.
- **Maat** — Saraswati R&D / IP / PLM ↔ Maat knowledge management: an R&D
  project tracker (TRL progression), an IP portfolio manager, PLM data sharing,
  technology scouting, and standards tracking.

Beyond these contracts, domain boundaries hold: Oya owns autonomous
aerial-system flight and swarm primitives that `@saraswati/drones` operations
build on, and Galatea owns humanoid embodied AI where `@saraswati/robotics`
extends into embodied systems.
