Domain · Features

Asase — Features and Capabilities

The core library is the implemented foundation of the Asase domain: all shared types, constants, unit utilities, regulatory compliance checks, stakeholder models, and business unit configurations.

21sections45 minread

On this page
Supporting documentation. This domain also carries 3 operational supporting docs under docs/domains/asase/ (API notes, ADRs, deep topic guides) — reconciled here by linking, kept beside the code as supporting material rather than a second canonical source (§2, §13).

Asase (named after Asase Yaa, the Akan earth goddess of fertility, sustenance, and the harvest) is a food and agriculture operations intelligence platform for Ghana's complete food value chain. It covers 19 business units spanning the entire agricultural lifecycle: from smallholder and commercial crop production through livestock and poultry operations, processing and manufacturing, temperature-controlled cold chain logistics, supply chain aggregation, quality assurance, export documentation, agricultural inputs, and market intelligence.

Ghana's agriculture sector employs approximately 44% of the workforce and contributes roughly 20% of GDP, yet loses an estimated 20–30% of some perishable crops (tomatoes, yam, plantain) to post-harvest spoilage — a central problem the platform targets. The domain ships 15 libraries under libs/asase/ and 5 applications under apps/asase/. The platform is built around Ghana's specific agro-ecological context: bimodal rainfall seasons (south), unimodal seasons (north), 16 administrative regions, five distinct agro-ecological zones, and the regulatory bodies governing Ghanaian agriculture (MoFA, FDA, GSA, COCOBOD, EPA, PPRSD, VSD).


Asase is used directly by five application surfaces — a management dashboard, a field mobile app, a digital marketplace, a processing plant interface, and an API gateway — and integrates with six other Oshun domains through typed connector classes. The sections below describe what each library provides, why it was built, and which real-world Ghanaian institutions and standards it encodes.


1. Core Domain Intelligence#

Package: @asase/core

The core library is the implemented foundation of the Asase domain: all shared types, constants, unit utilities, regulatory compliance checks, stakeholder models, and business unit configurations.

1.1 Ghana-Specific Agricultural Context#

Ghana's agricultural landscape differs fundamentally from temperate farming contexts. The core library encodes this context throughout.

1.1.1 Agro-Ecological Zone Classification#

Ghana has five distinct agro-ecological zones, each with distinct rainfall patterns, soil types, temperature ranges, and crop suitability:

Zone Characteristics
Coastal Savanna Low and erratic rainfall (800–900 mm/yr), sandy soils, cassava and coconut
Deciduous Forest High rainfall (1400–1800 mm/yr), forest zone; cocoa, oil palm, plantain
Forest-Savanna Transition Moderate rainfall, diverse crops; yam, maize, cassava, cocoa belt edge
Guinea Savanna Northern zone, unimodal rainfall (1000–1200 mm/yr); maize, groundnut, yam
Sudan/Sahel Savanna Far north, driest zone (<1000 mm/yr); millet, sorghum, cowpea
  • Regional profiles — Full agro-ecological profiles for all 16 administrative regions with rainfall ranges, primary soil types, and cropping calendars.
  • Bimodal vs. unimodal seasonality — Southern Ghana has two rainy seasons: Major (March–July) and Minor (September–November), enabling two crop cycles per year. Northern Ghana has a single rainy season (May–October).
  • Harmattan dry season — December–February brings hot, dry, dust-laden winds from the Sahara. Planning support accounts for crop moisture stress, reduced humidity (relevant for cocoa pod borer), and field access challenges.
  • Crop seasonality profiles — Per-crop planting windows, growth stage durations, input application windows, and harvest ranges calibrated to Ghana's specific rainfall patterns.

1.1.2 Regulatory Compliance Framework#

Type-safe compliance checks for all major Ghanaian agricultural regulatory bodies:

Regulatory Body Full Name Scope
MoFA Ministry of Food and Agriculture Farm registration, farmer certification, extension services
FDA Ghana Food and Drugs Authority Food safety, processing facility licensing, product registration
GSA Ghana Standards Authority Standards certification, product quality marks
COCOBOD Ghana Cocoa Board Cocoa quality grading, export certification, purchasing
EPA Environmental Protection Agency Pesticide registration, environmental impact assessments
PPRSD Plant Protection and Regulatory Services Directorate Phytosanitary inspection, export plant health certificates
VSD Veterinary Services Directorate Livestock health certification, abattoir inspection
  • isFdaRegulated(entity) — Determines whether a stakeholder or business unit requires FDA licensing.
  • requiresPprsdCompliance(entity) — Determines phytosanitary certification requirements for export operations.
  • requiresColdChainTracking(businessUnit) — Determines cold chain monitoring obligations based on business unit type.

1.1.3 Ghana-Specific Measurement Units#

Agricultural transactions in Ghana use traditional local units alongside international standards. The core library provides full conversion support:

Category Local units International units
Mass Maxi-bag (100 kg), mini-bag (50 kg) g, kg, tonne, pound, ounce
Volume Olonka (≈2.5 L), bowl (≈3.0 L), American tin (small ≈0.375 L, large ≈0.8 L) ml, litre, US gallon, m³
Area Plot (≈0.3 ha) m², hectare, acre, km²
Temperature Celsius, Fahrenheit, Kelvin
Currency GHS (Ghana Cedi) with reference exchange rates USD, EUR, GBP

The olonka is a traditional volumetric measure used in Ghanaian markets; the American tin is a recycled condensed-milk can used to measure small quantities of cereals and legumes. Mass, volume, and area conversions are provided both as a phantom-typed measurement algebra (measurement.ts) and as the runtime UnitConversionService.

1.2 Crop Cycle Management#

  • Crop cycle records — Full lifecycle through post-harvest with growth stage progression. CropCycle carries plotId, cropId, plantingDate, expectedHarvestDate, growthStage, variety, and seedSource.
  • Growth stages (GrowthStage enum) — dormant → germination → seedling → vegetative → flowering → fruiting → maturation → harvest → post_harvest.
  • Ghana crop variety catalogCROP_VARIETIES holds CropVarietyInfo for ~35 cultivars (localName, category, typicalYieldKgPerHa, growingDaysMin/Max, optimalRegions). Examples:
    • Maize: Obatanpa, Abontem, Mamaba, Aburohemaa
    • Cassava: Bankye Hemaa, Afisiafi, Ampong
    • Rice: Jasmine 85, AGRA, Tox 3108
    • Yam: Pona, Laribako, Dente
    • Cocoa: Cocoa Hybrid, Cocoa Amazonia
    • Export/tree crops: Cashew (Dwarf), Shea Nut, Oil Palm (Tenera Hybrid), Coconut (Malayan Yellow Dwarf)
    • The domain-entities.ts CROP_VARIETY_CATALOG adds richer CropVariety records (botanical classification, local-language names, yield ranges, market grades) for COCOA_HYBRID_CRIG, MAIZE_OBATANPA_QPM, CASSAVA_AFISIAFI, and YAM_PONA.
  • Yield calculation — Yield per hectare with comparison to typical yields by variety and region.
  • Harvest date estimation — Based on planting date, variety, and growing degree data.
  • Planting window validation — Automatic validation that planting dates fall within regional cropping calendar windows.
  • Post-harvest loss rates — Pre-calculated typical loss rates by commodity. Ghana loses an estimated 20–30% of some crops (yam, tomatoes, plantain) to post-harvest spoilage, a key platform problem to help address.

Automatic crop suitability lookup by administrative region, accounting for agro-ecological zone, rainfall pattern, and dominant soil types. A farmer in Bono East is shown different primary crop recommendations than a farmer in the Upper East region.

1.4 Farm Management (Core Types)#

  • Farm registration — The Farm entity records ownerId, region, district, geoLocation, plots, totalArea, and a registrationNumber validated against the GH-<region>-<district>-<serial> pattern.
  • Plot management — The Plot entity tracks area: PlotArea, soilType, irrigationType, currentCrop, and status (PlotStatus: active, fallow, preparation, harvested, abandoned). The richer FarmPlot value object in domain-entities.ts adds a GPS polygon, soil pH, and rotation history.
  • Farmer categories — The FarmerProfile category field is smallholder, commercial, outgrower, or cooperative_member; the economicGroup field ranges subsistencecommercial_large.
  • Farmer identificationFarmerProfile carries optional Ghana Card, MoFA farmer number, and SSNIT number; phone numbers are validated by validateGhanaPhoneNumber.

2. Farm and Crop Production#

Package: @asase/cropsimplemented

The crops library delivers comprehensive crop intelligence for Ghana's major agricultural commodities, from variety selection through field operations, input scheduling, irrigation, labour management, and vegetation health monitoring.

2.1 Crop Registry and Variety Recommendation#

  • GHANA_CROP_REGISTRY — Agronomic profiles for 15+ crop varieties calibrated to Ghanaian growing conditions, covering cocoa (Amelonado, Amazon, hybrid lines), cassava (Afisiafi, CSIR varieties), maize (Obatanpa, Mamaba), rice, yam, oil palm, shea, cashew, and key vegetables. Each profile specifies agro-ecological zone suitability, planting season, nitrogen-fixing status, post-harvest handling requirements, and market profile.
  • Variety query utilitiesgetVarietiesForZone(), getExportEligibleVarieties(), getNitrogenFixingVarieties(), and getVarietiesByCategory() provide targeted lookups to match farmer conditions to appropriate varieties without requiring full registry traversal.
  • recommendVarieties() — Multi-criteria scoring engine — Accepts farmer capacity tier (subsistence, smallholder, commercial), agro-ecological zone, market demand level, and target objectives as inputs; returns ranked variety recommendations with gross margin estimates (revenue, variable cost, and expected profit per hectare) at current market prices. This is the primary tool for MoFA extension officers advising farmers on variety selection.

