# Maat — Systems Deep Dive

> The `libs/maat/` area: eighteen Nx libraries that make up **Maat**, the
> business-intelligence and operating-system layer for a Ghana/Africa-focused
> industrial conglomerate — finance, capital, strategy, risk, supply chain,
> compliance, workforce, and the agent/knowledge/digital-twin machinery that
> ties them together. This page is the entity-catalog view of the area.

## What this area is

Maat is the "back office brain" of the Oshun portfolio: a suite of
deterministic, in-process domain engines that model the operations and finances
of a multi-company holding group. Every library under `libs/maat/` is a
`scope:maat` Nx library tagged `layer:domain`, and almost every one is a plain
TypeScript package built with `@nx/js:tsc` whose public surface is a barrel
`src/index.ts` that re-exports one module per business capability. The engines
are real domain algorithms — discounted-cash-flow valuation, Black-Litterman
portfolio allocation, value-at-risk, AfCFTA/ECOWAS tariff optimisation, genetic
project portfolio optimisation, GraphRAG knowledge retrieval — not CRUD
wrappers. Many implementation files carry `@noble/hashes` `sha256` imports
because the engines emit content-addressed, hash-stamped result records for
auditability, and `zod` schemas validate inputs at the boundary.

The area is organised by **tier**, visible in each `project.json`'s tags.
`@maat/core` is `maat:tier:core` and sits at the bottom: it owns the shared
organisation model (branded `OrganizationId`/`OperatingCompanyId` types, legal-
entity and industry-sector enums), the typed Maat event bus, and Redis namespace
conventions. The large business-capability libraries (`finance`, `capital`,
`strategy`, `risk`, `supply-chain`, `compliance`, `workforce`, `projects`,
`intelligence`, `knowledge`, `digital-twin`, `agents`, `reporting`) are
`maat:tier:feature`. `@maat/sdk` is `maat:tier:sdk` (the external client
surface), and `@maat/integrations` wires Maat to the seven sibling Oshun
portfolio companies.

A strong Ghana/West-Africa domain bias runs through the whole area: GHS is the
primary currency, engines reference COCOBOD/MOFA/Bank-of-Ghana data sources, the
tariff engines encode ECOWAS CET and AfCFTA African country codes, and the
compliance library is built around the Ghana regulatory bodies and the Ghana
Data Protection Act. This is what makes the code domain-specific rather than
generic ERP scaffolding.

Two libraries are intentionally narrow rather than broad: `@maat/dashboard` (~93
LOC, a single V2 balance-dashboard manifest builder) and
`@maat/negotiation-intelligence` (~178 LOC, one procurement-program module for
the Concordia bridge). They are real and implemented, just single-purpose — the
catalog labels them as such rather than implying the breadth of the larger libs.

## How it fits the wider system

These libraries compose three ways. **Within Maat**, the feature engines depend
on `@maat/core` for the organisation model and event taxonomy, and on each other
for cross-cutting data — `@maat/dashboard` explicitly composes `@maat/reporting`
(charts) and `@maat/intelligence` (signals) into a governed dashboard surface.
**Outward to the portfolio**, `@maat/integrations` adapts data from the seven
operating companies — Asase (agriculture/cold-chain), Freya (luxury fashion),
Cybele (construction/property), Brigid (manufacturing), Saraswati (R&D/EV
fleet), Iris (AI orchestration), and Aje (blockchain/digital assets) — into
Maat's intelligence, digital-twin, and finance models. **Outward to clients**,
`@maat/sdk` exposes a typed client, CLI, React components, webhooks and SSE
streaming over the `@maat/*` module set with Ghana-aware defaults. The
`@maat/negotiation-intelligence` library is the boundary to the Concordia
procurement-negotiation domain (Phase 179.7.1), translating a tenant procurement
program into Concordia extension defaults. Walk the "used by" edges on any node
below to see exactly who depends on it.

## Entity reference

### @maat/core

The foundation tier (`libs/maat/core/src`, `maat:tier:core`). It owns the shared
organisation model in `organization.ts` — branded ID types (`OrganizationId`,
`OperatingCompanyId`, `ISODateString`), and the enums every other Maat library
keys off (`LEGAL_ENTITY_TYPE_VALUES`, `LEGAL_STRUCTURE_MODEL_VALUES`,
`OWNERSHIP_MODEL_VALUES`, `OPERATING_COMPANY_INDUSTRY_SECTOR_VALUES`) — plus the
typed event bus in `event-bus.ts` (the `MaatDomainEventTypeSchema` enum of
`MarketIntelligenceEvent`/`AgentTaskEvent`/`StrategyDecisionEvent`/
`ComplianceAlertEvent`/`SimulationStateEvent` with versioned,
correlation-stamped Zod payloads) and Redis namespace conventions in
`redis-namespace.ts`. Four real implementation modules; the barrel re-exports
all three.

