# Asase — Systems Deep Dive

> The `libs/asase/` area: 28 Nx libraries implementing **food & agriculture
> operations intelligence for Ghana's value chain** — a shared domain core plus
> a dozen analytic engine libraries, an infrastructure/data layer, cross-domain
> connectors, and thin business-unit facade packages, all named after Asase Yaa,
> the Akan earth goddess.

## What this area is

Asase models Ghana's entire food and agriculture ecosystem — production,
processing, cold chain, supply chain, quality/compliance, export, inputs, market
intelligence, and food-service retail — as a set of pure-TypeScript domain
engines. The numbering scattered through the source (`56.x.y.z` tags in file
docblocks, and `Phase-56` types in `@asase/core`) marks this as the platform's
"Phase 56" build-out. Almost every claim in these libraries is grounded in
Ghana-specific reference data: agro-ecological zones, MoFA/FDA/GSA/COCOBOD
regulatory bodies, the cedi (GHS), the two-rainy-season calendar, and named
research sources (CSIR-SARI, GCFI, NRC feed tables, Codex/ISO standards).

Structurally the area has four tiers. **The foundation** is `@asase/core`
(domain types, branded IDs, enums, constants, validation, value objects, and the
Phase-56 business-unit registry), supported by `@asase/infrastructure`
(cache/storage/ events/metrics/PostGIS) and `@asase/migrations` (the Postgres
schema and seeds). **The engine tier** is twelve substantial analytic libraries
— `crops`, `livestock`, `processing`, `cold-chain`, `supply-chain`, `quality`,
`export`, `inputs`, `market-intel`, `retail`, `financials`, and `sota` — each
carrying 9K–17K lines of domain algorithms across many focused modules. **The
integration tier** is `@asase/connectors`, which translates Asase data into
payloads shaped for other Oshun domains. **The facade tier** is twelve thin
business-unit packages (`bakery`, `beverages`, `cafe`, `cassava`, `dairy`,
`fertilizer`, `market`, `oils`, `poultry`, `qsr`, `rice`, `spices`) that simply
re-export an aggregate engine plus that unit's Phase-56 package profile.

The defining architectural decision (documented in
`libs/asase/core/src/package-profiles.ts`) is that the 19 business units in the
README do **not** each get their own engine. Instead shared concerns are
implemented once in aggregate engines (`processing`, `retail`, `inputs`,
`livestock`, `market-intel`) and the per-unit packages are thin public import
paths over them. `ASASE_PHASE56_PACKAGE_PROFILES` in `@asase/core` is the source
of truth for that business-unit → package mapping.

## How it fits the wider system

Everything in the area sits above `@asase/core`, which carries the `scope:asase`
/ `layer:domain` tags and depends on no other Asase library; the engine
libraries import its types, enums, and validators. `@asase/infrastructure`
(`layer:infrastructure`) and `@asase/migrations` (`layer:data`) bridge the
domain to real backing services — Redis, MinIO, Prometheus, and a PostGIS
Postgres instance via `@oshun/database`. `@asase/connectors`
(`layer:integration`) is the outward edge: it builds
Brigid/Cybele/Freya/Saraswati/Maat/Aje-shaped payloads from Asase intelligence
without importing those domains' runtime, so the dependency only flows one way.
The thin facade packages are what application code imports when it wants a
single business unit's surface (e.g. `@asase/bakery`) rather than the broad
`@asase/processing` engine.

## Entity reference

### @asase/core

