# Brigid Domain - Features

> Industrial Automation Intelligence (`libs/brigid/*`, `apps/brigid/*`; TODO
> Phase 59)

Brigid is the Oshun bounded context for factory automation, industrial
operations, energy systems, maintenance intelligence, machine building, OT
cybersecurity, and industrial market operations. It is an implemented workspace
domain with 24 library packages and five application services.

Every industrial capability shares one foundation: the equipment, maintenance,
energy, robotics, security, and business type system in `@brigid/core`, and the
persistence schema in `@brigid/db`. This shared foundation means a maintenance
record, a factory sensor stream, and an energy audit all reference the same
equipment identity and obey the same validation rules — engineers working on any
vertical start from familiar ground.

Safety-critical and OT control workflows carry stricter rules than the rest of
the domain: deterministic fallback states, recorded operator overrides, and
immutable post-signoff records. Those rules are stated in the subsystems that
own them and summarized in §19.

---

## 1. Domain Foundation

**Packages:** `@brigid/core`, `@brigid/db`, `@brigid/cross-domain`,
`@brigid/sota-enhancements`

The foundation layer establishes the contracts every other Brigid library
depends on, so that a maintenance record, a factory sensor stream, and an energy
system all reference the same equipment identity and obey the same validation
rules.

- **Identifiers** — `@brigid/core` identifies entities with plain `string`
  fields (`equipmentId`, `sensorId`, `workOrderId`, and so on); there are no
  branded or opaque ID types. The `@brigid/db` registry tables enforce a unique
  business identifier alongside each surrogate UUID primary key.
- **Validation schemas** — `@brigid/core` ships Zod schemas (`schemas.ts`) that
  reject malformed payloads at ingestion. A `Sensor` whose `tag` breaks the
  ISA-5.1 instrument-tag pattern, an `OEEMetrics` record whose `oee` is not
  `availability × performance × quality`, or a `CalibrationRecord` with fewer
  than three measurement points is refused; validation errors are surfaced, not
  swallowed.
- **Asset hierarchy** — the ISA-95 `EquipmentLevel` ladder runs `enterprise`,
  `site`, `area`, `production_line`, `work_cell`, `equipment_unit`,
  `control_module`. Sites contain factories and production areas; lines contain
  work cells and equipment. The hierarchy is the addressing scheme for
  telemetry, alarms, and maintenance.
- **Persistence** — `@brigid/db` owns a Drizzle ORM schema and migrations for
  the facility hierarchy, equipment, sensors/actuators/PLCs, work orders, spare
  parts, energy systems, robots, digital twins, security assessments, training
  programs, calibration records, and materials batches. It separates relational
  records (PostgreSQL) from high-volume telemetry (TimescaleDB hypertables) so
  sensor ingestion does not contend with transactional writes.
- **Cross-domain adapter** — `@brigid/cross-domain` is the only sanctioned exit
  point. It maps Brigid DTOs into consumer-facing contracts for Asase, Freya,
  Cybele, Saraswati, and Maat, preventing those domains from importing Brigid
  internals directly and decoupling Brigid's internal model from external
  consumers.
- **SOTA enhancements** — `@brigid/sota-enhancements` carries Phase 59.23
  state-of-the-art enhancements across eight modules: human-centric automation,
  edge AI, 5G remote operations, AR/VR, generative AI, reinforcement learning,
  federated learning, and digital thread / quantum. It depends on the same
  foundation contracts so enhancements do not fork the type system.

---

## 2. Core Industrial Type System

`@brigid/core` defines the canonical objects shared across every vertical, in
ten modules (`equipment`, `maintenance`, `energy`, `robotics`, `security`,
`business`, `units`, `validators`, `standards`, `schemas`). Treating these as a
fixed vocabulary keeps factory, energy, maintenance, and OT code interoperable.
The type system is aligned to ISA-95, IEC 61131-3, ISO 12100, IEC 61511, IEC
62443, ISA-18.2, and ISA-101.

### 2.1 Equipment and Machine

`Equipment` is the base plant-asset record. Every asset carries an
`equipmentId`, an ISA-95 `level`, an `equipmentClass`, a `location`, make and
model details, and an OEE record.

