# Brigid — Systems Deep Dive

> The `libs/brigid/` area: 24 Nx libraries implementing **Brigid**, the
> industrial-automation intelligence domain — deterministic engineering
> computation packages (PLC codegen, refrigeration loads, well-test analysis,
> calibration uncertainty, …) tuned for Ghana industrial operations.

## What this area is

Brigid (named for the Celtic goddess of the forge) is the industrial-automation
intelligence domain. The `libs/brigid/` directory is not one package but **24
separate Nx libraries** (`@brigid/*`, plus the data-layer `@brigid/db`), each
tagged `scope:brigid`. Most are `type:domain` engineering libraries;
`@brigid/db` is `type:data`. Per the area `README.md`, the domain spans 24
business units — factory automation, custom machine building, industrial AI,
energy, water/waste, HVAC/refrigeration, weighing, training, maintenance,
robotics, digital twin, OT cybersecurity, mining, oil & gas, supply chain,
packaging, agricultural mechanization, and materials production.

These are **pure-computation TypeScript libraries**, not running services. Each
file is a set of domain-specific engineering algorithms grounded in named
standards and references — for example `weighing/src/calibration.ts` implements
GUM uncertainty (ISO/IEC Guide 98-3) and ISO 17025, `factory/src/plc.ts`
generates IEC 61131-3 PLC code for Siemens/Allen-Bradley/Beckhoff,
`mining/src/process-automation.ts` uses Langefors burden, Kuz-Ram fragmentation
and Bond work index, and `oil-gas/src/upstream.ts` computes Vogel IPR/AOF and
Horner build-up analysis. The libraries are large and substantive (the smallest
is `@brigid/weighing` at ~2.8K LOC of source plus tests; `@brigid/ai-industrial`
is ~13K LOC), and each ships a sizeable co-located `*.test.ts` suite.

A recurring theme across the area is **Ghana localization**: solar irradiance
tables (`energy/src/solar.ts` `GHANA_MONTHLY_PSH`), GHS currency constants
(`financials/src/bu-models.ts` `GHS_PER_USD = 14.0`), ECOWAS/VAT/NHIL
import-duty math (`supply-chain/src/logistics.ts`), named offshore fields (TEN,
Jubilee, Sankofa in `@brigid/oil-gas`), and the 1D1F / AfCFTA policy trackers in
`@brigid/market-intel`.

### How the area is shaped

The libraries form a small internal dependency stack rather than 24 independent
silos:

- `@brigid/core` is the shared base — equipment/maintenance/energy/security
  types, unit conversions, Zod validators, and an industrial-standards reference
  registry (`core/src/standards.ts`).
- `@brigid/db` is the persistence layer — a Drizzle ORM schema for PostgreSQL
  with TimescaleDB hypertables and pgvector (`db/src/schema.ts`,
  `db/src/migrations.ts`).
- `@brigid/cross-domain` holds the integration adapters and Zod API contracts
  that let other Oshun domains (Asase, Freya, Cybele, Saraswati, Maat) call into
  Brigid.
- The remaining 21 libraries are per-business-unit engineering engines.

## How it fits the wider system

The Brigid libraries are consumed from a small number of edges. The
`apps/brigid/api` application (a Hono "Factory Intelligence API",
`apps/brigid/api/src/app.ts`) is the HTTP surface that exposes them. Two other
domains integrate inbound: `libs/athena/integration` and
`libs/annapurna/integration` both import `@brigid/*` packages. And
`@brigid/cross-domain` is the deliberate outbound seam — its `api-contracts.ts`
defines Zod request/response schemas (equipment provisioning, energy-system
integration) keyed by
`requestingDomain: 'asase' | 'freya' | 'cybele' | 'saraswati' | 'maat'`, so
cross-domain traffic is validated at the boundary. The matching wire-type
package `@contracts/brigid` (documented in the contracts area) owns Brigid's
REST/event contracts; the libraries here own the computation behind them. Walk
the "used by" edges on any node below to see exactly who depends on it.

## Entity reference

### @brigid/agricultural-mech

Agricultural-mechanization engineering for Ghana (Phase 59.14), barrel at
`agricultural-mech/src/index.ts`. Four modules: `irrigation.ts` (irrigation &
water management), `post-harvest.ts` (post-harvest handling, the largest at
~1018 LOC), `greenhouse.ts` (controlled-environment automation), and
`livestock-aquaculture.ts`. Fully implemented with a ~1218-LOC test suite.

### @brigid/ai-industrial