The domain foundation every other Asase library builds on
(`libs/asase/core/src`, ~10.8K lines). It owns branded IDs (`FarmId`, `PlotId`,
`BatchId`, …) and their `create*` constructors, the domain enums
(`BusinessUnit`, `CropCategory`, `Region`, `Season`, `UnitOfMeasure`), value
objects (`Temperature`, `SoilPH`, `PlotArea`), Ghana reference constants
(`CROP_VARIETIES`, `REGULATORY_BODIES`, `SEASON_RANGES`, `HS_CODES`,
`GHS_EXCHANGE_RATES`), validators (`validateGhanaCoordinates`,
`validateCocoaQuality`, `validateGhanaPhoneNumber`), and typed errors
(`ColdChainBreachError`, `FoodSafetyViolationError`, …). It also houses the
Phase-56 modules: `business-units.ts` (the 19-member `BusinessUnitConfig` union
plus guards like `requiresColdChainTracking`), `package-profiles.ts` (the
`ASASE_PHASE56_PACKAGE_PROFILES` registry), `agro-ecology.ts`
(`GHANA_REGION_PROFILES`, `AgroEcologicalZone`, `REGION_TO_ZONE`),
`measurement.ts`, `seasonality.ts` (`CROP_SEASONALITY`), `stakeholders.ts`
(Ghana Card / TIN / SSNIT profiles), `domain-entities.ts`, `domain-services.ts`
(`UnitConversionService`, `GhanaRegulatoryService`, `AuditTrailService`), and
`geo-utils.ts` (`haversineDistanceKm`, `isWithinGhanaBounds`).

### @asase/infrastructure

The shared infrastructure layer (`libs/asase/infrastructure/src`,
`layer:infrastructure`, ~3.1K lines). It exposes five services through
`index.ts`: a namespaced TTL-aware Redis cache (`AsaseCacheClient`, `ASASE_TTL`,
`asaseKey`), a MinIO object-storage service for imagery and compliance docs
(`AsaseStorageService`, `ASASE_BUCKETS`), a domain event bus with a typed topic
hierarchy (`createAsaseEventBus`, `ASASE_TOPICS`, and concrete events like
`ColdChainBreachDetectedEvent`), Prometheus metrics (`AsaseMetricsService`), and
a PostGIS-backed geospatial service (`geospatial.ts`). The geospatial module
stores plot polygons, facility points and route linestrings in EPSG:4326,
reprojects to UTM 30N (EPSG:32630) for metric area, encodes Ghana's 16 regions
as boundary constants, and uses raw `pg` SQL rather than an ORM.

### @asase/migrations

The database migration and seeding framework (`libs/asase/migrations/src`,
`layer:data`, ~15K lines). It wraps `@oshun/database`'s `MigrationRunner` with
Asase-specific advisory-lock and schema config (`runner.ts`) and ships 11
ordered SQL migrations under `src/migrations/` — enums, crop tables, livestock
tables, facility/processing tables, cold-chain, supply-chain, quality, market,
ops tables, RLS policies, and agricultural inputs (e.g. `asase_crop_varieties`,
`asase_farms`, `asase_plots` in migration 002). The `seed/` directory provides
idempotent seed scripts (business units, crop varieties, facilities, livestock
breeds, markets, quality standards, suppliers, workers, agri-inputs). A
`migrate.ts` CLI exposes `up`/`down`/`status`/`seed`/`reset`, surfaced as the
`migrate:*` Nx targets in `project.json`.

### @asase/crops

Crop intelligence and field operations (`libs/asase/crops/src`, ~9K lines). It
centres on `crop-registry.ts` (`GHANA_CROP_REGISTRY` with 15+ variety profiles),
`variety-recommender.ts` (multi-criteria gross-margin scoring), and
`pest-disease-catalog.ts` (18+ threat entries with economic thresholds). The
analytic modules include `yield-predictor.ts` — a documented multi-factor model
where
`Predicted = attainableYield × 0.80 × rainfall × soilFertility × inputUsage × pestPressure × historical`,
with confidence intervals that widen by horizon (±15% at 30d, ±35% at 90d) —
plus `harvest-loss-estimator`, `irrigation-manager`, `soil-fertility-tracker`,
`weather-impact-analyzer`, `intercropping`, `mechanization-scheduler`,
`labor-manager`, `input-scheduler`, and `field-activity-tracker`.

### @asase/livestock