- **`status`** — `running`, `idle`, `maintenance`, `fault`, or `decommissioned`.
- **`Machine` extends `Equipment`** — the machine record adds a `category` (a
  20-value `MachineCategory` union: `cnc_machining`, `injection_moulding`,
  `welding`, `robot_cell`, `agv`, and so on), physical dimensions, an electrical
  spec, a capacity spec, interfaces, and an optional functional safety category
  (`Cat_B`..`Cat_4`) and performance level (`PLa`..`PLe`).
- **`OEEMetrics`** — Overall Equipment Effectiveness, with `availability`,
  `performance`, `quality`, the six big losses, and an enforced invariant: `oee`
  must equal `availability × performance × quality` within 0.001.
- Functional safety is carried by dedicated `@brigid/core` types
  (`SafetySystem`, `SafetyInstrumentedFunction`) with SIL ratings, fail-safe
  actions, and bypass procedures — these force deterministic fallback states and
  mandatory audit recording (see §19).

### 2.2 Sensor and Telemetry

`Sensor` is a process-instrument record bound to one piece of equipment.

- Carries `sensorId`, an ISA-5.1 instrument `tag` (e.g. `TT-101`), a `quantity`
  (one of 24 physical quantities — `temperature`, `pressure`, `vibration`, and
  so on), engineering range, `outputType`, accuracy, alarm setpoints, and an
  optional calibration block.
- **Telemetry storage** — sensor readings persist in the
  `brigid_sensor_telemetry` hypertable, each carrying `value`, `unit`, a
  `quality` flag (`good`, `bad`, or `uncertain`), `rawValue`, and `source`.
- **Data quality** — `@brigid/core`'s `validators.ts` flags out-of-range,
  fast-changing, stuck, and spike readings (`good`/`suspect`/`bad`) rather than
  silently dropping them. Ingestion also tolerates out-of-order arrival — a
  reading with an older timestamp than already-stored data is inserted in time
  order, not rejected (see §19).

### 2.3 MaintenanceRecord

`MaintenanceRecord` is the work-order object — the unit of maintenance and
service action against equipment.

- **`maintenanceType`** — one of eight: `corrective`, `preventive_scheduled`,
  `preventive_condition_based`, `predictive`, `improvement`, `inspection`,
  `overhaul`, `statutory`.
- **`priority`** — `emergency`, `urgent`, `high`, `medium`, `low`, or
  `scheduled`.
- **`status` lifecycle** — `WorkOrderStatus` is a 13-state enum running
  `draft → submitted → approved → parts_ordered → scheduled → assigned → in_progress → (pending_parts | pending_approval) → completed → verified → closed`,
  with `cancelled` reachable as a terminal state. The persisted
  `brigid_work_order_status` enum is the same set minus `pending_approval`.
- The record captures labor entries, materials used, GHS cost rollups, failure
  information, and a post-maintenance check (functional test, operator sign-off,
  root-cause analysis).
- **`CalibrationRecord`** is the separate ISO/IEC 17025 calibration object; a
  completed calibration record is immutable after signoff except through
  append-only correction events (see §19).

---

## 3. Factory Automation and Design

**Package:** `@brigid/factory` · **Application:** `apps/brigid/factory-os`

The factory package covers the full lifecycle of a production line: from initial
design and balancing through control-system integration, live operation, and
operator workflows. The companion `factory-os` application surfaces this
capability as a real-time operating environment for plant engineers and
operators.

### 3.1 Line Design and Balancing

- **Production-line design** — model a line as an ordered sequence of stations,
  each with cycle time, equipment, buffer capacity, and operator assignment.
- **Station balancing** — distribute work content across stations to minimize
  the gap between the bottleneck station's cycle time and the line's takt time;
  flag stations whose cycle time exceeds takt as throughput constraints.
- **Layout** — equipment placement and material-flow routing for a facility,
  including footprint, clearances, and utility connection points.
- **Throughput and OEE modeling** — compute Overall Equipment Effectiveness as
  `availability × performance × quality`, projecting line output under planned
  shift patterns and comparing modeled against actual.