The largest library in the area (~13K LOC), industrial AI under Phase
59.5/59.22/59.23. Modules include `computer-vision.ts` (CNN defect detection,
sub-pixel dimensional measurement, Delta-E color inspection via CIE76/CIEDE2000,
GR&R measurement-system analysis), `predictive-maint.ts` (bearing fault
frequencies BPFO/BPFI/BSF/FTF, MCSA, RUL via Wiener/Paris/Weibull, Mahalanobis
anomaly scoring), `process-optim.ts`, `robotics-ai.ts`, `edge-ai.ts`, and
`sota.ts`. `api-types.ts` defines application-architecture interfaces for
FactoryOS, EnergyMgmt, MaintenanceMgmt, TrainingAcademy and the BrigidAPI
routes. Honest note: some computer-vision/SOTA elements are documented
approximations (the source itself labels an "autoencoder simulation" and
"isolation forest concept") where a full trained ML runtime would otherwise be
required — the surrounding metrology and signal-processing math is real.

### @brigid/core

The shared base every other Brigid library builds on (`core/src/index.ts`
barrels eleven modules). It owns industrial type taxonomies (`equipment.ts`,
`maintenance.ts`, `energy.ts`, `robotics.ts`, `security.ts`, `business.ts`), an
SI unit-conversion module (`units.ts`), runtime Zod validators (`validators.ts`,
`schemas.ts` — e.g. `EquipmentLevelSchema`, `ISODateStringSchema`), and a
curated industrial-standards registry (`standards.ts`:
IEC/ISO/ANSI/NFPA/API/ASME entries plus Ghana EPA / Energy Commission / Minerals
Commission / GSA references, each with `keyRequirements` and `ghanaRelevance`).
Tagged `type:domain`.

### @brigid/cross-domain

Brigid's outbound integration layer (`cross-domain/src/index.ts`). Provides
adapter classes per partner domain — `asase-integration.ts` (food processing,
cold chain, HACCP/CIP), `freya-integration.ts` (textile/cosmetics/garment
lines), `cybele-integration.ts` (prefab housing, building materials, data-center
power), `saraswati-integration.ts`, and `maat-integration.ts` (factory
telemetry, OEE, equipment-utilization analytics) — plus `api-contracts.ts`, the
Zod request/response schemas (`BrigidEquipmentProvisioningRequestSchema`,
`BrigidEnergyIntegrationRequestSchema`) that gate cross-domain calls. Tagged
`type:domain`.

### @brigid/cybersecurity

OT/ICS cybersecurity (Phase 59.10, ~10.5K LOC) implementing IEC 62443. Four
modules with explicit named exports in `cybersecurity/src/index.ts`:
`assessment.ts` (zone-and-conduit modeling, Purdue levels, foundational-
requirement scoring, the `ALARP_RISK_MATRIX`, vulnerability scanning, asset
inventory), `network-security.ts` (Purdue segmentation, firewall ACL/DMZ/data-
diode design, remote-access design), `threat-detection.ts` (industrial IDS over
Modbus/DNP3/S7Comm/OPC-UA packets, CUSUM anomaly detection, MITRE ICS ATT&CK
mapping, SIEM-for-OT correlation), and `access-control.ts` (OT RBAC, patch
management, change tracking, backup verification, pen-test methodology).

### @brigid/db

The Brigid persistence layer, `type:data` (`db/src/index.ts`). `schema.ts`
(~1033 LOC) is a Drizzle ORM schema for PostgreSQL using `pgTable`/`pgEnum`
(`brigidEquipmentStatus`, `brigidEquipmentLevel`, …) with money columns at
numeric(12,2). `migrations.ts` carries post-migration SQL for TimescaleDB
hypertable conversion of `brigid_sensor_telemetry` (1-day chunks) and pgvector,
keyed off `BRIGID_DATABASE_URL`. `seed.ts` provides seed data. A small
`schema.test.ts` accompanies it.

### @brigid/digital-twin

Industrial digital twin / virtual commissioning (Phase 59.9,
`digital-twin/src/index.ts`). Modules: `factory-twin.ts` (ISA-95 hierarchy
nodes, real-time sensor binding, flow visualization, energy-allocation tree,
historical playback), `equipment-twin.ts`, `process-simulation.ts`, and
`virtual-commissioning.ts` (the largest at ~975 LOC, operator-training support).
Fully implemented with a ~1753-LOC test.

### @brigid/energy

Energy solutions, Ghana-optimized (Phase 59.6, `energy/src/index.ts`).
`solar.ts` implements PV design from real Ghana irradiance data
(`GHANA_MONTHLY_PSH`, harmattan dust-soiling rates), Hay-Davies plane-of-array
irradiance, and PR-methodology yield. Companions: `bess.ts` (battery storage),
`grid-hybrid.ts` (grid-tie / diesel hybrid), `power-quality.ts`, and
`ghana-energy.ts` (ECG grid context, ~1027 LOC).

### @brigid/factory