### @maat/finance

The corporate-finance engine set (`libs/maat/finance/src`, ~22 modules, ~18K
LOC). `package.json` describes it as "V2 ledger reconciliation, regional
pricing, refunds, and regulatory caps," but the implemented surface is broader
valuation/FP&A machinery: a real discounted-cash-flow engine
(`discounted-cash-flow-engine.ts` with explicit `GhanaMarketAssumptions` —
91-day T-bill risk-free rate, frontier equity risk premium, country risk premium
— WACC build-up and terminal value), comparable-company and LBO model builders,
IRR/NPV, pro-forma income-statement and balance-sheet builders, FX-risk and
multi-currency-consolidation engines, transfer pricing, and Ghana
tax-optimisation and tax-calendar engines. The barrel also exports a
`v2-persistence-ledger`.

### @maat/capital

The capital-allocation library (`libs/maat/capital/src`, ~16 modules, ~9K LOC).
It implements portfolio and investment decision tooling: a Black-Litterman
allocator (`black-litterman.ts`, with a confidence→omega mapping over `LOW`…
`VERY_HIGH` views and absolute/relative view types), investment evaluation,
hurdle-rate and capital-budgeting engines, a funding waterfall, debt-capacity
and treasury management, and Africa-specific instruments — diaspora-investment,
impact-investment, government-incentive, and milestone-capital-release modules,
plus capital-call management and a capital-efficiency dashboard. Results are
hash-stamped via `@noble/hashes` for auditability.

### @maat/strategy

The strategic-planning engine set (`libs/maat/strategy/src`, ~22 modules, ~17K
LOC; `maat:tier:feature`). `package.json`: "strategic planning, capital
allocation, and live-ops calendar authority." It implements the classic strategy
frameworks as real analyzers — Porter's Five Forces, SWOT, TAM/SAM/SOM, BCG
growth-share, Ansoff, Blue Ocean — alongside quantitative decision tooling:
real-options valuation, a game-theory module, Monte-Carlo simulation, scenario
definition/comparison, sensitivity and stress-testing frameworks, an MPT
optimizer, and dynamic capital-reallocation. It also carries a domain-specific
`v2-fighting-game-live-ops-calendar` (the "live-ops calendar authority" from the
description), tying the strategy layer to the V2 game's release cadence.

### @maat/risk

The enterprise-risk library (`libs/maat/risk/src`, ~16 modules, ~14.6K LOC). It
implements a risk taxonomy and probability-impact framework plus quantitative
risk math: a value-at-risk engine (`value-at-risk.ts` supporting `PARAMETRIC`,
`HISTORICAL`, and `MONTE_CARLO` methods across confidence levels 0.90–0.999 and
1–252-day horizons, with a West-African currency set centred on GHS), portfolio
Monte-Carlo, and key-risk-indicator tracking. Domain risk modules cover
political, currency-hedging, commodity-price, cybersecurity, climate, and
supply-chain risk, plus business-continuity, insurance-portfolio,
emerging-risk-radar, and risk-appetite. Outputs are hash-stamped for an
auditable risk register.

### @maat/supply-chain

The supply-chain and trade library (`libs/maat/supply-chain/src`, ~21 modules,
~21K LOC). Beyond standard supplier-map, supplier-risk-scoring, qualification/
onboarding, inventory-optimisation, logistics-routing, landed-cost, and
demand-forecasting engines, its distinguishing feature is real West-African
trade machinery: an AfCFTA tariff-optimisation engine
(`afcfta-tariff-optimization-engine.ts` encoding the full African country-code
set), an ECOWAS-CET database, free-trade-zone optimisation,
customs-documentation generation, and a trade-finance intelligence module. There
is also a supply-chain disruption simulator and a make-vs-buy analysis
framework.

### @maat/workforce