### 3.2 Control-System Integration

Brigid models the full plant-floor control stack — PLCs, SCADA, and HMI — so
that hardware signals become first-class Brigid entities.

- **PLC / SCADA / MES integration** — `@brigid/core` models `PLC`,
  `SCADASystem`, `SCADAPoint`, and `HMITerminal` types, and `@brigid/factory`
  ships `plc`, `scada`, and `communications` modules that map
  programmable-controller tags and supervisory-control points onto Brigid
  equipment, so plant-floor signals become sensor telemetry and machine state.
- **Recipes** — parameterized production recipes (setpoints, tolerances,
  sequence steps) versioned per product so a line can be reconfigured between
  runs with a known, auditable parameter set.
- **Alarms** — alarm definitions with thresholds and severity. SCADA alarm
  transitions are modeled by the ISA-18.2 `AlarmState` machine
  (`NORM`/`UNACK`/`ACKED`/`RTNUN`/`SHELVED`/`SUPPRESSED`/`INHIBITED`) with a
  four-level `AlarmPriority`; an active alarm surfaces over the factory
  WebSocket as an `ALARM_ACTIVE` message (see §17).

### 3.3 Production States and Commissioning

- **Production states** — a `ProductionLine` moves through `running`,
  `scheduled_downtime`, `unplanned_downtime`, `changeover`, and `idle`;
  transitions feed OEE and downtime analysis.
- **Commissioning** — structured bring-up of a new or modified line: integration
  checks, dry runs, ramp-up, and signoff. Equipment records carry an
  `installDate` and an optional `commissionDate`, and a commissioned asset's
  `status` becomes `running`.
- **Operator workflows** — guided start-up, changeover, and shutdown procedures
  surfaced through `factory-os`, with each step recorded against the shift.

---

## 4. Machine Building

**Package:** `@brigid/machines`

This package handles custom industrial machinery from design handoff through
delivery, installation, and in-service maintenance. It enforces a formal
phase-gate process so that design quality is checked at each stage before work
proceeds.

- **Machine lifecycle** — `@brigid/machines` defines a phase-gate
  `MachineDesignPhase` workflow: `concept`, `detail_design`, `procurement`,
  `assembly`, `testing`, `commissioning`. Each gate carries a `GateDecision`
  (`pass`/`conditional_pass`/`hold`/`kill`) and each stage gates the next.
- **CAD/CAM handoff** — mechanical and electrical design records and CAD files
  are stored in object storage and linked to the machine, so the as-built design
  travels with the asset throughout its service life.
- **Design records** — mechanical assemblies, electrical schematics, and control
  panel layouts captured as structured records, not just file attachments, so
  components are individually addressable.
- **FAT and SAT** — Factory Acceptance Test (at the builder) and Site Acceptance
  Test (at the customer site) are checklist-driven gates; a failed item blocks
  progression and is tracked to resolution. Passing acceptance moves the machine
  into in-service operation.
- **Installation and commissioning intelligence** — installation sequencing,
  utility hookup, and commissioning checks, reusing the §3.3 commissioning
  pattern.
- **Maintenance and spare parts** — each machine carries a bill of maintainable
  components and a recommended spare-parts list, feeding `@brigid/maintenance`.

---

## 5. Industrial AI

**Package:** `@brigid/ai-industrial`

This package applies machine learning to plant data to detect defects, predict
failures, and optimize processes. Models consume validated telemetry from
`@brigid/db` and emit predictions, recommendations, and maintenance signals back
into the maintenance and factory workflows.

- **Computer-vision inspection** — image-based defect detection on production
  output: surface defects, dimensional deviation, assembly completeness. Each
  inspection yields a pass/fail verdict with a confidence score and the
  contributing defect classes.
- **Anomaly detection** — unsupervised detection of abnormal machine behavior
  from telemetry, flagging deviations from a learned normal envelope before they
  cross hard alarm thresholds.
- **Predictive maintenance models** — remaining-useful-life and
  failure-probability estimates per asset; when probability crosses a configured
  threshold the model emits a `predictive` work order rather than waiting for a
  fixed-interval `preventive` one.
