# Maat — Systems Deep Dive

> The `apps/maat/` area: ten Nx application projects making up Maat, the
> Ghana-focused conglomerate / business-operations domain — five real Next.js
> operator frontends, one fully-built Hono API gateway, and four reserved
> service scaffolds.

## What this area is

Maat is the business-operations and portfolio-management domain for a Ghanaian
conglomerate. Its "companies" are themselves named after deities used elsewhere
in the monorepo — `ASASE` (AgriTech), `FREYA` (Logistics), `CYBELE` (Real
Estate), `BRIGID` (Steel/Manufacturing), `SARASWATI` (R&D/IP), `IRIS` (AI), and
`AJE` (Blockchain) — and the apps here are the tools an operator, strategist,
analyst, or investor uses to run that portfolio. Every project carries the
`scope:maat` Nx tag.

The area splits into three clearly different tiers. The first is a set of **five
Next.js web frontends** (`@maat/dashboard`'s project is `maat-dashboard-app`,
plus `@maat/agent-console`, `@maat/intel`, `@maat/investor`, `@maat/war-room`),
each on its own dev port (3055–3059) and each tagged `platform:web`. These are
genuinely implemented App-Router apps: they pair real domain-specific financial
computation — DCF projection (`apps/maat/war-room/src/lib/scenario-engine.ts`),
Herfindahl-Hirschman concentration plus blended-IRR/NPV capital allocation
(`apps/maat/war-room/src/lib/capital-allocation.ts`), and a bisection-solver
NPV/IRR investment simulator (`apps/maat/investor/src/lib/simulation-data.ts`) —
with curated, in-process seed data (the `src/lib/*-data.ts` functions return
realistic Ghana-market fixtures rather than reading a live database).

The second tier is **one real backend service**, `maat-api-gateway-app`
(`apps/maat/api-gateway`, tagged `layer:app`). It is a fully-built Hono gateway
— JWT auth, RBAC, rate limiting, API versioning, an audit trail,
OpenAPI/Swagger, and a realtime WebSocket fan-out server — fronting eleven
logical upstream domain services (`intelligence`, `strategy`, `agents`,
`finance`, `supply-chain`, `digital-twin`, `compliance`, `knowledge`,
`dashboard`, `simulation`, `worker`). The third tier is **four reserved service
scaffolds** (`maat-agents-app`, `maat-intelligence-app`, `maat-simulation-app`,
`maat-worker-app`): each is just a `.gitkeep` plus a one-line
`bootstrap<name>()` in `src/index.ts` that returns an `"... initialized"`
string. They are honest placeholders for the upstream services the gateway is
configured to route to, not implemented runtimes.

## How it fits the wider system

The frontends are operator-facing and, today, largely self-contained: each reads
its own in-process fixture libraries and computes results client/server-side,
with the dashboard acting as the hub — the other four apps' nav components
(`ConsoleNav`, `IntelNav`, `InvestorNav`, `WarRoomNav`) link back to
`http://localhost:3055`. The only outbound network seam in the frontends is the
dashboard's own `src/app/api/auth/login/route.ts`, which optionally verifies
credentials against a configured `MAAT_IDP_VERIFY_URL`; the frontends do **not**
yet call the Maat API gateway. The gateway, in turn, is the intended edge for
the eleven domain services — four of which exist here only as scaffolds — so the
end-to-end "frontend → gateway → service" path is partially wired: the edge
layer and the UIs are real, the service backends behind the gateway are mostly
not yet built in this repo. Walk the dependency edges on any node below to see
exactly what it imports.

## Entity reference

### @maat/agent-console

The agent-fleet operations console (`apps/maat/agent-console`, dev port 3058). A
real Next.js App-Router app with a `(console)` route group covering `fleet`,
`tasks`, `approvals`, `conversations`, and `analytics`, backed by typed views
(`AgentFleetView`, `TaskTreeView`, `ApprovalsView`, `ConversationView`,
`AgentAnalyticsView`). Its data comes from in-process fixtures in
`src/lib/agent-data.ts` — `getAgents()` returns richly-typed agent records
(status, capabilities, dependency edges, and per-agent metrics like
`successRatePct`, `p99LatencyMs`, `tokensUsedK`) defined by
`src/types/agent.ts`. Curated seed data, not a live agent runtime, but the UI
and types are fully implemented.

### maat-agents-app

A **scaffold**, honestly labelled (`apps/maat/agents`, project
`maat-agents-app`, tagged `layer:app`). The only real source is `src/index.ts`,
which exports `bootstrapagents()` returning the string
`'maat-agents-app initialized'`, alongside a `.gitkeep` and the standard
tsconfig/vitest boilerplate. It reserves the slot for the `agents` upstream
domain service the API gateway is configured to dispatch to (`/api/v1/agents`),
but no agent-orchestration logic is implemented here yet.

### maat-api-gateway-app

The real edge service for the Maat domain (`apps/maat/api-gateway`, tagged
`layer:app`). `src/app.ts` builds a Hono application with Bearer-JWT
authentication (`jsonwebtoken`, HS256), a 23-value RBAC permission enum
(`MaatPermissionSchema`) enforced per-route via `requirePermission`, and an
organization-isolation check (`ensureOrganizationAccess`). It composes real
middleware: per-organization/user/agent sliding-window rate limiting backed by a
Redis pipeline (`src/middleware/rate-limit.ts`), RFC-8594 `Sunset`/`Deprecation`
API versioning (`src/middleware/api-versioning.ts`), request/response audit
logging with an in-memory default trail
(`src/middleware/request-response-logging.ts`), a programmatically-generated
OpenAPI 3.1 spec plus Swagger UI at `/api/docs` (`src/openapi/spec.ts`), and a
realtime WebSocket fan-out server with `dashboard`/`agents`/`market-alerts`/
`simulation` channels (`src/realtime/websocket-server.ts`). It registers eleven
domain-service routers from `DEFAULT_DOMAIN_SERVICE_ROUTES`; note that each
router's `/dispatch` validates and resolves the upstream URL and returns `202`
accepted (and `/health` reports the route as `"registered"`) rather than
reverse-proxying the request body through — the auth, RBAC, and routing surfaces
are complete, true upstream forwarding is not yet performed. Real tests exist
(`src/app.spec.ts`, `src/realtime/websocket-server.spec.ts`).