Livestock, poultry, and aquaculture operations (`libs/asase/livestock/src`,
~16.5K lines). The standout module is `feed-formulation.ts`, a genuine
least-cost ration solver implementing the Big-M simplex LP method over 13
Ghana/West-Africa feed ingredients with crude-protein, energy, calcium,
phosphorus, lysine, methionine, fibre and moisture constraints, citing NRC
(1994/2012), INRA/CIRAD/AFZ and GSA 1153:2019. Around it sit poultry modules
(`broiler-tracker`, `layer-manager`, `hatchery-operations`, `house-environment`,
`poultry-distribution`), aquaculture modules (`aqua-feed-manager`,
`aqua-growth-tracker`, `fish-farm-registry`, `fish-health-manager`,
`water-quality-monitor`), and shared animal-health modules
(`disease-surveillance`, `vaccination-manager`, `mortality-morbidity`,
`livestock-registry`).

### @asase/processing

Food-processing operations intelligence (`libs/asase/processing/src`, ~13.7K
lines) and the aggregate engine behind the
bakery/beverages/cassava/dairy/oils/rice/spices facades. Its anchor is
`oee-engine.ts`, a SEMI E10 / VDMA Overall Equipment Effectiveness calculator
(Availability × Performance × Quality) tracking Nakajima's Six Big Losses
against JIPM world-class benchmarks, contextualised for Ghana's 55–75% typical
OEE. Supporting modules cover the plant lifecycle: `plant-digital-twin`,
`recipe-manager`, `bom-explosion`, `batch-execution-engine`, `batch-genealogy`,
`production-scheduler`, `spc-module` (statistical process control),
`predictive-maintenance`, `raw-material-receiving`, `yield-waste-tracker`,
`energy-efficiency`, `utility-monitoring`, `cost-of-quality`, and
`nutritional-labeling`.

### @asase/cold-chain

Cold storage, refrigerated transport, and grain-storage intelligence
(`libs/asase/cold-chain/src`, ~13.3K lines). `route-optimizer.ts` solves the
Vehicle Routing Problem with Time Windows for Ghana cold-chain deliveries, using
city-specific traffic congestion multipliers (Accra/Kumasi/Tamale peak
profiles), a compartment temperature-drift model with door-open heat impulses
(ASHRAE 2017 derived), and nearest-neighbour + 2-opt sequencing. The rest of the
library covers the cold-chain stack: `temperature-monitor`, `transport-fleet`
(haversine distance), `warehouse-manager`, `warehouse-receipt`,
`grain-storage-monitor`, `excursion-analytics`, `energy-optimizer`,
`backup-power`, `last-mile-tracker`, `postharvest-loss`, `facility-registry`,
`inventory`, `inventory-valuation`, and `compliance-docs`.

### @asase/supply-chain

Procurement, distribution, and market-channel intelligence
(`libs/asase/supply-chain/src`, ~14.7K lines). `vehicle-routing.ts` is a
nearest-neighbour + 2-opt routing engine parameterised on Ghana road types, fuel
prices (GHS/litre), six vehicle classes, customer time windows, and Road Traffic
Act driver hours-of-service limits (max 9h driving, 30-min break after 4.5h).
The library also implements `procurement`, `outgrower` and `contract-farming`
(smallholder sourcing), `distribution-network`, `market-channel`,
`commodity-price`, `price-forecast`, `margin-analysis`, `demand-sensing`,
`import-management`, `import-parity`, `supplier-risk`, `delivery-proof`, and
`returns-logistics`.

### @asase/quality

Food-safety, laboratory, and compliance workflows (`libs/asase/quality/src`,
~15.3K lines). `haccp.ts` implements all seven HACCP principles against Ghana
FDA Act 851, Codex CAC/RCP 1-1969, and ISO 22000:2018, encoding Ghana-specific
limits (10 ppb total aflatoxin, metal-detector CCP for packaged products ≥25 g).
The surrounding modules form a regulatory suite: `ccp-monitoring`, `prp`
(prerequisite programmes), `lims`, `aflatoxin`, `pesticide`, `water-quality`,
`calibration`, `audit`, `recall`, `fda-registration`, `export-certification`,
`organic-certification`, `label-compliance`, `environmental-compliance`, and
`regulatory-change`.