- **Process optimization** — recommend setpoint adjustments (temperature, speed,
  feed rate) that improve yield, energy use, or throughput within recipe
  tolerance bounds.
- **Quality prediction** — predict end-of-line quality from in-process telemetry
  so a likely-defective unit is caught mid-line, not at final inspection.
- **Model deployment and retraining** — model versioning, deployment, and
  performance tracking; drift in prediction accuracy raises a retraining signal.
  Industrial data pipelines feed labelled outcomes back to training. Predictions
  weight telemetry by `quality` and exclude `invalid` readings (see §2.2).

---

## 6. Energy Solutions

**Package:** `@brigid/energy` · **Application:** `apps/brigid/energy`

This package covers generation, storage, and consumption optimization for
industrial sites, including off-grid and hybrid configurations common in West
African markets where grid reliability is limited and solar resources are high.
The companion `energy` application exposes these capabilities as an operational
energy management system.

- **Solar PV** — model array capacity, orientation, and expected generation
  against site irradiance.
- **Battery storage** — state-of-charge tracking, charge/discharge scheduling,
  and cycle-life accounting for industrial battery banks.
- **Diesel hybridization** — coordinate diesel generation with solar and battery
  so the generator runs in efficient bands and idles when renewable supply
  covers load.
- **Load analysis** — characterize a facility's load profile to size generation
  and storage and identify shiftable load.
- **Peak shaving** — dispatch battery discharge during demand peaks to cap
  billed demand charges.
- **Microgrids** — coordinate multiple generation and storage assets behind a
  single point of supply, with islanding and grid-reconnection logic.
- **Tariffs and metering** — model time-of-use and demand tariffs, ingest meter
  data, and attribute consumption to lines and processes.
- **Energy audits** — structured audits identifying waste and efficiency
  opportunities with quantified savings.
- **Operational optimization** — produce a forward energy schedule and
  source-switching plan (`PowerManagementSystem` carries the switch logic,
  load-shedding rules, and grid-charge / solar-export setpoints).

---

## 7. Maintenance Intelligence

**Package:** `@brigid/maintenance` · **Application:** `apps/brigid/maintenance`

This package owns the work-order lifecycle and the analytics that decide when,
what, and how to maintain assets. It bridges traditional schedule-based
maintenance with AI-driven prediction, allowing a facility to progressively
replace fixed-interval work with condition-based and predictive work orders as
enough operational data accumulates.

- **Preventive maintenance** — fixed-interval or usage-based schedules that emit
  `preventive` work orders.
- **Predictive maintenance** — consume `@brigid/ai-industrial`
  failure-probability signals to emit `predictive` work orders ahead of failure,
  displacing unnecessary fixed-interval work.
- **Work orders** — create, assign, and track work orders through the §2.3
  `WorkOrderStatus` lifecycle, capturing labor, materials, costs, and the
  post-maintenance check.
- **Technician scheduling** — assign work orders to technicians by skill, shift,
  and certification, balancing load and respecting priority.
- **Downtime analysis** — attribute unplanned downtime to causes and assets,
  ranked by lost-output impact.
- **Reliability metrics** — compute MTBF (mean time between failures) and MTTR
  (mean time to repair) per asset and asset class, trended over time.
- **Spare-parts planning** — track spare stock against failure rates and lead
  times; a `pending_parts` work order is the explicit signal that drives
  reorder. `@brigid/maintenance` computes Economic Order Quantity, safety stock,
  and criticality-based auto-reorder.
- **Service contracts** — model contractual maintenance obligations and SLAs,
  including response-time commitments, and report compliance against them.

---

## 8. Robotics

**Package:** `@brigid/robotics`

This package models collaborative and warehouse robots as a distinct asset class
within the Brigid equipment hierarchy. Robots have unique safety requirements —
they share workspace with humans and operate at speeds and forces that can cause
injury — so the package enforces safety-zone semantics and requires validated
safety configurations before deployment.

- **Collaborative robots (cobots)** — model cobots sharing workspace with human
  operators, with payload, reach, and speed parameters.
