# Maat Domain — Architecture

> **Maat** — Portfolio Intelligence and Business Management Platform

---

## Domain Purpose

Maat is the central intelligence and management layer for a diversified
portfolio of businesses operating across multiple industries in West Africa. It
is named after the Egyptian goddess of truth, justice, and cosmic order —
reflecting its role as the source of analytical truth and governance across all
portfolio entities.

Running a conglomerate of distinct companies across agriculture, manufacturing,
fashion, construction, R&D, blockchain, and AI requires the analytical depth of
many specialist teams working in concert. Maat provides that depth
programmatically: strategy simulation, financial modeling, real-time competitive
intelligence, AI agent orchestration, compliance tracking, supply-chain
optimization, and a live digital twin of every portfolio company, all under one
roof. A single executive team can interrogate the live state of the entire
portfolio and simulate the consequences of decisions before committing to them.

The domain ships as **19 domain libraries** under `libs/maat/` plus **11
application roots** under `apps/maat/`. The libraries hold all domain logic; the
applications consume them. Of the 11 apps, five are implemented Next.js web apps
(`dashboard`, `agent-console`, `intel`, `investor`, `war-room`), one is an
implemented Hono API gateway (`api-gateway`), and four (`agents`,
`intelligence`, `simulation`, `worker`) are bootstrap scaffolds awaiting
implementation. Two libraries — `@maat/dashboard` and
`@maat/negotiation-intelligence` — are themselves scaffolds (see below).

---

## Library Organization

The 19 libraries are organized thematically under `libs/maat/`. Each library
owns a distinct capability area and can be understood independently of the
others.

```
libs/maat/
├── core/                       # Domain types, in-process event bus, Redis namespace builder
├── agents/                     # AI agent framework — registry, lifecycle, specialized agents
├── capital/                    # Capital allocation, investment evaluation, funding structures
├── compliance/                 # Regulatory compliance, licensing, filing automation
├── dashboard/                  # SCAFFOLD — only the V2 balance-dashboard contract
├── digital-twin/               # Organization state modeling and simulation engine
├── finance/                    # Financial modeling: DCF, LBO, pro formas, tax, FX
├── integrations/               # Connectors for the 7 portfolio companies
├── intelligence/               # Market monitoring, competitive intelligence, ML signals
├── knowledge/                  # In-memory knowledge graph, semantic search, document management
├── negotiation-intelligence/   # SCAFFOLD — procurement-program config (Concordia seed, Phase 179)
├── projects/                   # Project portfolio management and delivery tracking
├── reporting/                  # Report generation, board packs, KPI scorecards
├── risk/                       # Risk taxonomy, measurement, Monte Carlo, VaR
├── sdk/                        # TypeScript client SDK for external consumers
├── strategy/                   # Strategic frameworks: Porter's, BCG, scenario planning
├── supply-chain/               # Supply chain visibility, logistics, trade optimization
└── workforce/                  # People analytics, org design, workforce planning
```

> Dashboard _entity_ types (`Dashboard`, widgets, layouts, permissions) live in
> `@maat/core`, not in `@maat/dashboard`. The `@maat/dashboard` library
> currently exports only the V2 balance-dashboard contract.

The six implemented application roots under `apps/maat/` consume the libraries
above. Four additional app roots are bootstrap scaffolds that have not yet been
implemented.

```
apps/maat/
├── api-gateway/      # Hono JWT gateway — reverse-dispatch to domain services
├── dashboard/        # Next.js — portfolio / company / alerts / layout-builder
├── agent-console/    # Next.js — agent tasks, approvals, fleet, conversations
├── intel/            # Next.js — competitive landscape, news, pricing, sizing
├── investor/         # Next.js — investor portal: portfolio, explore, simulate
├── war-room/         # Next.js — scenario, market-entry, strategy-canvas, synergies
├── agents/           # SCAFFOLD — bootstrap stub
├── intelligence/     # SCAFFOLD — bootstrap stub
├── simulation/       # SCAFFOLD — bootstrap stub
└── worker/           # SCAFFOLD — bootstrap stub
```

---

## Layered Architecture

Maat is organized into six conceptual layers, from the raw data foundation at
the bottom to the user-facing application layer at the top. Each layer depends
only on layers below it.