### @asase/export

Export operations intelligence (`libs/asase/export/src`, ~14.3K lines).
`customs-duty-calculator.ts` computes landed cost and import duty across 24
destination countries, selecting the lowest valid preferential rate among GSP,
EU-Ghana EPA, AGOA, AfCFTA and bilateral agreements and validating
rules-of-origin, with rates sourced from WTO TDF, ITC MacMap and the relevant
tariff schedules. The library also provides `afcfta-compliance`,
`eu-regulation-tracker`, `export-license-manager`,
`quality-certification-tracker`, `trade-documents`, `contract-negotiation`,
`buyer-crm`, `logistics-optimizer`, `dynamic-pricing-engine`,
`commodity-analyzer`, `competitor-tracker`, `grading-engine`, `market-scanner`,
and `volume-forecaster`, oriented to Ghana's cocoa/shea/cashew export trade.

### @asase/inputs

Agricultural-inputs intelligence (`libs/asase/inputs/src`, ~17K lines — the
largest library in the area) and the aggregate engine behind the
`@asase/fertilizer` facade. `fertilizer-blend-optimizer.ts` derives
crop-specific NPK ratios from soil tests, target yields and agro-ecological zone
(five Ghana zones with per-zone rainfall constants), citing GCFI, MoFA,
CSIR-SARI, OPRI and IFA guidance. The rest spans fertilizer economics
(`fertilizer-cost-analyzer`, `fertilizer-subsidy-tracker`,
`organic-fertilizer-advisor`, `import-substitution-analyzer`), agrochemicals
(`agrochemical-guidance-engine`, `agrochemical-safety-module`,
`integrated-pest-management-advisor`), seed systems
(`seed-performance-database`, `seed-multiplication-tracker`), and
distribution/finance (`soil-nutrient-mapper`, `input-bundle-optimizer`,
`input-distribution-network-manager`, `input-quality-assurance`,
`farmer-credit-facilitator`).

### @asase/market-intel

Commodity and trade analytics (`libs/asase/market-intel/src`, ~13.8K lines) and
the engine behind the `@asase/market` facade. `price-forecasting-engine.ts`
implements three model families in pure TypeScript with no ML runtime: ARIMA for
short-horizon levels, GARCH(1,1) for volatility-driven confidence intervals, and
an honestly-documented triple-exponential-smoothing approximation labelled
"LSTM-inspired" for long horizons (the docblock states the LSTM layer is an
analytically-tractable Holt-Winters stand-in, not a neural net). Companion
modules include `commodity-price-tracker`, `farmgate-price-monitor`,
`price-elasticity-calculator`, `price-transmission-analyzer`,
`seasonality-profiler`, `supply-demand-modeler`, `consumer-trend-analyzer`,
`competitor-analysis-engine`, `market-entry-assessor`,
`afcfta-opportunity-scanner`, `regional-trade-flow-mapper`,
`policy-impact-simulator`, `cedi-exposure-calculator`, and
`trade-intelligence-dashboard`.

### @asase/retail

QSR, cafe, and institutional-catering engines (`libs/asase/retail/src`, ~11.4K
lines) and the aggregate engine behind the `@asase/cafe` and `@asase/qsr`
facades. `menu-engineering-analyzer.ts` classifies items as
Stars/Plowhorses/Puzzles/Dogs using the Kasavana-Smith (1982) matrix with Ghana
QSR food-cost benchmarks per menu category (e.g. higher targets for
labour-intensive local specials like jollof and banku). The library also
implements `dynamic-menu-pricer`, `menu-localizer`, `recipe-cost-calculator`,
`central-kitchen-planner`, `institutional-catering-manager`,
`franchise-management-system`, `restaurant-pos-integrator`,
`delivery-platform-integrator`, `delivery-logistics-engine`,
`customer-loyalty-engine`, `staff-scheduling-optimizer`,
`inventory-waste-tracker`, `qsr-location-analyzer`, and `quality-audit-system`.