- **Warehouse robots** — autonomous mobile robots for material movement, with
  routing and task-queue state.
- **ROS2 concepts** — represent robot nodes, topics, and task graphs aligned to
  the ROS2 model so robot programs map cleanly onto Brigid assets.
- **Cell safety and safety zones** — define guarded `SafetyZone`s around a robot
  cell (`collaborative_space`, `restricted_space`, `safeguarded_space`, and so
  on, aligned to ISO/TS 15066); the `Robot` record carries a `safeguardingType`
  and a `safetyValidated` flag. Zone intrusion forces the robot into a safe
  state, and robot-cell safety obeys the deterministic fallback requirement (see
  §19).
- **Task orchestration** — sequence and dispatch robot tasks, coordinating
  multiple robots and integration with machine cells so a robot's pick aligns
  with a machine's ready state.
- **Payload limits** — enforce per-robot payload and reach limits as hard
  constraints in task planning.

---

## 9. Industrial Digital Twin

**Package:** `@brigid/digital-twin`

A digital twin is a synchronized virtual model of a physical plant or line, kept
in step with reality by live telemetry. Brigid's digital twin package gives
engineers a safe sandbox for simulation, commissioning, and training — changes
that would be costly or dangerous to test on real equipment can be validated in
the twin first.

- **Plant and line twins** — a twin mirrors the asset hierarchy and live state
  of a real plant or line, kept in sync from telemetry.
- **Simulation** — run a production line forward in the twin to project
  throughput, buffer behavior, and bottlenecks under a chosen schedule.
- **Virtual commissioning** — validate control logic and line behavior against
  the twin before committing changes to physical equipment, reducing on-floor
  commissioning risk.
- **Operator training** — let operators rehearse start-up, changeover, and fault
  recovery against the twin without risk to production or safety.
- **Scenario analysis and what-if planning** — compare alternative line
  configurations, shift patterns, or product mixes in simulation before
  deciding.
- **Process replay** — replay historical telemetry through the twin to
  reconstruct and diagnose a past incident.

---

## 10. OT Cybersecurity

**Package:** `@brigid/cybersecurity`

Operational technology (OT) security is fundamentally different from IT
security: control systems run decades-old protocols with no native encryption,
and a security incident can cause physical damage or endanger workers. This
package secures OT and industrial control system assets following the IEC 62443
framework, and records every policy decision and operator override to create a
defensible audit trail.

- **OT/ICS asset inventory** — discover and catalog control-system assets (PLCs,
  HMIs, RTUs, engineering workstations) with firmware and protocol metadata.
- **IEC 62443 alignment** — organize the OT network into zones and conduits per
  the IEC 62443 model and evaluate posture against its requirements.
- **Network zones** — define security zones with allowed conduits between them;
  unexpected cross-zone traffic is flagged.
- **Threat detection** — monitor OT traffic and asset behavior for indicators of
  compromise, raising security alarms with affected asset and detection context.
- **Vulnerability tracking** — track known vulnerabilities against the asset
  inventory by firmware and component version, prioritized by exposure and
  criticality.
- **Access control** — model role-based access to control-system functions;
  every policy decision (allow/deny) and every operator override of a control is
  recorded as an audit event (see §19).
- **Incident response** — structured response workflows for OT security
  incidents, from detection through containment and post-incident review.
- **Security posture** — a rolled-up posture view across zones and asset classes
  for the security team.

---

## 11. Vertical Industries

Brigid ships dedicated libraries for industries whose automation needs differ
enough from general factory automation to warrant their own models. All reuse
the §2 core types and the §7 maintenance lifecycle, so vertical-specific models
are additive — they add domain concepts without replacing the shared foundation.

### 11.1 Mining — `@brigid/mining`

Mining automation: conveyor systems, processing plants, drill-and-blast
planning, and haulage intelligence (truck cycles, route optimization, fleet
utilization).

### 11.2 Oil and Gas — `@brigid/oil-gas`

Upstream, midstream, and downstream operations: well and pipeline
instrumentation, process-control intelligence, and flow and pressure monitoring
across the value chain.