The people/HR-analytics library (`libs/maat/workforce/src`, ~16 modules, ~5.2K
LOC). It models the workforce as decision-support engines rather than an HRIS:
org-design modelling, headcount planning, skills-gap analysis,
compensation-benchmarking, succession planning, and an attrition-prediction
model (`attrition-prediction.ts` that scores flight risk from tenure,
engagement, salary-vs-market, manager/peer relationship and job-search signals,
weighting in Ghana-region and competitor-hiring intensity, and emits
replacement-cost estimates in GHS). Also covers labour-market intelligence,
payroll modelling, diversity-tracking, org-network analysis, contractor
optimisation, expatriate management, training-ROI, and a workforce scenario
planner.

### @maat/projects

The portfolio/PMO library (`libs/maat/projects/src`, ~16 modules, ~10.7K LOC).
It implements project and portfolio management as computational engines: project
creation, a Gantt engine, cross-company dependency tracking, resource-allocation
optimisation, earned-value management, and project-health scoring — plus a
genetic portfolio optimiser (`portfolio-genetic-optimizer.ts`, which selects an
active project set under resource constraints from typed
`PgoProject`/`PgoResourceDemand` inputs weighted by priority and strategic
value). Rounded out by a project-risk register, RACI-matrix generator,
milestone-payment tracker, status reporting, change-request management, a
lessons-learned database, a portfolio dashboard, and a project-template library.

### @maat/compliance

The regulatory-compliance library (`libs/maat/compliance/src`, ~21 modules, ~21K
LOC) built around Ghana law. It carries a Ghana regulatory-body registry, a
Ghana regulation catalog, and a requirement-mapping engine, plus license/permit
tracking, a compliance calendar, regulatory-change monitoring, gap analysis,
audit preparation, and a cross-jurisdiction mapper. Domain-specific frameworks
include anti-corruption compliance, ESG reporting, environmental-impact
assessment, governance-compliance tracking, supply-chain ethics monitoring, a
Ghana Data Protection Act compliance engine, IP-portfolio management,
contract-compliance monitoring, regulatory-filing automation, and
compliance-training management.

### @maat/intelligence

The market/competitive-intelligence library (`libs/maat/intelligence/src`, ~31
modules, ~24.7K LOC — the largest feature lib). `package.json`: "market,
operational, anomaly, trend, and causal analysis." It implements a market
monitor, news aggregator, web-scraping and streaming-ingestion framework,
data-normalisation pipeline, competitor tracker and competitive-positioning
engine, patent monitoring, supplier-intelligence, partnership/M&A radar,
sentiment analyzer, trend detector, anomaly detection, and an early-warning
system. The advanced surface adds a causal-inference engine, a world-model
simulator, an intelligence synthesizer, a confidence-scoring framework, an
NL2SQL and voice-command interface, multimodal-intelligence fusion, a predictive
supply-chain twin, and an AI-regulatory-compliance scanner.

### @maat/knowledge

The knowledge-management / RAG library (`libs/maat/knowledge/src`, ~22 modules,
~20K LOC). It implements a document pipeline (ingestion, classification,
summarisation, entity extraction, versioning/deduplication) feeding a
Neo4j-schema knowledge graph with population, enrichment, query, and maintenance
services, semantic search, and a research-corpus manager. Its headline component
is a GraphRAG engine (`graph-rag-engine.ts`) explicitly following the Microsoft
GraphRAG paper (Edge et al., 2024) — graph construction, Leiden-style community
detection, community summarisation, and LOCAL/GLOBAL/HYBRID query modes over a
Maat-business entity type set — with all embedding/LLM/graph I/O behind
pluggable providers so it is testable in-memory. Also includes a
patent-landscape engine, academic-research monitor, knowledge-freshness engine,
and conflict resolution.

### @maat/digital-twin

The organisation-simulation library (`libs/maat/digital-twin/src`, ~21 modules,
~22.4K LOC). It models the whole conglomerate as a digital twin: an
organisation-state model (`organization-state-model.ts` with `FINANCIAL`/
`PRODUCTION`/`INVENTORY`/`WORKFORCE`/`DEMAND`/`PROJECTS` state dimensions across
operating-company and business-unit scopes), a state-ingestion pipeline,
snapshot versioning, a diff engine, and data-quality monitoring. On top sit
simulation engines — business-unit dependency graph, what-if and
bottleneck-identification analysis, impact attribution,
temporal/facility/workforce/financial-cascade simulators, a market-shock
simulator, multi-objective optimisation and resource-reallocation, a
visualisation-data generator, a scenario manager, and a unifying simulation API.

### @maat/agents