2.2 Pest and Disease Catalog#

  • PEST_DISEASE_CATALOG — 18+ scientifically documented threat entries covering Ghana's most economically significant crop threats: cocoa swollen shoot virus (CSSV), cassava mosaic disease (CMD), fall armyworm (Spodoptera frugiperda), cocoa pod borer (Conopomorpha cramerella), maize streak virus, rice blast (Magnaporthe oryzae), and black pod disease (Phytophthora palmivora). Each entry includes affected crops, severity level, notifiable status, and intervention options.
  • Threat lookup utilitiesgetThreatsForCrop(), getNotifiableThreats(), getThreatsBySeverity(), getBiocontrolEligibleThreats() — filter the catalog by crop, regulatory notification tier, severity, or eligibility for biological control methods. Notifiable diseases are those that Ghana's regulatory bodies (PPRSD, EPA) require to be reported within a defined period of detection.

2.3 Field Activity Tracking#

  • FieldActivityTracker — Records all field operations with GPS coordinates, equipment used, input quantities, labour hours, and cost data. Activity types span the full crop cycle: land preparation (plowing, ridging, mounding), planting, transplanting, fertilizer application, pesticide spraying, irrigation, harvesting, and post-harvest handling.
  • PHI compliance checkingPhiCheckResult verifies that pesticide applications respect the Pre-Harvest Interval (PHI) — the minimum number of days that must elapse between the last pesticide application and harvest. Spraying within the PHI window creates residue exceedances that fail export quality checks.
  • Plot cost summariesPlotCostSummary aggregates all input and labour costs by plot for farm-level profitability analysis.

2.4 Input Application Scheduler#

  • GHANA_INPUT_PRODUCTS — Catalog of fertilizer and agrochemical products registered in Ghana, with nutrient formulae, application rates, and resistance group classification. Resistance group rotation (shareResistanceGroup()) identifies products in the same chemical class — alternating between resistance groups delays pest resistance development.
  • generateInputSchedule() — Computes the optimal fertilizer and pesticide application schedule for a given crop and growth stage sequence, aligning application windows with stage transitions and weather suitability.
  • getOrganicProducts() — Returns the subset of products certified for organic and GAP (Good Agricultural Practice) certified production, relevant for export compliance and premium market access.

2.5 Irrigation Management#

  • GHANA_IRRIGATION_SCHEMES — Registry of Ghana's formal irrigation infrastructure: the Accra Plains Irrigation Scheme, Kpong Left Bank, Tono Irrigation Project, Vea Irrigation Project, Bontanga Irrigation Scheme, Golinga Irrigation Project, and Dawhenya Irrigation Scheme, with scheme type, command area, and primary crop associations.
  • estimateEToHargreaves() — Estimates reference evapotranspiration (ETo) using the Hargreaves equation from temperature data alone. Evapotranspiration (ET) is the combined water loss from soil evaporation and plant transpiration — the primary driver of crop water demand.
  • computeKcAtDas() — Computes the crop coefficient (Kc) at a given number of days after sowing (DAS) for a specified crop, using growth-stage-adjusted FAO Kc curves. Multiplying Kc × ETo gives crop-specific water demand (ETc).
  • generateIrrigationSchedule() — Produces a full seasonal irrigation schedule as daily entries, accounting for ETo, crop stage Kc, effective rainfall, and soil water-holding capacity.

2.6 Soil Fertility Tracking#

  • CSIR-SRI lab soil test recording — Captures full soil analysis results: pH, organic matter (%), available phosphorus (Mehlich-3), exchangeable cations (K, Ca, Mg, Na), micronutrients (Zn, Fe, Mn, Cu, B), bulk density, cation exchange capacity (CEC), and base saturation. Thresholds are calibrated to CSIR-Soil Research Institute (SRI) critical levels for Ghanaian soils.
  • Nutrient rating — Each nutrient receives a rating (deficient / low / adequate / high / excessive) against SRI thresholds for the target crop, driving fertilizer recommendations.
  • MOFA/SRID fertilizer recommendations — Fertilizer application recommendations follow the Soil Fertility Management guidelines published by the Ministry of Food and Agriculture's Soil Research and Information Division (SRID), expressed as NPK kg/hectare adjusted for test results and crop type.
  • Nutrient depletion tracking — Multi-season records track how nutrient levels change over time, enabling trend analysis to detect progressive soil degradation or improvement.

2.7 Crop Health Monitoring#

  • Satellite vegetation indices — Ingests Sentinel-2 multispectral data to compute NDVI (Normalized Difference Vegetation Index), EVI (Enhanced Vegetation Index), and NDWI (Normalized Difference Water Index) for each monitored field. NDVI measures photosynthetically active biomass: values below 0.15 indicate bare soil; above 0.55 indicates healthy canopy. NDWI detects crop water stress before visible wilting occurs.
  • NDVI health classificationNdviHealthClass categories: bare_soil, sparse_stressed, moderate, healthy, peak_vigor — providing a clear, actionable field health status at each observation.
  • Drone survey integration — Processes drone RGB imagery to complement satellite data at higher spatial resolution, enabling canopy gap analysis and disease symptom mapping at individual-plant scale.
  • Field scout report integration — Ground-truth observations from field scouts are correlated with satellite anomalies to confirm actual conditions, improving alert precision.

2.8 Labour Management#

  • Worker profiles — Track casual and permanent workers with type, status, contact details, and Ghana Card identification.
  • Wage calculationscalculateDailyWage() and calculatePieceRate() compute pay based on the current Ghana Daily Minimum Wage and activity-specific piece rates. The minimum wage constant (GHANA_DAILY_MINIMUM_WAGE_GHS) is maintained as a named constant for simple updates.
  • Labour compliance checkingcheckLabourCompliance() flags violations: sub-minimum-wage payments, underage workers assigned to hazardous tasks (minimum age 18 for hazardous agricultural work), and missing documentation.
  • Seasonal demand forecastingforecastSeasonalLabourDemand() projects labour requirements by activity across the planting, establishment, and harvest periods, supporting advance recruitment planning.

2.9 Mechanization Scheduling#

  • STANDARD_GHANA_EQUIPMENT — Equipment catalog covering tractors, combine harvesters, rice threshers, planters, sprayers, and other implements commonly available through Ghana's Agricultural Mechanization Service Centers (AGSMECs).
  • MechanizationScheduler — Books, tracks, and optimizes equipment deployment across multiple farm locations. Detects scheduling conflicts and computes utilization rates per machine.
  • Route optimizationOptimisedRoute minimizes travel distance and fuel cost when a single machine must service multiple farm locations in sequence.
  • Utilization reportingUtilisationReport tracks actual vs. scheduled usage hours, supporting rental cost recovery and maintenance scheduling.

2.10 Intercropping and Rotation#

  • INTERCROPPING_MATRIX — Compatibility matrix for Ghana's common crop combinations, classifying each pair as beneficial, neutral, or antagonistic based on documented biological mechanisms (nitrogen transfer, pest deterrence, shade tolerance, allelopathy). Ghana's traditional cocoa-plantain-cocoyam agroforestry combination is encoded as beneficial.
  • generateRotationPlan() — Produces multi-season rotation plans prioritized by a specified objective: nitrogen replenishment, disease disruption (break soil-borne pathogen cycles), market diversification (spread income across crops), or income smoothing (stagger harvest revenue across seasons).
  • Rotation plan querygetCompatibleCrops() and getAntagonisticCombinations() provide targeted lookups for planning and validation workflows.

3. Livestock, Poultry, and Aquaculture#

Package: @asase/livestockimplemented

The livestock library covers Ghana's major animal production sectors: small and large ruminants, commercial poultry (broilers and layers), hatchery operations, and feed formulation, with integrated disease surveillance, mortality analytics, and distribution optimization.

3.1 Livestock Registry#

  • GHANA_LIVESTOCK_BREEDS — Profiles for 18+ breeds across cattle (Sanga, White Fulani/Bunaji, N'Dama), sheep (West African Dwarf, Djallonke), goats (West African Dwarf, Sahelian), and pigs, with trypanotolerance ratings, production purpose, and typical performance benchmarks. Trypanotolerance is the ability of some West African cattle breeds (notably N'Dama and West African Shorthorn) to survive and remain productive in tsetse fly zones where Zebu or Bos taurus breeds would succumb to trypanosomiasis.
  • LivestockRegistry — Full individual animal registration with NLIS-compliant IDs (National Livestock Identification System), ear tag numbers, breed, sex, birth date, dam/sire lineage, farm GPS location, and health status. Movement records track transfers between farms or markets. generateNlisId() produces correctly formatted national identifiers.
  • Herd summaryHerdSummary provides species composition, age structure, sex ratio, and health status distribution across the registered herd.