### 11.3 Packaging — `@brigid/packaging`

Packaging-line automation: filling, sealing, labeling, and palletizing stations
modeled as balanced lines (§3.1) with format-changeover recipes.

### 11.4 Agricultural Mechanization — `@brigid/agricultural-mech`

Farm-equipment intelligence and irrigation automation: equipment fleets,
irrigation scheduling and control, and mechanization planning. Asase consumes
this capability for agricultural operations via the cross-domain adapter.

### 11.5 Water and Waste Treatment — `@brigid/water`

Water and waste-treatment plant operations: process control for treatment
stages, regulatory-compliance monitoring against discharge limits, and
operational reporting.

### 11.6 Refrigeration and HVAC — `@brigid/hvac`

Cold-chain, refrigeration, and HVAC systems: temperature integrity across the
cold chain, energy-efficiency optimization, and refrigeration service
operations.

### 11.7 Industrial Materials — `@brigid/materials`

Industrial materials production: plastics recycling, packaging materials,
welding consumables, and industrial gases — production, quality, and inventory
for the materials Brigid plants both make and consume.

---

## 12. Weighing and Calibration

**Package:** `@brigid/weighing`

Weighing and calibration is a compliance-sensitive area: instruments must be
traceable to national standards, calibration records must survive regulatory
audit, and a corrected record must never overwrite the original. This package
owns that entire workflow, from instrument registration through certificate
issuance.

- **Weighing systems** — model scales, load cells, and weighbridges as
  instrument assets with capacity and accuracy class.
- **Calibration workflow** — schedule and execute calibrations as `calibration`
  work orders (§2.3), capturing reference standards, as-found and as-left
  readings, and pass/fail against tolerance.
- **Metrology and traceability** — maintain the traceability chain from each
  instrument to the reference standards used to calibrate it.
- **Certification** — issue calibration certificates on successful calibration.
  A completed calibration record is immutable after signoff; a later correction
  is an append-only correction event, never an in-place edit (see §19).

---

## 13. Supply Chain

**Package:** `@brigid/supply-chain`

This package optimizes the flow of materials and parts into and through
industrial operations, connecting supplier lead times and inventory levels to
production schedules so materials arrive when needed rather than accumulating as
working capital.

- **Inventory** — track raw materials, work-in-progress, spares, and finished
  goods with stock levels and reorder points.
- **Logistics** — plan inbound and outbound movement, including transport mode
  and lead-time accounting.
- **Vendor management** — maintain vendor records, performance history, and
  lead-time reliability, feeding sourcing decisions and `@brigid/market-intel`
  procurement intelligence.
- **Industrial demand forecasting** — forecast material and part demand from
  production schedules and historical consumption so inventory targets and
  reorders are demand-driven.

---

## 14. Training Academy

**Package:** `@brigid/training` · **Application:** `apps/brigid/training`

Industrial operations require certified, competent workers — regulations mandate
specific qualifications for operating pressure vessels, electrical
installations, and safety-critical systems. This package owns the full
technical-skills training and certification system for the industrial workforce,
from curriculum design through certification issuance and renewal tracking.

- **Courses** — structured technical courses in industrial skills (controls,
  maintenance, safety, robotics operation) with modules and assessments.
- **Certifications** — track certifications a worker holds. The `Certification`
  record carries issue and expiry dates, a `CertificateStatus`
  (`active`/`expired`/`suspended`/`revoked`/`pending_renewal`), a renewal
  window, an audit history, and continuing-professional-development entries.
- **Skills and instructors** — model a worker's skill profile and the
  instructors qualified to teach and assess each skill.
- **Learner progress** — track each learner's course progress, assessment
  results, and workforce progression path.

---

## 15. Market Intelligence and Financials

**Packages:** `@brigid/market-intel`, `@brigid/financials`

These two packages support the business side of industrial operations: scoring
market opportunities, monitoring procurement conditions, and building the
financial models that feed Maat's organization-wide analytics.

- **Market intelligence** — `@brigid/market-intel` scores industrial market
  opportunities, monitors procurement intelligence (pricing, vendor capacity,
  lead-time movement), and ranks opportunities for the business.