### maat-dashboard-app

The executive dashboard and the area's hub app (`apps/maat/dashboard`, package
`@maat/dashboard`, dev port 3055). The most fully-built frontend: it has real
JWT session auth using `jose` (`src/lib/auth.ts` signs an HS256 `maat_session`
httpOnly cookie with an 8-hour expiry), Next middleware (`src/middleware.ts`),
and login/logout API routes — `src/app/api/auth/login/route.ts` optionally
verifies against an external `MAAT_IDP_VERIFY_URL`. Its `(dashboard)` route
group covers `portfolio`, per-company drill-down (`company/[companyId]`),
`alerts`, and a `layout-builder`, with components like `PortfolioOverview`,
`RiskRadarPanel`, `StrategicInitiativesPanel`, and `CompanyDrillDown`. Financial
and company data come from in-process fixtures (`src/lib/company-data.ts`,
`src/lib/portfolio-data.ts`; `portfolio-financials.ts` simply re-exports
`COMPANY_FINANCIALS`).

### @maat/intel

The competitive-intelligence browser (`apps/maat/intel`, dev port 3057). A real
Next.js app whose `(intel)` route group covers `landscape`, `news`, `pricing`,
`regulatory`, and market `sizing`, rendered by views such as
`CompetitiveLandscapeView`, `PriceMonitorView`, `RegulatoryTrackerView`, and
`MarketSizingView`. The domain types in `src/types/intel.ts` model competitors,
threat levels, and strategic groups against the seven portfolio companies, and
`src/lib/market-sizing-data.ts` supplies TAM/SAM/SOM models with
Conservative/Base/Optimistic scenarios (Ghana-specific assumptions and five-year
CAGRs). Implemented UI and types over curated intelligence fixtures.

### maat-intelligence-app

A **scaffold** (`apps/maat/intelligence`, project `maat-intelligence-app`,
tagged `layer:app`). Real source is limited to `src/index.ts` exporting
`bootstrapintelligence()` returning `'maat-intelligence-app initialized'`, plus
a `.gitkeep` and tsconfig/vitest boilerplate. It reserves the backend
`intelligence` domain service (`/api/v1/intelligence` in the gateway); note this
is distinct from the `@maat/intel` frontend, which is the implemented UI. No
intelligence-pipeline logic is implemented in this scaffold.

### @maat/investor

The investor / diaspora portal (`apps/maat/investor`, dev port 3059). A real
Next.js app with a `(portal)` route group covering `dashboard`, `explore`,
`onboard` (the `DiasporaPortal`), `portfolio`, and `simulate`, with components
like `InvestorDashboard`, `BusinessUnitExplorer`, `InvestmentSimulator`, and
`InvestmentTierSelector`. Its standout is genuine financial logic:
`src/lib/simulation-data.ts` implements `npv()` and a bisection-method `irr()`
solver and builds BEAR/BASE/BULL scenarios with annual cash flows, MOIC, and
payback — real computation, not hardcoded outputs — over investment-tier and
business-unit fixtures.

### maat-simulation-app

A **scaffold** (`apps/maat/simulation`, project `maat-simulation-app`, tagged
`layer:app`). The only real source is `src/index.ts` exporting
`bootstrapsimulation()` returning `'maat-simulation-app initialized'`, alongside
`.gitkeep` and standard config. It reserves the `simulation` upstream domain
service the gateway routes to (`/api/v1/simulation`, also a realtime
`simulation` channel); the actual heavy simulation engine is not implemented
here. (The investor and war-room frontends contain their own in-process
simulation math; this service backend remains a placeholder.)

### @maat/war-room

The strategy war room (`apps/maat/war-room`, dev port 3056) — the most
computation-heavy frontend. Its `(war-room)` route group covers
`strategy-canvas`, `scenario`, `capital`, `market-entry`, and `synergies`. It
carries two real engines: `src/lib/scenario-engine.ts` projects five-year DCF
financials from scenario variables using Ghana macro constants (25% corporate
tax, 21% WACC, 5% terminal growth) and computes scenario comparisons, and
`src/lib/capital-allocation.ts` computes the Herfindahl-Hirschman concentration
index, weighted blended IRR from per-company sector IRR expectations, and
WACC-discounted portfolio NPV. Blue Ocean strategy canvases and synergy/market-
entry data live in sibling `src/lib/*-data.ts` fixtures. Fully-implemented UI
plus real strategic-finance math.

### maat-worker-app

A **scaffold** (`apps/maat/worker`, project `maat-worker-app`, tagged
`layer:app`). Real source is just `src/index.ts` exporting `bootstrapworker()`
returning `'maat-worker-app initialized'`, plus `.gitkeep` and tsconfig/vitest
boilerplate. It reserves the `worker` background-processing service the gateway
exposes (`/api/v1/worker`, `worker:read`/`worker:write` permissions); no
job/queue worker runtime is implemented here yet.