The agent-orchestration library (`libs/maat/agents/src`, ~28 modules, ~27.8K LOC
— the largest in the area). It implements an agent platform: a registry
(`agent-registry.ts` with typed implementation handlers, health-check handlers,
and ACTIVE/INACTIVE/RETIRING/DEPRECATED lifecycle states), a factory,
lifecycle/pool managers, and a configuration schema, plus role agents (strategy,
engineering, finance, operations, research, compliance). The coordination layer
adds a task decomposer, dependency-graph executor, a tool registry, MCP
server-discovery / transaction-coordinator / intent-routing, inter-agent
communication, an agent memory system, a human-in-the-loop workflow engine,
performance-tracking and feedback-loop systems, an observability dashboard, a
LangGraph-style workflow engine, an RL capital-allocation environment, and a
federated-learning framework. Note: this is the in-process agent
infrastructure/data-model layer; LLM/tool execution is handled through the typed
handler and provider seams rather than a bundled model client.

### @maat/reporting

The reporting/output library (`libs/maat/reporting/src`, ~16 modules, ~6.7K
LOC). `package.json`: "KPI scorecards, charts, board packs, and governed report
exports." It implements a KPI-scorecard engine (`kpi-scorecard-engine.ts` with
RAG status, trend direction, variance-from-target and sparkline data across five
strategic pillars — Financial/Operational/Customer/People/Sustainability),
board-report and investor-deck generators, a chart-data generator, PDF-export
engine, report distribution, an NL query interface, cross-company benchmarking,
variance analysis, regulatory-filing reports, an MD&A commentary generator, an
ad-hoc report builder, a cash-flow waterfall, and an ESG-report generator.

### @maat/dashboard

A narrow, single-purpose library (`libs/maat/dashboard/src`, ~93 LOC — two
modules, one real). It builds the governed **V2 balance dashboard** surface
(`v2-balance-dashboard.ts`): a manifest of panels (pick-rate, win-rate,
win-rate-on-block, frame-data-drift, hot/cold heatmap, A/B publication, release
gate) bound to a fixed set of V2 match-event topics, that composes
`@maat/reporting` charts and `@maat/intelligence` signals. `package.json`
describes it as the home for "governed dashboard manifests and product-facing
metric surfaces." Real and implemented, but deliberately scoped to the V2
balance surface rather than a general dashboard framework.

### @maat/integrations

The portfolio-integration layer (`libs/maat/integrations/src`, 8 modules, ~5.5K
LOC). Its `index.ts` declares it "Connects all 7 Maat portfolio companies to the
Maat intelligence platform," with one adapter per sibling domain: Asase
(agriculture/cold-chain — commodity price points across COCOA/CASSAVA/MAIZE/etc.
with COCOBOD/MOFA/FAO sources, supply-demand snapshots), Freya, Cybele, Brigid,
Saraswati, Iris, and Aje. Each adapter defines the typed data shapes Maat
ingests from that company into its intelligence, digital-twin, and finance
models — the boundary translation layer between the operating companies and the
Maat brain.

### @maat/sdk

The client SDK (`libs/maat/sdk/src`, ~11 modules, ~5.7K LOC; `maat:tier:sdk`).
It exposes the `@maat/*` platform to external consumers with Ghana-aware
defaults (GHS currency, `Africa/Accra` timezone): a typed client
(`typed-client.ts` with a `MaatModule` union over all fifteen feature modules,
environment/retry/timeout config), a CLI tool, React components, a webhook
manager, an API-key manager, batch operations, SSE streaming, a plugin
architecture, an offline mode, and an SDK docs generator. It is the
public-facing surface tier, not a feature engine.

### @maat/negotiation-intelligence

A narrow, single-purpose library (`libs/maat/negotiation-intelligence/src`, ~178
LOC — one real module). `package.json`: "Pactum-class procurement negotiation
intelligence — supplier scoring, lever calibration, ERP bridge (Phase 179.7.1)."
The implemented surface is the `procurement-program.ts` module: Zod schemas for
a `ProcurementProgram` (procurement tracks like
`tail_spend_automated`/`direct_material_sourcing`, an authorised lever set such
as `unit_price`/`payment_terms_dpo`/`rebate_tiered`, and spend-based approval
thresholds), plus `findApprovalThreshold` and `toMaatExtensionDefaults` helpers
that translate a tenant program into the `MaatProcurementExtension` defaults
each Concordia procurement case inherits. It is the tenant-config bridge to the
Concordia negotiation domain — real and focused, with the broader
supplier-scoring machinery described in the package description not yet present
in `src`.