- **Financial models** — `@brigid/financials` builds financial models across
  every Brigid business unit (factory, energy, maintenance, materials,
  verticals), producing the operational and capital rollups that Maat consumes
  for organization-wide finance and risk.

---

## 16. Application Services

Five services in `apps/brigid/*` expose Brigid's libraries as operational
workflows. Each service is a standalone application that can be deployed
independently; the shared API service is the primary integration point for
external callers and partner domains. The specifications register them as
`@brigid/api`, `@brigid/factory-os`, `@brigid/energy-ms`,
`@brigid/maintenance-ms`, and `@brigid/training-lms`.

- **`apps/brigid/api`** — the domain API surface, a Hono application. Hosts the
  REST route groups (§17) and is the entry point for equipment, telemetry,
  maintenance, energy, AI, training, and cross-domain data.
- **`apps/brigid/factory-os`** — the factory operating-system interface: live
  line state, OEE and throughput dashboards, alarms, recipe selection, and
  operator start-up / changeover / shutdown workflows.
- **`apps/brigid/energy`** — the energy operations service: generation and
  storage dispatch, load and tariff views, peak-shaving control, and energy
  forecasts.
- **`apps/brigid/maintenance`** — the maintenance service: the work-order queue,
  technician scheduling, downtime analysis, and reliability reporting.
- **`apps/brigid/training`** — the training LMS: course delivery, assessments,
  certification issuance and expiry tracking, and learner progression.

---

## 17. APIs, Events, and Persistence

### 17.1 API Route Groups

`@brigid/api` is a Hono application. Health endpoints (`/health`, `/ready`) sit
at the root; the functional API is mounted at `/api/v1` with these route groups:

1. **Equipment** (`/equipment`) — list, read, create, update, soft-delete, bulk
   create/update, and the recursive asset hierarchy.
2. **Telemetry** (`/telemetry`) — batch ingestion (≤1000 readings per batch),
   latest reading per tag, and time-series history.
3. **Maintenance** (`/maintenance`) — work orders, PM schedules, spare parts,
   and MTBF/MTTR/availability KPIs.
4. **Energy** (`/energy`) — solar, battery, and grid status, a combined summary,
   and audit-reading submission.
5. **AI** (`/ai`) — image-based vision inspection, per-asset RUL /
   failure-probability predictions, and process-parameter optimization.
6. **Training** (`/training`) — course catalog, enrollment, learner progress,
   assessment submission, and certifications.
7. **Cross-domain** (`/cross-domain`) — equipment-provision and maintenance
   requests, plus a Server-Sent Events telemetry subscription.

A WebSocket endpoint (`/ws/factory`) streams live factory state. Route-level
stores are currently in-memory `Map` structures; the `@brigid/db` schema is the
persistence target.

### 17.2 Events

Brigid does not yet ship a published platform-event catalog of named event
constants. The implemented event surface consists of two real-time channels:

- **Factory WebSocket messages** (`/ws/factory`) — the `FactoryWSMessageType`
  union: `SCADA_UPDATE`, `ALARM_ACTIVE`, `ALARM_CLEARED`, `OEE_UPDATE`,
  `ASSET_STATUS_CHANGE`, `WORK_ORDER_UPDATE`, plus the control messages
  `SUBSCRIBE`, `UNSUBSCRIBE`, `PING`, `PONG`. Payloads carry SCADA tag updates,
  alarm events, or OEE data.
- **Cross-domain SSE events** — `CrossDomainEvent` objects are appended to an
  internal queue and replayed over
  `GET /api/v1/cross-domain/telemetry/subscribe`. The emitted `eventType` values
  are `EQUIPMENT_PROVISION_REQUESTED` and `CROSS_DOMAIN_MAINTENANCE_REQUEST`.
- **SCADA alarm state** — SCADA alarm transitions are modeled by the ISA-18.2
  `AlarmState` machine in `@brigid/factory`.

