# Brigid — Systems Deep Dive

> The `apps/brigid/` area: five Nx projects that make up **Brigid, the Factory
> Intelligence / industrial-operations app domain** — an HTTP API surface plus
> four standalone domain-logic engines for energy, factory operations,
> maintenance, and industrial training.

## What this area is

Brigid is Oshun's industrial / smart-manufacturing domain. The `apps/brigid/`
directory holds five tracked Nx projects: one HTTP service (`@brigid/api`) and
four pure-logic library packages (`@brigid/energy-ms`, `@brigid/factory-os`,
`@brigid/maintenance-ms`, `@brigid/training-lms`). Every project carries the
`scope:brigid` Nx tag, builds with `tsc -p tsconfig.build.json`, and tests with
Vitest; each is independently versioned at `0.1.0` and exports its public
surface from `src/index.ts`. The source headers across the tree mark this as
"Phase 59.22.x" work.

These are not thin scaffolds. The four logic libraries are between ~2.5K and
~3.4K lines each (implementation plus tests), and the implementations are
genuinely domain-specific rather than generic CRUD: IEC 61724 solar Performance
Ratio with NOCT cell-temperature derating (`energy/src/solar-monitor.ts`), ISO
22400 OEE with MTBF/MTTR (`factory-os/src/production-monitor.ts`), ISO
10816/13373 vibration zoning plus z-score/IQR anomaly detection and
linear-regression RUL (`maintenance/src/predictive-maintenance.ts`), and a
ladder-logic PLC interpreter (XIC/XIO/OTE/OTL/TON/TOF) with a PID-driven SCADA
process simulator (`training/src/virtual-lab.ts`).

The notable structural point is that the four logic libraries are **siblings,
not dependencies of the API**. Each library declares `"dependencies": {}` in its
`package.json` and pulls in no other workspace package; the API in turn depends
only on `hono` and `zod` and re-implements its own route-level handlers and RBAC
types (for example its own `FactoryRole` in `api/src/middleware/auth.ts`) rather
than importing the engines. So the four engines are self-contained calculation
kernels, and `@brigid/api` is a parallel HTTP layer over the same domain
concepts — they share a vocabulary (equipment, telemetry, energy, maintenance,
training) without sharing code today.

## How it fits the wider system

Within the catalog, this app area is the runtime counterpart to the
`@contracts/brigid` package documented in the Contracts area — the wire-type
surface for the Brigid business domain. The API positions itself as a
cross-domain integration point: `api/src/routes/cross-domain.ts` accepts
equipment-provisioning and maintenance requests from other systems and emits
events such as `EQUIPMENT_PROVISION_REQUESTED` and
`CROSS_DOMAIN_MAINTENANCE_REQUEST` tagged with `sourceSystem: 'brigid-factory'`,
streaming them back over an SSE subscription endpoint.

The boundaries to keep in mind: all state in this area is **in-memory** (`Map`
and array stores in the API routes and inside the engine classes) — there is no
database or message-bus wiring in these projects, so they are computation and
HTTP-shaping layers, not persistence services. And the API's AI endpoints are
heuristic/simulated rather than real ML inference (see `@brigid/api` below),
which the source labels honestly. Consumers should treat the four engines as the
trustworthy domain math and the API as the request/response and RBAC envelope
around equivalent concepts.

## Entity reference

### @brigid/api

The Hono-based Factory Intelligence HTTP API (`apps/brigid/api`; app header
"@brigid/api — Hono-based Factory Intelligence API"). `src/app.ts` builds a Hono
app with secure-headers, CORS, logging, pretty-JSON, a 100-req/min IP
rate-limiter (`middleware/rate-limit.ts`), and optional JWT auth
(`middleware/auth.ts` `parseJWT` + `requireRole`), then mounts feature routers
under `/api/v1`: `equipment`, `telemetry`, `maintenance`, `energy`, `ai`,
`training`, and `cross-domain`, plus root-level `websocket` routes and `/health`
/ `/ready` probes. The routers are real REST handlers over in-memory `Map`
stores — e.g. `routes/equipment.ts` does paginated/filtered list, soft-delete,
asset-hierarchy tree-building, and bulk upsert with role guards. Honesty note:
`routes/ai.ts` is explicitly **simulated** — its `/ai/vision/inspect` handler is
commented "Simulated AI vision analysis" and returns a deterministic heuristic
finding with a `calculateVisionConfidence` score rather than running a vision
model; the prediction store is seeded with fixed sample assets. The HTTP
plumbing, RBAC, and CRUD are real; the AI "analysis" is a heuristic placeholder,
not inference. It depends only on `hono`, `@hono/node-server`,
`@hono/zod-openapi`, and `zod`, and does not import the four sibling engines.