Factory automation (Phase 59.3, `factory/src/index.ts`). Seven modules:
`production.ts`, `plc.ts` (IEC 61131-3 program generation for Siemens
S7-1200/1500, Allen-Bradley ControlLogix, Beckhoff TwinCAT, with a typed
`PLCDataType`/`PLCVendor` model and a PLC simulator), `scada.ts`,
`communications.ts`, `motion.ts`, `safety.ts`, and `batch.ts`. Each is a
substantial codegen/engineering module (scada ~1300 LOC, plc ~1173 LOC).

### @brigid/financials

Financial models for all 24 business units (Phase 59.20,
`financials/src/index.ts`). `bu-models.ts` (~1358 LOC) defines ~36 named
BU-specific revenue/cost/EBITDA model classes
(`FactoryAutomationFinancialModel`, `EnergyFinancialModel`,
`MiningFinancialModel`, …) computing margins in GHS via a shared `buildResult`
helper and `GHS_PER_USD`/`GHS_PER_EUR` constants. `portfolio-analysis.ts` does
portfolio-level analysis; `pricing-costing.ts` does project pricing/costing.

### @brigid/hvac

Refrigeration, cold-chain & HVAC engineering (Phase 59.16, version 1.0.0,
`hvac/src/index.ts`). `refrigeration.ts` implements cold-room heat-load
calculation, blast-freezer design via Plank's equation, a `REFRIGERANT_DATABASE`
with GWP/Kigali/safety classification, compressor and evaporator (LMTD) sizing.
`hvac-design.ts` (load calc, chillers, AHUs, ductwork), `energy-compliance.ts`
(Kigali/F-gas), and `pharma-cold-storage.ts` (GDP-compliant) round it out, with
Ghana 35-38°C ambient context throughout.

### @brigid/machines

Custom machine-building intelligence (Phase 59.4, `machines/src/index.ts`).
`design-workflow.ts` (~1512 LOC) implements a phase-gate process (concept →
commissioning), FDS generation, ECO impact analysis, and CPM Gantt scheduling.
`mechanical.ts`, `electrical.ts`, `bom-assembly.ts`, and `compliance.ts` cover
the engineering disciplines and CE/standards compliance.

### @brigid/maintenance

Predictive / condition-based maintenance (Phase 59.7,
`maintenance/src/index.ts`). `condition-monitoring.ts` implements weighted
multi-parameter health scoring, the Weibull reliability function
R(t)=exp(-(t/η)^β), MTTF via the gamma function, and a multi-level alert engine
with hysteresis. `cmms.ts` (work orders, PM scheduling, asset hierarchy),
`spare-parts.ts` (EOQ, safety stock, criticality), `kpi-analytics.ts`
(MTBF/MTTR, downtime Pareto), and `remote-iot.ts` (IoT ingestion, SLA, warranty,
AR guidance) complete it.

### @brigid/market-intel