A formal cross-factory event bus (Kafka topics for alarms, production, and
quality; MQTT for IoT) is described as future infrastructure but is not yet
expressed as Brigid event-constant code — treat it as `(planned)`.

Brigid **bridges** to Asase, Freya, Cybele, Saraswati, and Maat via
`@brigid/cross-domain`, and relies on shared platform infrastructure (auth,
database, metrics, logging, event bus, storage).

### 17.3 Persistence

Brigid uses four storage technologies, each chosen for the access pattern of the
data it holds.

- **PostgreSQL** — domain records, reference data, work orders, financial
  records, market intelligence, and audit history.
- **TimescaleDB** (hypertables) — high-volume telemetry and sensor streams, kept
  in separate hypertables so ingestion volume does not degrade record queries.
- **Redis** — operational caches, command coordination, and dashboard hot state.
- **Object storage** — CAD files, commissioning packs, inspection media,
  training content, and reports.

---

## 18. Cross-Domain Integrations

All data exchange flows through `@brigid/cross-domain`; consumers never import
Brigid internals directly. This boundary ensures that Brigid can refactor its
internal model without breaking partner domains, and that partner domains cannot
depend on Brigid implementation details that might change.

The table below shows what each consumer receives and why Brigid, not the
consumer, owns the industrial data:

- **Asase** consumes Brigid food-processing automation, cold chain, agricultural
  mechanization, and post-harvest equipment intelligence for agricultural
  operations. The boundary exists because Asase owns agricultural economics and
  food-chain logistics, not the engineering control systems that run those
  operations.
- **Freya** consumes Brigid textile-manufacturing, cosmetics-production,
  garment-manufacturing, and packaging-line intelligence for beauty, fashion,
  and textiles. Freya owns product design and brand identity; Brigid owns the
  production lines.
- **Cybele** consumes Brigid prefab-housing, building-materials, data-center-
  power, and construction-equipment intelligence for construction and
  infrastructure. Cybele owns the built environment; Brigid owns the factories
  that manufacture the components for it.
- **Saraswati** consumes Brigid EV-battery, solar-panel, electronics-assembly,
  and PCB manufacturing intelligence for advanced-technology manufacturing.
  Saraswati owns the technology products; Brigid owns the manufacturing
  processes that produce them.
- **Maat** consumes Brigid factory-telemetry, equipment-utilization,
  predictive-maintenance, supply-chain, and energy analytics for
  organization-wide rollups. Maat aggregates across all domains; it does not
  store Brigid's raw operational data, only the normalized analytics that Brigid
  surfaces.
- **Shared** provides auth, database, metrics, logging, event bus, storage, and
  deployment primitives.

---

## 19. Non-Functional Requirements

These constraints apply across every subsystem above. They are not aspirational:
the `@brigid/core` types, `@brigid/db` schema, and application middleware are
built specifically to enforce them. Safety-critical and OT workflows depend on
all four.

- **Deterministic fallback for safety-critical workflows** — any workflow
  touching a safety-critical asset (robot cells, safety-instrumented functions,
  control paths) must, on validation failure, sensor loss, or model uncertainty,
  enter a defined safe fallback state — never an undefined or best-guess one.
  The `@brigid/core` `SafetySystem` type carries the recorded `failSafeAction`
  and `bypassProcedure` that back this. Validation errors are surfaced;
  auditability is preserved.
- **Recorded OT decisions and overrides** — every OT and
  industrial-cybersecurity policy decision and every operator override of a
  control is written to the audit log with actor, timestamp, and rationale.
- **Out-of-order, degraded-quality telemetry** — telemetry ingestion tolerates
  out-of-order readings (inserted in time order) and degraded sensor quality
  (carried as a `quality` flag, weighted or excluded downstream), without
  rejecting the stream.
- **Immutable records after signoff** — maintenance and calibration records are
  immutable once signed off; corrections are append-only correction events that
  preserve the original record and its full history.
- **Verification expectations** — changes run the affected packages' tests, type
  checks, linting, and contract checks plus integration tests for affected app
  services. Industrial-safety, cybersecurity, and control-path changes
  additionally require focused tests around validation, fallback behavior, audit
  events, and permission boundaries.