### @brigid/energy-ms

The Energy Management System logic library (`apps/brigid/energy`), exported as
eight modules from `src/index.ts`. `architecture.ts` defines the energy RBAC
matrix (`ENERGY_ROLE_PERMISSIONS` for viewer/operator/manager), the WebSocket
event taxonomy (`SOLAR_UPDATE`, `BATTERY_SOC_UPDATE`, `GRID_STATUS`, …), and
per-source telemetry intervals. `solar-monitor.ts` is the strongest example of
the area's domain depth: a `SolarPVMonitor` implementing the NOCT cell-temp
model, a temperature-derating factor from the Pmax coefficient, IEC-61724
Performance Ratio with excellent/good/fair/poor classification, and shading-loss
detection — with comments calling out Ghana's typical 0.75–0.85 PR under high
temperature derating. The remaining modules (`battery-management.ts`,
`power-distribution.ts`, `energy-cost.ts`, `microgrid-control.ts`,
`energy-audit.ts`, `carbon-tracker.ts`) are comparably sized real
implementations, exercised by a 711-line `energy.test.ts`.

### @brigid/factory-os

The factory-operations OS logic library (`apps/brigid/factory-os`), nine modules
from `src/index.ts`. `production-monitor.ts` carries the `FactoryOSArchitecture`
RBAC engine (operator/supervisor/engineer/manager/viewer over
production/quality/maintenance/scheduling/alarms/reports/users) and a
`ProductionMonitor` computing ISO-22400 OEE as availability × performance ×
quality from recorded downtime and output, plus MTBF/MTTR from breakdown events.
`digital-twin.ts` implements a `DigitalTwinViewer`: a spatial asset model in mm
coordinates, live-telemetry sync that flips assets to `FAULT` when ≥50% of
sensors read out of range, min-max normalized heatmaps, and a
`virtualCommissioning` routine that estimates throughput, finds the
highest-utilization bottleneck, and detects XY bounding-box collisions between
assets. The other modules (`scada-overview.ts`, `scheduler.ts`,
`quality-management.ts`, `alarm-management.ts`, `shift-handover.ts`,
`kpi-dashboard.ts`, `batch-management.ts`) round out the shop-floor surface and
are covered by a 1,047-line `factory-os.test.ts`.

### @brigid/maintenance-ms

The maintenance (CMMS) logic library (`apps/brigid/maintenance`), eight modules
from `src/index.ts`. `architecture.ts` describes a mobile-first design with an
offline-sync config (last-write-wins / server-wins / client-wins strategies, an
IndexedDB store name) and a maintenance RBAC matrix
(technician/supervisor/planner/manager). `predictive-maintenance.ts` is the
analytical core: a `PredictiveMaintenanceEngine` with linear-degradation RUL
estimation (including a ±20% confidence interval), z-score anomaly detection
cross-validated against IQR outliers, ISO 10816/13373 vibration-velocity zoning
(A < 2.3 < B < 4.5 < C < 7.1 < D mm/s with prescribed actions), and a
least-squares health-trend slope classifying assets as stable/degrading/
improving. `work-order.ts` models the full WO lifecycle
(corrective/preventive/predictive/inspection, OPEN→IN_PROGRESS→…→COMPLETED with
planned-vs-actual variance); `asset-management.ts`, `spare-parts.ts`,
`maintenance-kpi.ts`, `remote-monitoring.ts`, and `mobile-api.ts` complete the
domain, with an 848-line `maintenance.test.ts`.

### @brigid/training-lms

The industrial-training Learning Management System logic library
(`apps/brigid/training`), eight modules from `src/index.ts`. `architecture.ts`
implements an xAPI / Tin Can statement model (actor/verb/object/result with the
standard ADL verb IRIs), an LMS data model (learner/enrollment/learningRecord),
LMS RBAC (learner/instructor/coordinator/manager), and statement build/validate
helpers. The standout is `virtual-lab.ts`: a `PLCSimulator` that executes
ladder-logic rungs instruction-by-instruction (XIC/XIO/OTE/OTL/OTU plus TON/TOF
timers with enable/done/timing bits) and a `SCADASimulator` that advances a
default five-tag process (reactor temperature, feed flow, tank level, pressure,
effluent pH) using per-tag PID controllers and a first-order time-constant
response model, scoring the trainee as alarms trip. `course-catalog.ts`,
`assessment.ts`, `certification.ts`, `learner-progress.ts`,
`instructor-management.ts`, and `corporate-training.ts` provide the surrounding
LMS features, with an 866-line `training-lms.test.ts`.