### @asase/financials

Financial models and investment analytics for the Asase conglomerate
(`libs/asase/financials/src`, ~12K lines). `investor-return-calculator.ts`
models a four-tier capital stack (senior debt, mezzanine, preferred equity,
common equity), computing IRR via bisection, MOIC, cash yield, and a
seniority-ordered distribution waterfall with base/upside/downside exit
scenarios at Years 5 and 7, all in GHS millions. The other modules form a
corporate-finance suite: `consolidated-projection-engine`,
`unit-economics-modeler`, `working-capital-modeler`, `capex-planning-module`,
`debt-capacity-analyzer`, `fx-risk-quantifier` (cedi exposure),
`tax-optimization-modeler`, `scenario-planner`, `benchmarking-module`,
`farm-economics-calculator`, `processing-economics-analyzer`,
`startup-cost-estimator`, `synergy-valuation-engine`, and
`impact-metrics-calculator`.

### @asase/sota

State-of-the-art technology modules (`libs/asase/sota/src`, `type:sota`, ~4.7K
lines). It contains four real, dependency-free computation modules:
`satellite.ts` (spectral vegetation indices — NDVI/EVI/NDWI/SAVI — LAI
estimation, change detection, EUDR deforestation monitoring, flood/drought early
warning), `drone.ts` (GCAA-compliant flight planning, prescription zones, plant
counting), `computer-vision.ts` (cocoa fermentation/ICCO grading, cashew AFI
grading, grain mycotoxin/aflatoxin estimation), and `blockchain-iot.ts` (a
hash-chained provenance ledger with chain-integrity verification, smart-contract
payment triggers, and IoT cold-chain excursion analytics). `ml-predictions.ts`
is honest about its nature: `predictYield` is a deterministic weighted agronomic
ensemble of nutrient/water/soil/climate/historical sub-scores — the `MLModel`
enum (`'XGBoost' | 'LightGBM' | …`) is a label, and the header states "no
external ML libraries required," so no actual trained model runs here.

### @asase/connectors

Cross-domain synergy connectors (`libs/asase/connectors/src`,
`layer:integration`, ~3.4K lines; lint/test only, no build target). Each module
translates Asase intelligence into a payload shaped for another Oshun domain and
defines that boundary surface locally rather than importing the target domain's
runtime: `brigid-connectors` (irrigation/processing-facility/cold-chain/road
engineering specs), `cybele-connectors` (climate-adaptation, soil-health,
water-resource and biodiversity-impact integration with RCP scenarios and WRB
soil types), `freya-connectors` (GCX-referenced marketplace listings,
mobile-money payment reconciliation, warehouse-receipt/PO trade finance),
`saraswati-connectors` (multi-language farmer training modules and research
outputs), `maat-connectors` (FDA food-safety compliance reports and land-tenure
packages), and `aje-connectors` (agricultural credit scorecards and commodity
hedge structures).

### @asase/bakery

A thin business-unit facade (`libs/asase/bakery/src/index.ts`,
`type:feature-lib`). It contains no engine code of its own: it re-exports the
entire `@asase/processing` engine, surfaces the Phase-56 helpers from
`@asase/core`, exposes the `BakeryConfig` type (as `BakeryBusinessUnitConfig`),
and exports `bakeryPackageProfile = ASASE_PHASE56_PACKAGE_PROFILES.bakery`. It
exists so application code can import a bakery-scoped path over the shared
processing engine.

### @asase/beverages

A thin facade over `@asase/processing` (`libs/asase/beverages/src/index.ts`,
`type:feature-lib`). It re-exports the processing engine, the core Phase-56
helpers, the `BeveragesConfig` type, and `beveragesPackageProfile`. Per the
README it covers juice, water, soft-drink and traditional beverages (sobolo,
asaana); the actual operations logic lives in `@asase/processing`, not here.

### @asase/cafe