Ghana industrial-automation market intelligence (Phase 59.19,
`market-intel/src/index.ts`). `market-analysis.ts` provides
`GhanaManufacturingAnalyzer` (sector sizing/TAM, automation-adoption scoring),
`CompetitorTracker` (win/loss, Porter's Five Forces),
`TechnologyAdoptionTracker` (Rogers' S-curve diffusion, TRL), and
`GovernmentPolicyTracker` (1D1F, AfCFTA, local content) backed by real constants
(`SECTOR_PROFILES`, `KNOWN_COMPETITORS`). `sector-demand.ts` and
`business-dev.ts` (lead scoring, proposals, tenders) add demand and BD
analytics.

### @brigid/materials

Industrial-materials production (Phase 59.18, `materials/src/index.ts`). Three
modules: `welding-consumables.ts` (AWS/ISO electrode classification —
E6010/E7018/E316L etc., IIW flux basicity index, coating extrusion, baking
profiles, carbon-equivalent QA), `industrial-gases.ts` (nitrogen/oxygen/argon/
acetylene production), and `plastics-recycling.ts` (collection, processing,
compounding).

### @brigid/mining

Mining-automation intelligence for Ghana operations (Phase 59.11,
`mining/src/index.ts`). `process-automation.ts` implements expert mining-process
math — Langefors burden/spacing, Kuz-Ram fragmentation, Bond work index and CSS
product sizing, Hogg & Fuerstenau SAG mill power, flotation recovery kinetics,
and CIL/heap-leach kinetics with cyanide/pH control. `fleet-logistics.ts`
(haulage/shovel allocation, grade control) and `safety-environment.ts` (gas
detection, tailings, ventilation, ~1386 LOC) complete it.

### @brigid/oil-gas

Oil & gas process automation across upstream/midstream/downstream (Phase 59.12,
`oil-gas/src/index.ts`), targeting Ghana's TEN, Jubilee and Sankofa fields plus
GNGC/Atuabo/Tema infrastructure. `upstream.ts` (~1577 LOC) implements Vogel IPR
and AOF (`calculateVogelIPR`/`calculateVogelAOF`), Horner build-up analysis,
wellhead ESD logic (`WELLHEAD_ESD_MATRIX`), and production allocation.
`midstream.ts` (pipeline SCADA, leak detection, custody transfer, compressor/
pump stations), `downstream.ts`, and `safety-compliance.ts` (API 14C /
ISO 13703) follow.

### @brigid/packaging

Packaging automation (Phase 59.13, `packaging/src/index.ts`).
`primary-packaging.ts` covers form-fill-seal (VFFS/HFFS) configuration,
Torricelli/Bernoulli orifice nozzle-flow for liquid filling, bottling-line
balancing, and SEMI-E10 / Nakajima OEE. `secondary-packaging.ts`,
`inspection.ts`, `line-optimization.ts`, and `packaging-materials.ts` complete
the line, with West African film-material constants.

### @brigid/robotics

Collaborative and warehouse robotics (Phase 59.8, `robotics/src/index.ts`).
`cobot.ts` implements use-case scoring, ROI (NPV/IRR/payback with Ghana labor
costs), ISO/TS 15066 power-and-force-limit contact thresholds per body region,
and speed-and-separation-monitoring distances. `robot-programming.ts`,
`agv-warehouse.ts` (AGV/AMR fleet, WMS), and `robot-safety.ts` (~1676 LOC,
human-robot interaction) round it out.

### @brigid/sota-enhancements

State-of-the-art enhancements (Phase 59.23, `sota-enhancements/src/index.ts`):
`human-centric.ts` (Industry 5.0, RULA ergonomics), `edge-ai.ts` (TinyML,
multi-sensor Kalman fusion), `5g-remote-ops.ts`, `ar-vr.ts`, `generative-ai.ts`,
`reinforcement-learning.ts`, `federated-learning.ts`, and
`digital-thread-quantum.ts`. Honest note: several of these are real but
simplified algorithms — e.g. `reinforcement-learning.ts` is a genuine tabular
Q-learning controller (`RLProcessController` with a 4000-cell `qTable`, learning
rate 0.1, γ 0.95) rather than a deep-RL runtime, and the generative/quantum
modules are conceptual/heuristic implementations, not wrappers over external
SOTA models. The digital-thread module does real SHA-256 hash chaining.

### @brigid/supply-chain

Supply-chain optimization (Phase 59.25, `supply-chain/src/index.ts`).
`planning.ts` implements Holt-Winters demand forecasting, MRP lot-sizing,
ABC/XYZ classification, Clark-Scarf multi-echelon optimization, supplier
scorecards, and S&OP orchestration, with statistical helpers
(`inverseNormalCDF`/`normalCDF`). `logistics.ts` adds nearest-neighbor route
optimization, a Ghana `ImportDutyCalculator` (ECOWAS levy, VAT, NHIL, GET Fund),
warehouse slotting/S-shape pick paths, and a P×I risk heat map.

### @brigid/training

Technical Training Academy (Phase 59.17, version 1.0.0,
`training/src/index.ts`). `curriculum.ts` (~2095 LOC) implements
Bloom's-taxonomy detection (`BLOOM_VERBS`, `detectBloomLevel`), credit-hour
calculation, prerequisite-graph validation, and named curricula (PLC, robotics,
electrical, instrumentation with calibration-uncertainty, energy, water,
cybersecurity). `assessment.ts` covers Rasch-IRT competency assessment and Ghana
NVQ certification; `delivery.ts` adds ROI calculation, spaced repetition, and
apprenticeship tracking.

### @brigid/water

Water & waste-treatment plant design, control and compliance (Phase 59.15,
`water/src/index.ts`). `water-treatment.ts` implements coagulation/flocculation/
sedimentation, Carman-Kozeny filter head-loss with backwash logic, CT-concept
chlorination/UV disinfection, UF/MF/NF/RO membrane flux and salt rejection, and
Hazen-Williams distribution hydraulics. `wastewater.ts` and
`industrial-effluent.ts` (~1485 LOC, Ghana EPA compliance) complete it.

### @brigid/weighing

Weighing and calibration metrology (Phase 59.24, version 1.0.0,
`weighing/src/index.ts`). `weighing-systems.ts` designs weighbridges, batch
weighing, checkweighers, tank weighing and belt weighers per OIML R 76/R 50/R 51
classes. `calibration.ts` (~1055 LOC) implements ISO 17025 calibration
management (`CalibrationManagementSystem` with current/due/overdue status), GUM
measurement-uncertainty budgets (`MeasurementUncertaintyCalculator`, ISO/IEC
Guide 98-3, distribution divisors for rectangular/triangular/U-shaped),
procedure libraries, certificate generation, and drift analysis.