3.2 Vaccination Management#

  • GHANA_VACCINE_CATALOG — 14+ VSD-approved vaccines for cattle (Contagious Bovine Pleuropneumonia/CBPP, Brucellosis, FMD), sheep and goats (Peste des Petits Ruminants/PPR, sheep pox), and poultry (Newcastle Disease, Gumboro/IBD, Marek's Disease, Avian Influenza H5N1). Each entry specifies target species, administration route, cold chain category, booster interval, and VSD registration status.
  • VaccinationManager — Schedules and records vaccinations with cold chain validation, batch traceability, and withdrawal period enforcement. buildInitialSchedule() generates the complete recommended vaccination programme for a newly enrolled animal based on species and age.
  • VSD compliance reportingVsdComplianceReport documents vaccination coverage rates and cold chain adherence for Veterinary Services Directorate inspection, supporting the national disease surveillance programme.
  • Cold chain validationvalidateColdChain() checks that a vaccine lot's storage temperature records are consistent with its cold chain category (frozen at ≤-15°C, refrigerated at 2–8°C, or ambient) before use — invalid cold chain voids vaccine efficacy.

3.3 Feed Formulation#

  • GHANA_FEED_INGREDIENTS — Database of locally available feed ingredients: maize grain, maize bran, wheat offal, rice bran, fish meal, soybean meal, groundnut cake, cotton seed cake, cassava chips, plantain peel, palm kernel cake, and mineral-vitamin premixes. Each ingredient carries proximate analysis data (crude protein, metabolizable energy, crude fibre, fat) and current market price per tonne.
  • NUTRITIONAL_REQUIREMENTS — Breed- and stage-specific nutrient requirements (crude protein, metabolizable energy, calcium, phosphorus, lysine, methionine) for broilers, layers, cockerels, cattle, sheep, and goats at each production phase.
  • FeedFormulationEngine / formulateRation() — Least-cost linear programming ration formulation that meets all nutrient constraints while minimizing ingredient cost. The formulated ration includes a nutrient profile validation, cost per tonne, and ingredient percentages — the core of practical farm feed management in Ghana's context where ready-mixed feeds are expensive.

3.4 Broiler Production Tracking#

  • BROILER_BREED_STANDARDS — Ross 308, Cobb 500, Arbor Acres, and Sasso breed performance standards: target body weight, daily weight gain, cumulative feed intake, and FCR (Feed Conversion Ratio) at each age day from placement to harvest. FCR (kg feed consumed per kg live weight gained) is the primary efficiency metric for commercial broiler operations; a Ross 308 broiler should achieve approximately 1.65 FCR to day 35.
  • BroilerFlockTracker — Records daily performance metrics: weight sampling, mortality count, feed consumption, and water intake. Calculates daily FCR, cumulative FCR, and European Production Efficiency Factor (EPEF — a combined score of FCR, mortality rate, daily weight gain, and live weight, widely used in West African commercial poultry benchmarking).
  • estimateHarvestDate() — Projects the day a flock will reach target market weight based on current growth trajectory versus breed standard.
  • Stocking density compliancecomputeStockingDensity() verifies that flock count does not exceed welfare and biosecurity limits per square metre of house floor area.

3.5 Layer Farm Management#

  • LAYER_STRAIN_STANDARDS — ISA Brown, Lohmann Brown, Hy-Line Brown, and Nick Chick strain production standards by flock age week: target hen-day production percentage, peak production week, feed intake, and expected egg weight trajectory.
  • LayerFarmManager — Tracks weekly production records: eggs produced, mortality, feed consumed, and egg weight sampling. Computes Hen-Day Production (HDP — eggs laid per day as a percentage of live hens on that day) and Hen-Housed Production (HHP — eggs laid as a percentage of hens placed at the start, capturing cumulative mortality impact).
  • GHANA_EGG_GRADE_THRESHOLDS — Ghana Standards Authority grade thresholds: Grade A (≥60g), Grade B (50–59g), Grade C (40–49g), pullet/small (<40g). classifyEggWeight() assigns grades automatically.
  • Lighting managementgenerateLightingRecommendation() computes the optimal artificial light programme by flock week, supplementing natural photoperiod to maintain consistent laying stimulus and prevent premature production decline.

3.6 Hatchery Operations#

  • GHANA_HATCHERY_BENCHMARKS and INCUBATION_TARGETS — Industry benchmark hatchability percentages and incubation parameter targets (dry-bulb temperature, wet-bulb temperature/humidity, turning frequency, CO2 ppm) for setting and hatching phases of broiler and layer eggs.
  • HatcheryManager — Manages the complete hatchery workflow: egg lot intake with fertility assessment, setter machine loading, incubation monitoring with alert generation for out-of-range readings, candling records (identifying clear, dead-germ, and cracked eggs by day 7 and day 18), transfer to hatcher, and hatch result recording.
  • Performance metricscomputeHatchPerformance() calculates hatchability of fertile eggs, hatchability of eggs set, and fertility rate from lot and batch records. computePasgarScore() calculates the Pasgar score — a standardized 10-point chick quality assessment widely used in commercial hatcheries to evaluate day-old chick vigour, navel healing, leg straightness, and feather development before dispatch.
  • classifyChickQuality() — Classifies chicks as Grade A (prime), Grade B (passable), or Reject based on Pasgar score, enabling quality-segregated dispatch to farms.

3.7 Disease Surveillance#

  • GHANA_DISEASE_PROFILES — Disease profiles for Ghana's notifiable and economically significant livestock diseases, with OIE List A status, affected species, transmission routes, clinical signs, mortality rates, and statutory notification timelines. OIE List A diseases (now WOAH Notifiable Diseases) are transboundary diseases of serious socioeconomic or public health consequence requiring compulsory notification to the World Organisation for Animal Health.
  • DiseaseSurveillanceSystem — Records incident reports, tracks outbreak progression, and manages movement restrictions and quarantine zones. computeOutbreakSeverity() classifies an outbreak as minor, moderate, serious, or critical based on case count, species affected, and spread rate.
  • generateWahisNotification() — Produces a structured WAHIS (World Animal Health Information System) notification for reportable outbreaks, pre-formatted for submission to Ghana's VSD and onward reporting to the OIE/WOAH international reporting system.

3.8 Mortality and Morbidity Analytics#

  • GHANA_MORTALITY_BENCHMARKS — National and industry benchmarks for acceptable mortality rates by species, production system, and season (Harmattan dry season typically elevates respiratory disease mortality).
  • MortalityMorbidityService — Records mortality events (with root cause categorization: disease, predation, management, unknown) and morbidity episodes, computing cumulative mortality rates and comparing them against benchmarks.
  • classifyMortalityRate() — Classifies a mortality rate as normal, elevated, or critical relative to the applicable Ghana industry benchmark.
  • computeEpef() — Calculates the European Production Efficiency Factor for a broiler flock, the composite KPI used across West African commercial poultry to rank farm performance.
  • Root cause analysisRootCauseAnalysis identifies recurring mortality causes across multiple flocks or time periods, surfacing management patterns (e.g., ventilation failures correlating with respiratory mortality peaks).

3.9 Poultry House Environment#

  • HouseEnvironmentController — Monitors temperature, relative humidity, CO2, NH3 (ammonia), litter moisture, and lighting levels inside poultry houses. evaluateEnvironment() assesses all readings against species- and phase-specific targets simultaneously, returning an EnvironmentAssessment with alerts sorted by severity.
  • computeThi() — Calculates the Temperature-Humidity Index (THI), a composite heat stress indicator combining dry-bulb temperature and relative humidity. Poultry enter heat stress at THI >27 and severe stress at THI >31. classifyThi() returns a heat stress severity category.
  • computeMinVentilationRate() and estimateAirChangesPerHour() — Compute the minimum ventilation rate and air change frequency needed to control CO2 and NH3 below welfare limits, driving fan controller commands.
  • Actuator commandsActuatorCommand outputs control signals for fans, heaters, foggers, and curtains, enabling integration with physical climate control hardware or SCADA systems.

3.10 Poultry Distribution Optimization#

  • GHANA_ROAD_DISTANCES_KM and GHANA_TRANSIT_TIMES_HOURS — Pre-computed road distance and travel time matrices between Ghana's major poultry distribution nodes (Accra, Kumasi, Tamale, Cape Coast, Tema, Bolgatanga, and others), enabling rapid route cost estimation without live mapping APIs.
  • PoultryDistributionOptimizer — Optimizes distribution routes for live birds, dressed chicken, and eggs across the distribution network, balancing transport cost, transit time, cold chain requirements, and vehicle capacity.
  • Live bird welfare complianceLIVE_BIRD_WELFARE_LIMITS and checkLiveBirdWelfare() verify that journey duration, stocking density in crates, and temperature exposure remain within Ghana's animal welfare guidelines for live bird transport.
  • Cold chain monitoringevaluateTransitTemperature() checks whether chilled or frozen product temperatures stayed within safe ranges during transit, and computeFreshnessScore() estimates remaining shelf life based on accumulated temperature exposure.
  • estimateTransportCost() — Calculates transport cost per kg of product from route distance, vehicle type, fuel price, and loading/unloading costs, supporting pricing and logistics decisions.

4. Infrastructure Services#

Package: @asase/infrastructureimplemented

The infrastructure library provides shared platform services consumed by all other Asase libraries: namespaced caching, agricultural document storage, a domain event bus, Prometheus observability metrics, and PostGIS geospatial indexing for farm and facility locations. Because multiple Asase libraries (crops, livestock, cold-chain, supply-chain) all need to cache data, publish events, and store documents, these concerns are centralised here rather than duplicated per library. @asase/infrastructure depends on shared Oshun platform packages — @oshun/cache, @oshun/event-bus, @oshun/logging, and @oshun/metrics — and wraps them with Asase-specific namespacing and configuration.

  • Redis caching (AsaseCacheClient) — Namespaced, TTL-aware cache with key-pattern helpers (asaseKey(), asasePattern()) that prevent key collisions between domains. Predefined TTLs (ASASE_TTL) for common data types: crop prices (15 min), weather data (1 hr), farm profiles (24 hr), regulatory reference data (7 days). Cache prevents repeated calls to expensive external data sources (satellite APIs, weather services, commodity price feeds).
  • MinIO object storage (AsaseStorageService) — S3-compatible object storage organized into purpose-specific buckets: farm imagery, crop health drone surveys, compliance documents (phytosanitary certificates, audit reports), processing records, cold chain logs, and market intelligence reports. buildComplianceKey() generates standardized object paths for regulatory document retrieval. Pre-signed URL generation enables time-limited direct download without exposing storage credentials.
  • Domain event bus — Typed event bus with topic hierarchy covering all Asase domains: crop cycle events (CropsCycleStartedEvent, CropsHarvestRecordedEvent, CropsPestAlertEvent), cold chain events, livestock events, processing events, and market price events. The event bus ASASE_TOPICS and ASASE_TOPIC_PATTERNS constants enable wildcard subscriptions (e.g., subscribe to all livestock events with one handler).
  • Prometheus metrics — Domain-specific metric definitions for observability: crop yield per hectare, livestock mortality rate, cold chain temperature deviation count, processing batch throughput, and supply chain delivery latency. These metrics feed Grafana dashboards for operational monitoring.
  • PostGIS geospatial indexing — Farm polygon boundaries, facility locations, and delivery route geometries stored as PostGIS geometry types for efficient spatial queries (e.g., "find all farms within 50 km of Kumasi Cold Store that grow cassava").

5. Processing and Manufacturing#

Package: @asase/processingimplemented

The processing library models food manufacturing operations as a digital twin — a software replica of a physical processing plant that can simulate throughput, schedule production runs, and track batch execution against recipes. It applies across all 19 Asase business units, from bakeries and cassava-processing facilities to dairy plants and rice mills. The library integrates food-safety standards (HACCP, Ghana FDA LI 1541 labelling rules) and industrial KPIs (OEE, SPC, cost of quality) directly into the production management workflow rather than treating them as separate audit concerns.

5.1 Plant Digital Twin and Production Lines#

  • ProcessingPlantRegistry — Models plants, production lines, and stages with BUSINESS_UNIT_STAGES definitions per business unit. Computes line throughput (computeLineThroughput), stage rates, line energy, and CIP duration, and finds the bottleneck stage with findBottleneckStage.
  • Production schedulingProductionScheduler builds shift-based schedules with allergen-aware Clean-In-Place (CIP) sequencing (determineCipLevel, requiresAllergenCip), priority scoring, and constraint-violation detection.

5.2 Raw Material, BOM, and Batch Execution#

Before production can start, incoming raw materials must be assessed, bills of materials must be checked against inventory, and the execution must be tracked with enough detail to support a product recall if needed. These three concerns — intake quality, materials explosion, and batch traceability — are handled together in this group.

  • Raw material receivingRawMaterialReceivingService with GHANA_RAW_MATERIAL_PROFILES, quality-check evaluation, and grading decisions on intake.
  • BOM explosionBomExplosionService explodes a production plan against inventory levels, producing procurement requisitions with priorities and ingredient substitution suggestions (GHANA_INGREDIENT_SUBSTITUTIONS).
  • Batch executionBatchExecutionEngine records stage execution, ingredient additions, and parameter readings, classifying deviation severity against recipe specifications.
  • Batch genealogyBatchGenealogyTracker links input lots to finished lots for trace-back and trace-forward (TraceabilityReport).

5.3 Recipes and Nutritional Labeling#

Ghana's Food and Drugs Authority requires processed foods to carry nutritional labels compliant with LI 1541. The recipe and labelling system computes those labels from actual ingredient formulations using Ghana's published food composition table, rather than relying on generic databases that may not reflect local ingredients.

  • RecipeManagerGHANA_STANDARD_RECIPES, ingredient-balance validation, recipe scaling, expected-output computation, and undeclared allergen detection.
  • NutritionalLabelingEngine — Computes NutritionFacts from the GHANA_FOOD_COMPOSITION_TABLE using the Atwater energy method, percentage of GHANA_DAILY_REFERENCE_INTAKES, and Ghana FDA labeling-rule (LI 1541) compliance.

5.4 OEE, SPC, and Cost of Quality#

These three tools together give plant managers a complete picture of operational efficiency. OEE (Overall Equipment Effectiveness) tells you how well each machine is utilised versus its theoretical maximum. SPC (Statistical Process Control) tells you whether a production process is in statistical control or drifting out of spec. Cost of Quality assigns a financial figure to quality failures, distinguishing prevention costs from failure costs to guide where improvement effort pays off most.

  • OEEOEEEngine computes Overall Equipment Effectiveness, the six big losses, and Pareto loss analysis.
  • Statistical Process ControlSPCService builds X-bar/R, P, and C control charts, applies the WECO rules, and computes process capability (Cp/Cpk).
  • Cost of QualityCOQReportingService tracks prevention, appraisal, internal-failure, and external-failure costs against GHANA_COQ_BENCHMARKS with trend and variance analysis.

5.5 Energy, Utilities, and Maintenance#

Energy is one of the largest variable costs in Ghanaian food processing. The GHANA_UTILITY_RATES constants reflect current ECG (Electricity Company of Ghana) tariff bands and industrial water rates. The solar-feasibility and biomass-substitution analyses are particularly relevant in Ghana's context, where industrial electricity costs have risen sharply and many processing facilities are in agro-zones with good solar irradiance or access to biomass waste from their own production.

  • Utility monitoringUtilityMonitoringService (GHANA_UTILITY_RATES, GHANA_UTILITY_BENCHMARKS) measures electricity, water, and fuel use and rates efficiency against benchmarks.
  • Energy efficiencyEnergyEfficiencyAnalytics scores specific energy consumption, heat-recovery opportunities, solar feasibility, and biomass substitution.
  • Predictive maintenancePredictiveMaintenanceService uses ISO 10816 vibration zones, EWMA trending, and Weibull failure probability to schedule maintenance windows.
  • Yield and wasteYieldWasteTracker records production runs and loss entries against GHANA_YIELD_BENCHMARKS, identifying primary loss drivers.

6. Cold Chain Management#

Package: @asase/cold-chainimplemented

Cold chain refers to the temperature-controlled supply chain from farm or processing facility through transport to retail. Ghana loses significant quantities of perishable produce (tomatoes, pepper, fish) to cold chain gaps; managing this intelligently is central to the platform's value proposition.

6.1 Facilities and Temperature Monitoring#

  • ColdStorageFacilityRegistry — Cold rooms and refrigeration equipment with FACILITY_TEMPERATURE_RANGES, refrigerant tracking (REFRIGERANT_PROPERTIES, CO₂-equivalent computation), and Ghana Energy Commission / Ghana FDA compliance status.
  • TemperatureMonitoringService — Real-time sensor monitoring with GHANA_PRODUCT_TEMP_PROFILES, zone thresholds, breach detection, rolling statistics, and excursion alarms by severity.
  • Grain storage monitoringGrainStorageMonitor uses the Chung-Pfost equilibrium-moisture model and dewpoint to classify storage hotspots and recommend aeration.

6.2 Warehousing, Inventory, and Receipts#

  • Cold room inventoryColdRoomInventoryService tracks product lots, storage positions, pick lists, and shelf-life status.
  • Warehouse managementWarehouseManager validates lot intake against COCOBOD grade-I moisture and defect limits and schedules fumigation.
  • Inventory valuationInventoryValuationEngine computes weighted-average and FIFO cost, market value, and quality write-downs.
  • Warehouse receipts (GCX)WarehouseReceiptManager issues Ghana Commodity Exchange warehouse receipts with grade certification, storage-fee accrual, pledges, and transfers — enabling commodity-backed credit.

6.3 Transport, Routing, and Energy#

  • Transport fleetTransportFleetManager manages refrigerated vehicles, compartments, GPS tracking, and geofence alerts.
  • Last-mile trackingLastMileColdChainTracker models insulated-box ice pack depletion (latent-heat physics) for rider deliveries.
  • Route optimizationColdChainRouteOptimizer plans temperature-aware delivery routes using Ghana traffic profiles and compartment-temperature estimation.
  • Energy optimizationEnergyOptimizationEngine analyzes compressor duty cycles, defrost schedules, and door infiltration against the ECG tariff. BackupPowerManager plans generator and battery resilience around Ghana grid outages ("dumsor").

6.4 Loss Quantification and Compliance#

  • Post-harvest lossPostHarvestLossEngine quantifies weight, pest, and spoilage losses and evaluates storage-technology investments.
  • Excursion analyticsExcursionAnalyticsEngine computes Mean Kinetic Temperature and cumulative time-temperature exposure to drive disposition decisions.
  • Compliance documentationComplianceDocumentGenerator renders temperature records, chain-of-custody documents, and excursion reports.

7. Supply Chain and Logistics#

Package: @asase/supply-chainimplemented

The supply-chain library covers the commercial flow of agricultural products from source to buyer: procurement, outgrower management, contract farming, distribution network optimisation, commodity price intelligence, and demand forecasting. Ghana's supply chain is particularly complex: outgrower schemes link large processing companies to thousands of smallholder farmers under formal contracts; Tema and Takoradi ports are the main import entry points for fertiliser and capital equipment; and road quality varies sharply between regions, making routing decisions non-trivial.

The @asase/core Shipment entity tracks movements using ShipmentStatus values pending, loading, in_transit, at_checkpoint, delayed, delivered, and returned. The TransportMode values reflect Ghana's actual logistics landscape: truck_refrigerated, truck_ambient, motorcycle, bicycle, rail, and vessel.

7.1 Procurement and Sourcing#

  • ProcurementEngine — Supplier scoring/tiering, purchase orders, and import landed-cost computation against GRA_IMPORT_DUTY_RATES, GHANA_IMPORT_LEVIES, and Tema/Takoradi port charges.
  • Outgrower schemesOutgrowerSchemeManager handles farmer enrolment, season plans, input disbursement on credit, extension visits, and harvest settlement with loan recovery.
  • Contract farmingContractFarmingService orchestrates farming contracts with pricing formulas, delivery schedules, penalty/bonus terms, and dispute resolution (internal and DADU mediation tiers).
  • Import managementImportManagementService handles letters of credit, shipping documents, customs entries, and document-completeness checks.

7.2 Supplier Risk and Distribution#

  • SupplierRiskRegistry — Scores suppliers across supply reliability, quality consistency, financial stability, geographic concentration, and climate vulnerability, with alternative-supplier recommendations.
  • Distribution networkDistributionNetworkOptimizer models regional distribution centers, computes EOQ / safety stock / reorder points, and forecasts demand with weighted moving averages and seasonality.
  • Vehicle routingVehicleRoutingEngine plans routes with nearest-neighbour + 2-opt, fuel cost, driver hours-of-service limits, and delivery time windows.
  • Market channelsMarketChannelService manages traditional markets, supermarket chains, institutional (GSFP) channels, and export compliance with volume-discount pricing.

7.3 Delivery, Returns, and Price Intelligence#

  • Delivery proofDeliveryProofService records proof-of-delivery with OTP verification, GPS accuracy checks, invoicing, and credit notes.
  • Returns logisticsReturnsLogisticsService handles recalls, pullbacks, container-deposit returns, waste disposal, and CAPA tracking with FDA notification deadlines.
  • Commodity pricesCommodityPriceService aggregates price submissions across Ghana market locations with IQR outlier detection, VWAP, and a market-basket index.
  • Price forecastingPriceForecastEngine fits ARIMA(1,1,0), Holt-Winters, and linear-trend models, deseasonalising with Ghana seasonal indices and converting CBOT/ICE benchmark quotes to GHS/kg.
  • Import parity & marginsImportParityService computes CIF and landed cost vs. local prices; MarginAnalysisService maps value-chain margins, detects compression points, and recommends transfer pricing.
  • Demand sensingDemandSensingEngine produces demand forecasts with exponential smoothing, price/income elasticities, macro adjustment, and inventory-positioning recommendations.

8. Quality Assurance#

Package: @asase/qualityimplemented

Food safety and quality management in Ghana is governed by multiple overlapping regimes: Ghana FDA licensing, Ghana Standards Authority (GSA) product standards, COCOBOD grading for cocoa, EPA effluent and pesticide standards, and international certification schemes (BRC, ISO 22000, GLOBAL_GAP) required for export markets. The quality library provides a unified framework for managing these obligations across all 19 Asase business units — from recording HACCP critical control points on a production line to triggering a class-2 product recall and notifying FDA.

Quality grading is defined in @asase/core as the QualityGrade enum (premium, grade_a, grade_b, grade_c, reject). Cocoa quality validation uses COCOBOD thresholds via validateCocoaQuality, with moisture ≤ 7.5% required for grade_1.

8.1 HACCP, CCP Monitoring, and Prerequisite Programs#

  • HaccpPlanManager — Hazard analysis, risk-priority computation, CCP decision-tree application, and HACCP compliance scoring against the FDA Ghana required-records list.
  • CcpMonitoringService — Records CCP readings, evaluates deviations, computes pasteurisation F₀, and prompts corrective actions.
  • PrpTracker — Tracks prerequisite programs (sanitation, pest control, water chlorination, food-handler medical certificates) with compliance scoring.

8.2 Laboratory, Contaminants, and Residues#

  • LIMSLimsService manages laboratory samples and tests across microbiological, chemical, and physical disciplines, issuing test certificates.
  • Aflatoxin managementAflatoxinManagementService applies sampling protocols by lot size, rapid-test and HPLC confirmation, and lot disposition against per-market AFLATOXIN_LIMITS_PPB.
  • Pesticide residuePesticideResidueService evaluates residues against EU/Codex/US-EPA MRLs and checks pre-harvest interval compliance.
  • Water qualityWaterQualityService evaluates water tests against GS 175-1 limits with trend analysis.
  • CalibrationCalibrationService manages instrument calibration, uncertainty budgets, and CCP-linked instrument qualification.

8.3 Certification, Recall, and Compliance#

  • AuditsAuditManagementService runs food-safety audits, computes BRC grades, and tracks corrective actions and certification records.
  • CertificationsOrganicCertificationService, ExportCertificationService, and FdaRegistrationService manage organic, export, and Ghana FDA product registration with renewal alerts.
  • RecallsRecallManagementService runs class-based recalls with batch-genealogy tracing, customer notification, recovery-rate computation, and FDA regulatory reports.
  • Environmental & regulatoryEnvironmentalComplianceService tracks EPA permits, effluent/air-emission limits, and waste management; RegulatoryChangeMonitoringService tracks regulatory changes and compliance gaps. LabelComplianceService validates label elements.

9. Export Operations#

Package: @asase/exportimplemented

Ghana's primary export commodities by value include cocoa and cocoa products, gold, oil, and timber. Agricultural non-traditional exports (NTEs) include shea, cashew, fresh and processed fruits, vegetables, and horticulture. This library covers export analysis, documentation, compliance, and buyer management. A particular focus is the EU Deforestation Regulation (EUDR), which requires exporters of cocoa, oil palm, soy, and other commodities to demonstrate that their supply chains are deforestation-free — a compliance requirement that is transforming how Ghanaian exporters source and document their supply chains.

9.1 Export Analysis and Intelligence#

  • Commodity analysis — A commodity export analyzer computes Incoterms cost breakdowns, runs price scenario analysis, and projects export revenue against REFERENCE_BENCHMARK_PRICES_USD_PER_MT.
  • Market scannerExportMarketScanner scores destination-market opportunities using tariff schedules, trade agreements, demand signals, and annual import volumes.
  • Commodity gradingCommodityGradingEngine maps cocoa, cashew, shea, rubber, and palm-oil quality measurements to Ghana export grades.
  • Volume forecastingExportVolumeForecaster projects quarterly export volume with seasonal indices and forward-contract positions.
  • Competitor trackingCompetitorExportTracker analyzes competing origins' market share, price position, and Ghana's competitive advantages.

9.2 Trade Documentation and Compliance#

  • Trade documentsTradeDocumentGenerator generates and validates phytosanitary certificates, certificates of origin, commercial invoices, bills of lading, and packing lists.
  • AfCFTA complianceAfCFTAComplianceEngine computes local value added and change-of-tariff-classification against AfCFTA rules of origin.
  • EU regulationEURegulationTracker assesses EUDR (deforestation-free) compliance, MRL conformity, and novel-food status.
  • Customs dutyCustomsDutyCalculator computes duties and landed cost per destination country with trade-agreement preferences.
  • Export licensingExportLicenseManager tracks COCOBOD, GFZB, and GEPA licenses with quota utilization and renewal-status assessment.

9.3 Buyer Management and Pricing#

  • Buyer CRMExportBuyerCRM scores buyer relationships across payment performance, volume, price premium, retention, and strategic value, with churn-risk assessment.
  • Dynamic pricingDynamicPricingEngine builds cost stacks and price quotes from basis differentials, freight, and margin targets with sensitivity analysis.
  • Contract negotiationContractNegotiationAssistant structures spot, forward, minimum-price, option, and collar contracts and recommends hedging strategies.
  • Logistics optimizationExportLogisticsOptimizer selects transport mode, container type, port, and shipping line with cost/time breakdowns.
  • Certification trackingQualityCertificationTracker monitors export certification schemes with audit checklists and renewal alerts.

10. Agricultural Inputs#

Package: @asase/inputsimplemented

Agricultural inputs — fertilisers, certified seeds, and agrochemicals — are the primary lever for raising smallholder yields in Ghana. The inputs library addresses three structural problems: the cost of inputs is high relative to farmgate prices (making blending and timing advice financially significant); the Ghana government's Planting for Food and Jobs (PFJ) subsidy programme requires accurate tracking of coupon redemptions to prevent leakage; and many inputs (especially agrochemicals) are sold counterfeit or at substandard quality. This library provides the intelligence layer for managing inputs from source through distribution to farm-level advice, including farmer credit facilitation for the financing schemes most relevant to Ghanaian smallholders (GIRSAL-guaranteed, PFJ, COCOBOD BSCA, outgrower, VSLA, and FBO).

10.1 Fertilizer Intelligence#

  • Blend optimizationFertilizerBlendOptimizer builds fertilizer blends from base nutrient requirements adjusted for soil test results and agro-ecological zone, with nutrient-use and cost efficiency metrics.
  • Soil nutrient mappingSoilNutrientMapper classifies nutrient deficiencies against CSIR-SRI baseline profiles and satellite vegetation indices (NDVI, NDRE), producing regional deficiency maps.
  • Cost analysisFertilizerCostAnalyzer computes CIF landed cost, ex-warehouse Accra price, transport cost, and regional price maps.
  • Organic fertilizerOrganicFertilizerAdvisor recommends organic amendments and legume systems with cost-benefit and NPV analysis.
  • Subsidy trackingFertilizerSubsidyTracker tracks the Planting for Food and Jobs (PFJ) program: coupon batches, redemption, budget projection, and leakage-risk classification.

10.2 Seed and Agrochemical Intelligence#

  • Seed performanceSeedPerformanceDatabase holds the CSIR/Ghana variety catalogue (maize, sorghum, millet, cowpea, soybean, groundnut, rice) with disease-resistance scoring and zone ranking.
  • Seed multiplicationSeedMultiplicationTracker plans certified-seed production, demand forecasting, inventory balance, and regional distribution.
  • Agrochemical guidanceAgrochemicalGuidanceEngine uses the EPA Ghana product catalogue for PHI/MRL compliance and resistance-rotation advice.
  • Integrated pest managementIntegratedPestManagementAdvisor computes economic injury levels and thresholds and recommends biological and cultural controls.
  • Agrochemical safetyAgrochemicalSafetyModule computes water-body buffer zones, re-entry intervals, and incident-notification deadlines.

10.3 Distribution, Credit, and Quality#

  • Input distributionInputDistributionNetworkManager models agro-dealer hubs, road types, delivery cost, and seasonal accessibility.
  • Farmer creditFarmerCreditFacilitator computes credit scores and loan recommendations across GIRSAL-guaranteed, PFJ, COCOBOD BSCA, outgrower, VSLA, and FBO financing schemes, with mobile-money fee computation.
  • Input bundlesInputBundleOptimizer prices crop-specific input bundles by farm-size tier with PFJ subsidy and financing eligibility.
  • Import substitutionImportSubstitutionAnalyzer builds investment cases for local fertilizer blending, biopesticide production, and seed multiplication.
  • Input quality assuranceInputQualityAssurance runs batch testing, counterfeit-detection protocols, and supplier audits against fertilizer, pesticide, and seed quality standards.

11. Market Intelligence#

Package: @asase/market-intelimplemented

Price information is notoriously thin in Ghanaian agricultural markets: smallholders sell at whatever the first trader offers, processors cannot easily benchmark what they pay, and exporters must convert between international CBOT or ICE futures benchmarks and local GHS farmgate prices. The market intelligence library aggregates and analyses commodity prices across Ghana's 12 major market centres, builds econometric forecasting models calibrated to Ghana's seasonal patterns, and provides continental trade analysis for the AfCFTA opportunity. The Ghana Cedi (GHS) exposure calculators are especially important in Ghana's context, where sharp currency depreciations have repeatedly compressed processor and exporter margins on USD-denominated commodities.

11.1 Price Tracking and Forecasting#

  • Commodity pricesCommodityPriceTracker normalises prices to per-MT, applies seasonal adjustment, and computes transaction cost and price-history summaries against BENCHMARK_PRICES_USD_PER_MT.
  • Farmgate pricesFarmgatePriceMonitor estimates consumer price from farmgate (and the reverse) using regional transport cost and marketing margins, computing marketing efficiency.
  • Price forecastingPriceForecastingEngine fits ARIMA, GARCH-volatility, and Holt-Winters models with ensemble weighting and scenario analysis.
  • Price transmissionPriceTransmissionAnalyzer estimates long-run elasticity and asymmetric error-correction transmission, computes the Lerner index, and identifies market-chain bottlenecks.
  • Cedi exposureCediExposureCalculator projects exchange-rate scenarios and quantifies FX pass-through on import costs and export revenue.

11.2 Supply, Demand, and Competition#

  • Supply-demand modelingSupplyDemandModeler builds commodity balance sheets, interprets stock tightness, and applies supply shocks.
  • Competitor analysisCompetitorAnalysisEngine computes the Herfindahl-Hirschman Index, market structure, and competitor threat scores.
  • Consumer trendsConsumerTrendAnalyzer tracks per-capita consumption, urban/rural gaps, import dependency, and import-substitution opportunities.
  • Price elasticityPriceElasticityCalculator computes point/arc elasticity, fits log-linear demand, and computes cross-price and consumer-surplus effects.
  • SeasonalitySeasonalityProfiler decomposes price series and scores seasonal trading opportunities against the Ghana planting calendar.

11.3 Continental Trade Intelligence#

  • AfCFTA opportunityAfCFTAOpportunityScanner scores African-market opportunities by tariff advantage, market size, logistics, and non-tariff barriers.
  • Regional trade flowRegionalTradeFlowMapper scores trade corridors, finds least-cost corridors, and quantifies NTB cost burden.
  • Market entryMarketEntryAssessor scores target markets across size, growth, competition, regulatory complexity, and logistics feasibility.
  • Trade intelligence dashboardTradeIntelligenceDashboard detects price/volume/unit-value anomalies and computes mirror-data gaps and smuggling-risk indices.
  • Policy simulationPolicyImpactSimulator simulates export bans, levies, price ceilings, buffer-stock releases, and tariff changes, with stakeholder-impact assessment.

12. Retail and QSR Operations#

Package: @asase/retailimplemented

Asase's retail-facing business units — bakeries, cafes, QSR chains, and institutional caterers — face a distinctive set of operational challenges in Ghana's urban food-service market: high Mobile Money payment volumes, dependence on the Ghana School Feeding Programme (GSFP) for institutional catering revenue, rapid expansion of food-delivery platforms in Accra and Kumasi, and labour scheduling requirements under Ghana's labour law. This library provides operations intelligence for these business units, covering everything from site selection through franchise management, menu engineering, waste reduction, and customer loyalty.

12.1 Location, Franchise, and Operations#

  • QSR locationQSRLocationAnalyzer scores candidate sites across population density, income affordability, traffic, competitor proximity, real-estate feasibility, and zone suitability, with revenue and breakeven estimates.
  • Franchise managementFranchiseManagementSystem computes tiered royalties, brand-standard audit scores, performance indices, and franchisee onboarding stages.
  • POS integrationRestaurantPOSIntegrator ingests transactions and computes daypart, product-mix, channel, and payment breakdowns including Mobile Money adoption.
  • Staff schedulingStaffSchedulingOptimizer builds compliant schedules against Ghana labour law and the QSR wage schedule from hourly demand forecasts.
  • Quality auditQualityAuditSystem runs HACCP and mystery-shopper audits against Ghana FDA critical limits with corrective actions.

12.2 Menu, Cost, and Delivery#

  • Menu engineeringMenuEngineeringAnalyzer classifies menu items (star/plough-horse/puzzle/dog) by contribution margin and popularity; RecipeCostCalculator computes recipe cost and suggested selling price; MenuLocalizer scores cultural fit and Halal compliance.
  • Dynamic pricingDynamicMenuPricer adjusts menu prices for demand, cost pass-through, competitor ceilings, and margin floors.
  • Inventory wasteInventoryWasteTracker classifies waste severity, identifies root causes, and recommends reductions.
  • DeliveryDeliveryLogisticsEngine batches and routes orders across Accra zones with rider earnings; DeliveryPlatformIntegrator computes third-party platform commissions and channel profitability.

12.3 Catering and Loyalty#

  • Institutional cateringInstitutionalCateringManager manages catering contracts, menu-cycle compliance, bulk procurement, and Ghana School Feeding Programme (GSFP) subsidy computation.
  • Central kitchenCentralKitchenPlanner plans production batches, distribution runs, cold-chain compliance, and outlet cost allocation.
  • Customer loyaltyCustomerLoyaltyEngine runs a tiered points program with RFM scoring, churn-risk classification, customer-lifetime-value estimation, and personalised promotions.

13. Financial Models#

Package: @asase/financialsimplemented

The financials library models the economics of the Asase conglomerate from first principles: each of the 19 business units has its own startup cost profile, unit economics, and working-capital cycle. The library then consolidates these into ten-year income statements, balance sheets, and cash flows, with scenario planning across commodity price, FX, weather, and policy assumptions — a structure that mirrors how an institutional investor or development-finance institution (DFI) would evaluate a multi-business-unit agri-conglomerate.

The library is standalone (no @asase/core dependency) by design: financial models should be stable even as operational data structures evolve, and they are often evaluated independently of the full platform.

13.1 Unit and Operational Economics#

  • Startup costStartupCostEstimator builds cost line items per business unit and scale, estimating direct jobs, year-1 revenue, and payback.
  • Unit economicsUnitEconomicsModeler computes contribution margin, breakeven volume, and EBIT with sensitivity scenarios.
  • Farm economicsFarmEconomicsCalculator computes gross margin, cost-per-kg, and breakeven yield across agro-ecological zones and mechanisation levels.
  • Processing economicsProcessingEconomicsAnalyzer compares processing tiers with capacity-utilisation sensitivity.
  • Working capitalWorkingCapitalModeler builds crop working-capital profiles and financing-cost breakdowns.

13.2 Corporate Finance and Investment#

  • Consolidated projectionConsolidatedProjectionEngine builds ten-year income statements, balance sheets, and cash-flow statements per business unit and consolidates them with key ratios.
  • Capex planningCapexPlanningModule ranks capex projects by NPV, IRR, payback, and strategic score, and allocates funding.
  • Debt capacityDebtCapacityAnalyzer computes debt-capacity metrics and compares lender term sheets.
  • Tax optimizationTaxOptimizationModeler models tax regimes, intra-group transactions, capex tax shields, and group effective tax rate.
  • Investor returnsInvestorReturnCalculator computes IRR, MOIC, and exit-waterfall distributions.

13.3 Scenario, Risk, and Impact#

  • Synergy valuationSynergyValuationEngine values cross-unit synergies with realisation-risk adjustment.
  • Scenario planningScenarioPlanner runs Monte Carlo simulations across commodity, FX, weather, and policy assumptions.
  • BenchmarkingBenchmarkingModule computes valuation multiples against a peer universe.
  • FX riskFXRiskQuantifier computes per-unit FX exposure and hedge recommendations.
  • Impact metricsImpactMetricsCalculator computes smallholder, employment, import-substitution, and food-security impact, plus an IRIS+ score and SDG alignment.

14. SOTA Technology#

Package: @asase/sotaimplemented

The SOTA library adds state-of-the-art sensing, inference, and traceability capabilities that augment the operational libraries but sit above them. It is standalone (no @asase/core dependency) so it can be deployed independently or updated without affecting the core domain model. The capabilities span five technology layers: satellite remote sensing (Sentinel-2 data processed to vegetation indices), drone precision agriculture (GCAA-compliant flight planning and spray prescription), computer-vision quality grading for cocoa, cashew, and grain, blockchain-based supply-chain traceability for EUDR and consumer provenance, and ML/RL models for yield prediction and crop planning. The IoT cold-chain monitoring module bridges sensor telemetry into the cold- chain domain's excursion analytics.

14.1 Satellite and Drone#

  • Satellite monitoringSatelliteCropMonitor computes vegetation indices (NDVI, EVI, NDWI, SAVI), estimates LAI, and classifies crop health; CropAreaEstimator classifies land cover and estimates crop area; DeforestationAlertSystem detects forest loss for EUDR compliance; FloodDroughtEarlyWarning assesses flood and drought risk.
  • Drone operationsDroneSurveyPlanner builds GCAA-compliant flight plans; DroneSprayingController builds and validates spray-prescription zones; PlantCountAnalyzer estimates plant count, canopy gaps, and replanting needs.

14.2 Computer Vision Grading#

  • CacaoBeanGrader — Computes the fermentation index and assigns ICCO cocoa grades with price premiums.
  • CashewKernelClassifier — Assigns cashew W-grades and AFI grades from defect and colour analysis.
  • GrainQualityAnalyzer — Classifies grain moisture, estimates mycotoxin and aflatoxin risk, and computes storage life.

14.3 Blockchain, IoT, and ML#

  • Blockchain traceabilityBlockchainTraceabilityLedger builds a hash-linked provenance ledger with traceability scoring, EUDR compliance, and consumer QR content; SmartContractPaymentSystem triggers contract payments.
  • IoT cold chainIoTColdChainMonitor processes sensor batches and detects excursions; ColdChainAnalyticsDashboard computes temperature stability, energy use, and predictive maintenance.
  • ML and RLMLYieldPredictor predicts yield from nutrient, water, soil, and climate-suitability scores; CropDiseasePredictor forecasts disease outbreak risk; RLCropPlanningAgent generates optimal multi-season crop plans; RLResourceAllocator allocates resources by marginal return.

15. Geolocation and Mapping#

Package: @asase/core (implemented)

Geolocation is split across two packages based on their dependencies. Pure-TypeScript utilities that carry no external dependencies live in @asase/core (geo-utils.ts, domain-services.ts) — they can be used in any context including server-side batch jobs and field-app offline mode. Spatial queries that require a live database connection (plot boundaries, market catchment areas, delivery routes stored as PostGIS geometry) live in @asase/infrastructure (AsaseGeospatialService).

  • Ghana bounds validationisWithinGhanaBounds checks that GPS coordinates fall within Ghana (≈4.5°–11.2°N, 3.5°W–1.3°E); validateGhanaCoordinates adds latitude/longitude/altitude/accuracy checks.
  • Haversine distancehaversineDistanceKm computes great-circle distance between two coordinates in kilometres.
  • DMS conversiontoDms converts decimal degrees to Degrees-Minutes-Seconds for field use with GPS devices.
  • Midpoint calculationmidpoint returns the geographic midpoint between two locations.
  • Region geolocationGeolocationService.getRegionForCoordinate maps a GPS coordinate to a Ghana administrative region using region bounding boxes; getZoneForCoordinate returns the agro-ecological zone.
  • Market distancefindNearestMarkets ranks the nearest market centres with road-distance and travel-time estimates.
  • PostGIS geospatial@asase/infrastructure provides GHANA_REGION_INFO, GEO_SQL, plot-boundary / facility-location / delivery-route geometry, and market-catchment queries.
  • Ghana phone numberformatGhanaPhoneNumber normalises to +233 form; identifyGhanaOperator returns MTN, Vodafone, AirtelTigo, Glo, or Other.

16. Stakeholder Management#

Package: @asase/core (implemented)

Ghana's agricultural value chain involves a diverse cast of actors — from subsistence smallholders to national commodity exporters, from rural banks to EPA inspectors. Each actor type carries different regulatory obligations, data requirements, and system permissions. Encoding these as a discriminated union (rather than a single generic User type) lets the compiler enforce stakeholder-specific rules at compile time and makes compliance functions precise.

16.1 Stakeholder Types#

Stakeholder is a discriminated union of eight profile types, each extending a BaseStakeholder (id, role, name, contact, kycVerified, onboardedAt):

Stakeholder (role) Profile sub-classifier
Farmer (farmer) category: smallholder / commercial / outgrower / cooperative_member; economicGroup: subsistencecommercial_large
Processor (processor) category: primary / secondary / tertiary
Distributor (distributor) tier: national / regional / district / last_mile
Retailer (retailer) retailerType: supermarket / mini_mart / market_stall / hawker / agro_dealer / cooperative_shop
Exporter (exporter) destinationMarkets, GEPA/FDA/export licence numbers, AGOA-beneficiary flag
Input supplier (input_supplier) supplierType: national_distributor / regional_distributor / agro_dealer / manufacturer
Financier (financier) financierType: microfinance / rural_bank / commercial_bank / fintech / agri_insurer / development_finance
Regulator (regulator) bodyType: Ghana_FDA / GSA / PPRSD / VSD / COCOBOD / GEPA / GRA / MOFA / EPA / NIA / Local_Government

16.2 Compliance Utility Functions#

  • Type guardsisFarmer, isProcessor, isDistributor, isRetailer, isExporter, isInputSupplier, isFinancier, isRegulator.
  • isFdaRegulated(stakeholder) — Returns true for processors, retailers, and exporters requiring FDA Ghana oversight.
  • requiresPprsdCompliance(stakeholder) — Returns true for input suppliers and for retailers that sell agrochemicals.
  • getStakeholderDisplayName(stakeholder) — Formats "<name> (<role>)".
  • The business-unit-level helpers requiresFdaLicence and requiresColdChainTracking (see Section 17) operate on BusinessUnitConfig rather than on stakeholders.

17. Business Unit Configurations#

Package: @asase/core (implemented)

Type-safe configuration interfaces for all 19 Asase business units. Each unit is represented as a discriminated union type capturing its specific operational parameters, regulatory bodies, capacity metrics, and reporting requirements.

Every config interface carries a type discriminant (used for TypeScript type narrowing) and most carry certifications (a QualityCertification[] array) and channels (a MarketChannel[] array). The table below shows the key unit-specific fields for each of the 19 business units. Helper functions requiresColdChainTracking and requiresFdaLicence take a BusinessUnitConfig and return boolean — making regulatory gate logic a single function call rather than a scattered set of if statements.

# Config interface Key fields
1 BakeryConfig ovenCount, dailyCapacityKg, flourSource, fdaLicenceType
2 CafeConfig seatingCapacity, offersDelivery, cuisineType, fdaLicenceType
3 ProcessedFoodsConfig monthlyCapacityTonnes, productCategories, fdaLicenceType
4 PlantFarmsConfig totalAreaHectares, operatingRegions, primaryCrops, hasOutgrowerScheme, outgrowerFarmerCount
5 AquacultureConfig waterVolumeCubicMeters, species, pondCageCount, annualProductionTonnes, hasProcessingFacility
6 ColdChainConfig storageInstallations, refrigeratedTrucks, insulatedVans, transitInsuranceValueGhs
7 ExportProcessingConfig destinationMarkets, phytosanitaryBody, hasFumigationChamber, annualExportTonnes, exportLicenceNumber
8 AnimalFeedConfig dailyMillCapacityTonnes, feedTypes, pprsdRegistered, annualProductionTonnes
9 InstitutionalCateringConfig programmeCount, dailyMealCapacity, sectors, includesNutritionAssessment
10 AgriculturalInputsConfig skuCount, stocksAgrochemicals, stocksCertifiedSeeds, distributionRegions, agrodealerCount
11 BeveragesConfig dailyCapacityLitres, categories, fdaApproved
12 PoultryConfig broilerBirdsPerCycle, layingHens, eggsPerDay, slaughterCapacityPerHour, hasHatchery
13 DairyConfig dailyMilkCollectionLitres, dailyProcessingCapacityLitres, products, pasteurisationMethod
14 EdibleOilsConfig extractionMethod, oilCrops, refineryCapacityTonnesPerDay, sellsByProducts
15 RiceMillingConfig dailyMillingCapacityTonnes, millingType, hasParboilingUnit, byProducts
16 SpicesConfig spiceCategories, hasDryingFacility, hasMillingFacility, targetMoisturePercent
17 CassavaProcessingConfig dailyCapacityTonnes, products (gari, fufu_flour, starch, cassava_chips, lafun, kokonte), hcnTestedForExport
18 QsrChainsConfig outletCount, outletCities, averageDailyCoversPerOutlet, hasCentralKitchen, isFranchise
19 FertilizerConfig categories, storageCapacityTonnes, distributionRegions, hasBlendingUnit, pprsdRegistered

BusinessUnitConfigMap maps each BusinessUnit enum value to its config type, and ConfigForBU<T> indexes it. Type guards (isBakeryConfig, etc.) and the helpers requiresColdChainTracking, requiresFdaLicence, and getMarketChannels operate on the union.

Sobolo is a Ghanaian beverage made from dried hibiscus flowers (Hibiscus sabdariffa); asaana is a fermented corn drink. Gari is a granular fermented cassava product — a West African staple produced by fermenting, pressing, and frying grated cassava. (The BeveragesConfig categories field uses the values water, juices, carbonated, energy, dairy_drinks, and alcohol; traditional drinks such as sobolo and asaana are produced under those categories.)


18. Audit Trail and Compliance#

Package: @asase/core (implemented)

Export markets, Ghana FDA, and international certification schemes all require auditable records of who changed what, when, and why. The audit trail is implemented as an event-sourced log — every change produces an immutable event rather than overwriting data in place. The ComplianceTag values on each event identify which regulatory framework the event is relevant to, making it straightforward to generate a Ghana FDA inspection report or a COCOBOD-tagged audit trail without re-processing the full event log.

  • Event-sourced audit logAuditTrailService produces immutable AuditEvents recording actor (type system / worker / manager / api_integration / regulatory_inspector, plus id, name, optional IP), action, resourceType, resourceId, businessUnit, before/after state, changed fields, compliance tags, reason, and correlation ID. Event IDs are EVT-<timestamp>-<sequence>.
  • Pluggable storage adapterAuditStorageAdapter interface with an in-memory implementation (InMemoryAuditAdapter), allowing production adapters to be plugged in.
  • Query and reportingrecord, recordCreate, recordUpdate (computes changed fields by JSON diff), query, getHistory, and getComplianceEvents support compliance reporting by actor, resource, date range, and compliance tag.
  • Compliance tagsComplianceTag values EU_EXPORT, US_FDA, AGOA, COCOBOD, GHANA_FDA, GSA_CERTIFIED, HACCP_CCP, ISO22000, GLOBAL_GAP identify the regulatory framework each event relates to.

19. Applications#

Five purpose-built application packages live under apps/asase/. Each is a TypeScript library with src/ modules and Vitest specs. These are the consumer-facing surfaces that assemble library capabilities into user workflows — the API gateway for external integrations, the dashboard for management visibility, the field app for on-farm data capture in low-connectivity environments, the marketplace for B2B and farmer-to-input procurement, and the processing interface for factory operators.

Application Path Modules
API Gateway apps/asase/api api-gateway.ts, api-auth.ts
Management Dashboard apps/asase/dashboard dashboard-shell.ts, kpi-view.ts, value-chain-viz.ts, alert-center.ts, reporting-engine.ts
Field Application apps/asase/field field-data-capture.ts, farmer-registration.ts, mobile-advisory.ts, input-distribution.ts, harvest-procurement.ts
Digital Marketplace apps/asase/marketplace b2b-portal.ts, farmer-input-store.ts
Processing Interface apps/asase/processing processing-dashboard.ts, batch-traceability.ts, qc-workstation.ts

19.1 Management Dashboard#

  • AsaseDashboardShell — Role-based dashboard sessions and permissions with visible-module resolution.
  • ConsolidatedKPIView — Aggregates KPIs across business units (ASASE_BU_METRICS), surfacing top and underperforming units.
  • ValueChainVisualization — Builds margin waterfalls, commodity flow maps, and bottleneck rankings.
  • AlertManagementCenter — Priority-scored alerts with escalation rules.
  • ReportingEngine — Report templates and scheduled reports.

19.2 Field Application#

  • FieldDataCapture — Offline-capable farm-visit records with a sync queue (soil samples, crop scouting) for Ghana's variable rural connectivity.
  • FarmerRegistrationModule — Farmer registration with biometric enrolment, household categorisation, plots, and crop history.
  • MobileAdvisorySystem — Weather, market-price, agronomic, and pest advisories with channel selection and USSD menu text.
  • InputDistributionTracker — QR-verified input distribution with stock tracking.
  • HarvestProcurementModule — Weight capture, parameter-based grading, and payment initiation at procurement stations.

19.3 Digital Marketplace#

  • B2B portalb2b-portal.ts connects Asase products with institutional buyers.
  • Farmer input storeFarmerInputStore provides a digital catalog and cart for smallholder input procurement, with a Mobile Money order flow (place → pay → dispatch → confirm) across MTN, Vodafone, and AirtelTigo networks.

19.4 Processing Plant Interface#

  • Processing dashboard, batch traceability, and QC workstation modules for factory managers and quality-control staff.

19.5 API Gateway#

  • api-gateway.ts and api-auth.ts provide a gateway and authentication layer for integration with external systems.

20. Cross-Domain Integration#

Package: @asase/connectorsimplemented

Asase integrates with six other Oshun domains through connector classes and builder functions, each with typed payload interfaces:

Connector group Bridge classes (@asase/connectors)
Brigid IrrigationInfrastructureConnector, ProcessingFacilityDesignBridge, ColdChainInfrastructurePlanner, RuralRoadAssessmentLink
Cybele ClimateAdaptationConnector, SoilHealthIntegrator, WaterResourceLinker, BiodiversityImpactAssessor
Freya AgriculturalMarketplaceConnector, PaymentReconciliationBridge, SupplyChainFinanceLinker
Saraswati FarmerTrainingContentGenerator, AgriculturalResearchBridge
Maat FoodSafetyComplianceConnector, LandTenureIntegrator
Aje AgriculturalLendingConnector, CommodityHedgingBridge

These connectors bridge irrigation/facility/road engineering (Brigid), climate adaptation and soil/water/biodiversity (Cybele), marketplace listings, payment reconciliation, and supply-chain finance (Freya), farmer training and research (Saraswati), food-safety compliance and land tenure (Maat), and agricultural lending and commodity hedging (Aje).


Library Summary#

All 15 libraries and 5 applications are implemented.

Library Package Status Primary Capabilities
Core @asase/core Implemented Domain types, Ghana agro-ecological context, regulatory compliance, 19 business unit configs, stakeholder management, audit trail, Drizzle schema (36 tables)
Crops @asase/crops Implemented Crop registry, variety recommender, pest/disease catalog, field activities, input scheduling, irrigation, soil fertility, crop health monitoring, labour, mechanization, intercropping, yield prediction, weather, harvest loss
Livestock @asase/livestock Implemented Livestock registry (NLIS), vaccination manager (VSD), feed formulation, broiler/layer/hatchery, disease surveillance (WAHIS), mortality analytics, house environment, distribution, aquaculture (fish farm, growth, feed, health, water quality)
Infrastructure @asase/infrastructure Implemented Redis caching, MinIO storage, typed event bus, Prometheus metrics, PostGIS geospatial indexing
Processing @asase/processing Implemented Plant digital twin, scheduling, raw-material receiving, BOM, batch execution, recipes, OEE, SPC, cost of quality, energy/utility monitoring, predictive maintenance, batch genealogy, nutritional labeling
Cold Chain @asase/cold-chain Implemented Facility registry, temperature monitoring, inventory, warehouse, GCX warehouse receipts, energy optimizer, backup power, transport fleet, route optimizer, post-harvest loss, excursion analytics, compliance docs
Supply Chain @asase/supply-chain Implemented Procurement, outgrower, contract farming, import management, supplier risk, distribution network, vehicle routing, market channel, returns, delivery proof, commodity price, price forecast, import parity, margin analysis, demand sensing
Quality @asase/quality Implemented HACCP, CCP monitoring, PRP, LIMS, aflatoxin, pesticide residue, water quality, calibration, recall, environmental/regulatory compliance, organic/export/FDA certification
Export @asase/export Implemented Commodity analyzer, market scanner, grading, volume forecaster, competitor tracker, trade documents, AfCFTA, EU regulation, customs duty, license manager, buyer CRM, dynamic pricing, contract negotiation, logistics, certification tracker
Inputs @asase/inputs Implemented Fertilizer blend/cost/subsidy, soil nutrient mapper, organic fertilizer advisor, seed performance/multiplication, agrochemical guidance, IPM advisor, agrochemical safety, input distribution, farmer credit, input bundles, import substitution, input QA
Market Intelligence @asase/market-intel Implemented Commodity/farmgate price tracking, price forecasting, price transmission, cedi exposure, supply-demand modeling, competitor analysis, consumer trend, price elasticity, seasonality, AfCFTA opportunity, regional trade flow, market entry, trade intelligence, policy simulator
Retail @asase/retail Implemented QSR location, franchise management, POS integrator, staff scheduling, quality audit, menu engineering, recipe cost, menu localizer, inventory waste, dynamic menu pricer, delivery logistics/platforms, institutional catering, central kitchen, customer loyalty
Financials @asase/financials Implemented Startup cost, unit/farm/processing economics, working capital, consolidated projection, capex planning, debt capacity, tax optimization, investor return, synergy valuation, scenario planner, benchmarking, FX risk, impact metrics
Connectors @asase/connectors Implemented Cross-domain connectors to Brigid, Cybele, Freya, Saraswati, Maat, Aje
SOTA @asase/sota Implemented Satellite remote sensing, drone precision agriculture, computer-vision grading, blockchain traceability + IoT cold chain, ML yield prediction + RL crop planning
Migrations @asase/migrations Implemented Drizzle migration runner, 11 migration files, 8 seed scripts, connection-pool presets