```
┌─────────────────────────────────────────────────────────────┐
│  APPLICATION LAYER                                          │
│  apps/maat — api-gateway (Hono) · 5 Next.js web apps       │
├─────────────────────────────────────────────────────────────┤
│  CONSUMER LAYER                                             │
│  SDK (@maat/sdk)                                            │
├─────────────────────────────────────────────────────────────┤
│  INTELLIGENCE & ANALYSIS LAYER                              │
│  @maat/agents · @maat/intelligence · @maat/strategy         │
│  @maat/finance · @maat/capital · @maat/risk                 │
│  @maat/compliance · @maat/workforce · @maat/supply-chain    │
│  @maat/projects · @maat/reporting · @maat/knowledge         │
├─────────────────────────────────────────────────────────────┤
│  SIMULATION & MODELING LAYER                                │
│  @maat/digital-twin                                         │
├─────────────────────────────────────────────────────────────┤
│  DATA INTEGRATION LAYER                                     │
│  @maat/integrations (Asase, Freya, Cybele, Brigid,          │
│  Saraswati, Iris (Maat portfolio company, not to be         │
│  confused with the `@iris/*` Oshun domain), Aje)            │
├─────────────────────────────────────────────────────────────┤
│  FOUNDATION LAYER                                           │
│  @maat/core (types, in-process event bus, organization model)│
└─────────────────────────────────────────────────────────────┘
```

The **Foundation Layer** (`@maat/core`) defines the shared domain vocabulary —
branded ID types, Zod-validated entity schemas, a typed in-process event bus,
and a Redis key-namespace builder — that every other library builds on top of.
No library needs to know how another library works internally; they communicate
through the shared type system defined in core.

The **Data Integration Layer** (`@maat/integrations`) contains one connector per
portfolio company. These connectors describe the data shapes that flow in from
each company's operational systems (ERP, IoT telemetry, transaction logs, and
research pipelines). They are implemented as pure `@maat/integrations` modules
and do not import the portfolio companies' own Oshun domain libraries.

The **Simulation & Modeling Layer** (`@maat/digital-twin`) maintains a live
computational model of each portfolio company's state. It ingests data from the
integration layer, stores immutable versioned snapshots, and supports
deterministic scenario simulation — feeding results upward to the intelligence
and analysis layer.

The **Intelligence & Analysis Layer** contains the bulk of the domain:
specialized analytical engines for strategy, finance, capital, risk, compliance,
workforce, supply chain, projects, knowledge, reporting, and market
intelligence. This layer is where domain-specific algorithms live — DCF
valuation, Monte Carlo simulation, regulatory filing automation, supply-chain
optimization, and the AI agent orchestration framework.

The **Consumer Layer** (`@maat/sdk`) provides a typed TypeScript client that
external developers and internal tooling use to interact with the platform
without depending directly on the domain libraries.

The **Application Layer** surfaces all of this through a Hono API gateway and
five specialized Next.js web apps aimed at different user personas.

---

## Core Design Patterns

### 1. Event-Driven Architecture

`@maat/core` exports `InMemoryMaatEventBus`, a typed **in-process** event bus
(not Redis-backed). Events are the primary mechanism by which domain activities
notify interested subscribers — a compliance deadline fires a
`ComplianceAlertEvent`; an agent completing a task fires an `AgentTaskEvent`.
The bus carries five discriminated domain event types —
`MarketIntelligenceEvent`, `AgentTaskEvent`, `StrategyDecisionEvent`,
`ComplianceAlertEvent`, and `SimulationStateEvent` — each validated by a Zod
schema extending a shared envelope. Publishers call `publish`; subscribers use
`subscribe(eventType, handler)` or `subscribeAll(handler)`. Handlers run via
`Promise.allSettled`, and a rejected handler surfaces as an `AggregateError`.
The `@maat/core` Redis namespace module produces collision-proof key strings for
a future Redis integration but opens no connection.

### 2. AI Agent Orchestration

`@maat/agents` (28 modules) implements a multi-agent system with specialized
agents for the six `AgentClass` values — strategy, engineering, finance,
operations, research, and compliance. The framework provides:

- a central `AgentRegistryService` for registration, discovery, and health;
- an agent factory and lifecycle manager;
- a declarative agent-configuration schema (model, tool-access, memory,
  cost-budget, and escalation policy);
- a tool registry and MCP integration (server discovery, transaction
  coordinator, intent routing);
- inter-agent communication, agent memory, performance tracking, feedback loops,
  and a collaboration framework;
- a human-in-the-loop workflow engine.

The specialized agents are deterministic analysis agents that compose other
`@maat/*` libraries (for example, the finance agent imports `@maat/intelligence`
and `@maat/strategy`); they do not call an LLM directly. The
`langgraph-workflow-engine` module is a **LangGraph-_style_** stateful graph
engine implemented in pure TypeScript — it does not depend on the LangGraph
library. `rl-capital-allocation-env` is a Gym-style reinforcement-learning
environment (tabular Q-learning, REINFORCE, A2C) and
`federated-learning-framework` implements FedAvg/FedProx/FedMedian with
differential privacy — both pure TypeScript with no external ML dependency.

### 3. Organization Digital Twin

`@maat/digital-twin` maintains a live computational model of each portfolio
company. Rather than waiting for a periodic report, executives can interrogate
the live state of each company at any moment. The twin ingests operational data
continuously, stores immutable versioned snapshots, and supports deterministic
simulation. The simulation engine can evaluate scenarios by applying
hypothetical `StateChange` objects to a baseline snapshot and projecting
forward.

### 4. Cross-Company Intelligence

`@maat/intelligence` operates as a continuous intelligence gathering system
with:

- Scheduled scrapers and market data feeds populating a normalized data store
- Streaming analytics pipelines processing real-time signals
- ML models for sentiment analysis, trend detection, and anomaly detection
- A synthesis layer that aggregates signals into executive intelligence briefs

`@maat/knowledge` maintains an in-memory knowledge graph connecting entities
across the portfolio, with semantic search and a graph-RAG engine. The
`knowledge-graph-neo4j-schema` module models node and relationship records (each
node carries a `neo4jLabel`) so the graph can later be projected onto Neo4j; the
current implementation uses TypeScript records and Zod validation and bundles no
`neo4j-driver` dependency.

### 5. Ghana-First Compliance

`@maat/compliance` is built with a Ghana-first regulatory model, encoding the
Ghana Revenue Authority, Securities and Exchange Commission Ghana, Bank of
Ghana, Food and Drugs Authority, and Environmental Protection Agency as primary
regulatory bodies. This reflects the fact that the portfolio companies are
primarily incorporated and operating in Ghana. Cross-jurisdiction mappings
extend coverage to other ECOWAS and international jurisdictions as portfolio
companies expand. The compliance engine is deeply integrated with
`@maat/reporting` to automate regulatory filing generation — reducing the manual
effort required to stay current with Ghana's compliance calendar.

---

## Data Architecture

The Maat domain currently has **no wired datastore**. Domain state is held in
in-memory value objects validated by Zod; no library imports a PostgreSQL
driver, an ORM (Drizzle/Prisma), a `neo4j-driver`, or a Redis client. The two
modules below describe key/record shapes for a _future_ datastore integration;
they are useful today as the schema contract that a future persistence layer
must honor.

### Knowledge Graph Schema (`@maat/knowledge`)

`knowledge-graph-neo4j-schema.ts` defines an in-memory graph model whose node
records include a `neo4jLabel` field intended for an eventual Neo4j projection.
The node and relationship type vocabularies are:

- Node types: `ORGANIZATION`, `PERSON`, `PRODUCT`, `MARKET`, `REGULATION`,
  `TECHNOLOGY`, `LOCATION`, `EVENT`, `CONCEPT`.
- Relationship types: `COMPETES_WITH`, `SUPPLIES_TO`, `REGULATED_BY`,
  `LOCATED_IN`, `INVENTED_BY`, `PART_OF`.

### Redis Namespace Builder (`@maat/core`)

`redis-namespace.ts` is a pure key-string builder — it produces no side effects
and opens no connection. Centralizing key construction here ensures all services
use consistent, non-colliding namespaces when a Redis integration is wired in.
The default prefixes are `maat` (root), `maat:agent:state`,
`maat:intelligence:cache`, `maat:strategy:results`, `maat:dashboard:state`, and
`maat:rate:limit`.

---

## Dependencies on Other Oshun Domains

The Maat libraries currently have **no source-level imports** from other Oshun
domains (`@sophia/*`, `@iris/*`, shared `@oshun/*`). Each Maat library is
self-contained TypeScript. This boundary is intentional: Maat is a business
intelligence and operations platform. It consumes _data_ from the portfolio
companies' operational domains, but does not import their domain libraries. Any
cross-domain integration is planned, not yet wired.

The seven `@maat/integrations/*` connectors describe data flows from the
portfolio companies (Asase, Freya, Cybele, Brigid, Saraswati, Iris, Aje) but are
themselves implemented as `@maat/integrations` modules — they do not import
those companies' domains. Maat owns organization operating systems, portfolio
intelligence, governance operations, and business rollups. Themis owns
governance primitives; Aje owns blockchain rails; each individual domain system
owns its source operational data.

---

## Library Dependency Graph (Internal)

Cross-library imports within `libs/maat/` are intentionally minimal. Keeping
dependencies sparse prevents tight coupling between analytical subsystems and
makes each library independently testable. The only internal `@maat/*` imports
observed in source are:

```
@maat/agents      ──▶ @maat/intelligence, @maat/strategy
@maat/compliance  ──▶ @maat/intelligence

every other library (including @maat/core)  ──▶ (no internal @maat deps)
```

The `@maat/sdk` typed client defines request/response shapes for all modules but
does not import the domain libraries. `@maat/agents` specialized agents compose
`@maat/intelligence` and `@maat/strategy` engines directly — for example, the
finance agent uses `TrendDetector` and `CapitalBudgetingEngine`.

---

## Nx Build Configuration

Maat libraries build with the `@nx/js:tsc` executor and test with
`@nx/vite:test` (Vitest); library tags are `scope:maat` and `type:lib`. The
`api-gateway` app builds with `@nx/js:tsc`; the five Next.js apps use
`nx:run-commands` wrapping `next build`/`next start` and are tagged
`scope:maat`, `type:app`, `platform:web`.

When Nx is unavailable (e.g. duplicate-project errors from worktrees), use these
direct invocations instead:

```bash
# Type check
cd libs/maat/<library> && npx tsc --noEmit

# Test
cd libs/maat/<library> && npx vitest run
```