A thin facade over `@asase/retail` (`libs/asase/cafe/src/index.ts`,
`type:feature-lib`). It re-exports the retail engine (POS, menu, catering), the
core Phase-56 helpers, the `CafeConfig` type, and
`cafePackageProfile = ASASE_PHASE56_PACKAGE_PROFILES.cafe`. It is a
business-unit import path, not an independent implementation.

### @asase/cassava

A thin facade over `@asase/processing` (`libs/asase/cassava/src/index.ts`,
`type:feature-lib`) for gari/fufu-flour/starch/chips operations. It re-exports
the processing engine, the core Phase-56 helpers, the `CassavaProcessingConfig`
type, and `cassavaPackageProfile`. No cassava-specific engine code lives here.

### @asase/dairy

A thin facade over `@asase/processing` (`libs/asase/dairy/src/index.ts`,
`type:feature-lib`) for milk/pasteurisation/yogurt/cheese operations. It
re-exports the processing engine, the core Phase-56 helpers, the `DairyConfig`
type, and `dairyPackageProfile`. Cold-chain coverage referenced in the README is
provided by the separate `@asase/cold-chain` engine, not duplicated here.

### @asase/fertilizer

A thin facade over `@asase/inputs` (`libs/asase/fertilizer/src/index.ts`,
`type:feature-lib`). It re-exports the agricultural-inputs engine, the core
Phase-56 helpers, the `FertilizerConfig` type, and
`fertilizerPackageProfile = ASASE_PHASE56_PACKAGE_PROFILES.fertilizer`. The
fertilizer/blend optimisation logic itself lives in `@asase/inputs`.

### @asase/market

A thin facade over `@asase/market-intel` (`libs/asase/market/src/index.ts`,
`type:feature-lib`). It re-exports the market-intelligence engine, the core
Phase-56 helpers, the generic `BusinessUnitConfig` type, and
`marketPackageProfile`. The README describes it as the "public market
intelligence facade over commodity, demand, and trade analytics" — the analytics
live in `@asase/market-intel`.

### @asase/oils

A thin facade over `@asase/processing` (`libs/asase/oils/src/index.ts`,
`type:feature-lib`) for palm/coconut/groundnut/soybean oil extraction and
refining. It re-exports the processing engine, the core Phase-56 helpers, the
`EdibleOilsConfig` type (as `OilsBusinessUnitConfig`), and `oilsPackageProfile`.
No oils-specific engine code lives here.

### @asase/poultry

A thin facade over `@asase/livestock` (`libs/asase/poultry/src/index.ts`,
`type:feature-lib`). It re-exports the livestock engine (broiler/layer/hatchery
modules), the core Phase-56 helpers, the `PoultryConfig` type, and
`poultryPackageProfile = ASASE_PHASE56_PACKAGE_PROFILES.poultry`. The poultry
operations logic itself lives in `@asase/livestock`.

### @asase/qsr

A thin facade over `@asase/retail` (`libs/asase/qsr/src/index.ts`,
`type:feature-lib`) for quick-service-restaurant chain operations. It re-exports
the retail engine (franchise/POS/delivery/central-kitchen modules), the core
Phase-56 helpers, the `QsrChainsConfig` type, and `qsrPackageProfile`. No
QSR-specific engine code lives here beyond the profile binding.

### @asase/rice

A thin facade over `@asase/processing` (`libs/asase/rice/src/index.ts`,
`type:feature-lib`) for paddy processing, parboiling and packaging. It
re-exports the processing engine, the core Phase-56 helpers, the
`RiceMillingConfig` type, and
`ricePackageProfile = ASASE_PHASE56_PACKAGE_PROFILES.rice`. The milling logic
itself lives in `@asase/processing`.

### @asase/spices

A thin facade over `@asase/processing` (`libs/asase/spices/src/index.ts`,
`type:feature-lib`) for pepper/ginger/turmeric drying, milling and moisture
compliance. It re-exports the processing engine, the core Phase-56 helpers, the
`SpicesConfig` type, and
`spicesPackageProfile = ASASE_PHASE56_PACKAGE_PROFILES.spices`. No
spices-specific engine code lives here.
