# Athena Domain - Architecture

> Maker intelligence and workshop-operations platform: an implemented Phase-67
> stack of ~40 packages under `libs/athena/` (TypeScript domain libraries plus a
> self-contained Rust geometry kernel), with a partial Phase-136 sovereign
> CAD-kernel slice. This page describes what is actually in the tree, not the
> planning backlog.

Athena is the Oshun domain for autonomous furniture manufacturing,
musical-instrument luthiery, multi-material workshop operations, smart and
living furniture, and the CAD/CAM/CAE and business systems around the shop
floor. It is named for the Greek goddess of crafts and practical arts — the
patroness of artisans — and it carries a deliberate West-African grounding: the
default currency in `@athena/core` is `GHS` (Ghanaian cedi) and the seed catalog
in `@athena/db` opens with _Khaya ivorensis_ (African mahogany), teak, and
obeche (`wawa`).

Unlike the three sibling documents in this folder, which were written while the
domain was still planning-only, the code is now here. A scan of the monorepo
shows **no `apps/athena/` and no `services/athena/` directories** — Athena ships
as a library domain. It lives almost entirely under `libs/athena/` (≈485 tracked
files across 40 package directories) plus a cross-domain contract package at
`libs/contracts/athena/` (`@contracts/athena`). Everything builds as Nx
libraries: each package carries `project.json`, `package.json`,
`tsconfig*.json`, and a `vitest.config.ts`, except the one Rust crate, which
builds with Cargo.

## Status at a Glance

- **Phase 67 (maker / workshop operations): implemented.** All 37 planned
  library areas exist as real packages with domain logic and tests — for example
  `@athena/cad`'s test suite is 993 lines, `@athena/luthiery`'s is 1072,
  `@athena/cam`'s is 744. Non-test source under `libs/athena/` is on the order
  of 120k lines.
- **Geometry kernel: implemented as a standalone Rust crate.**
  `cad-topology-rust` (≈2,500 lines) delivers the B-rep / NURBS /
  feature-operation / constraint / topology-optimization core that the Phase-136
  `@athena/kernel` and `@athena/constraint` specs call for, with `#[no_mangle]`
  WASM exports.
- **Rest of Phase 136: roadmap.** The separately-numbered kernel packages
  (`cad-studio`, `sim`, `eda`, `cam-milling`, `cam-additive`, `cam-other`,
  `gis`, `simulation-coupling`) do **not** exist as packages. Their scope is
  partly anticipated inside the Phase-67 packages (`@athena/cam`,
  `@athena/simulation`, `@athena/electronics`) and the Rust kernel, but the
  sovereign-suite split is not built.
- **Honest seams to know about:** the REST layer (`@athena/api`) runs over an
  **in-memory store**, not yet wired to the Drizzle schema in `@athena/db`; the
  Rust Boolean operations are **AABB approximations**, not exact B-rep Booleans;
  `@athena/apps` holds application _contracts_, not a deployed UI.

## Workspace Shape

```text
libs/athena/
  core/            ← foundation: types, Zod schemas, calculators, compatibility matrix
  cad/             ← parametric CAD (TS) + capability manifest over the Rust kernel
  cad-topology-rust/ ← Rust B-rep/NURBS/feature/constraint/SIMP kernel (+ WASM exports)
  cam/  cnc/  additive/  robotics/  simulation/   ← engineering + production floor
  electronics/  acoustics/  firmware/  iot/        ← smart-product engineering
  materials/                                       ← material science + selection
  woodcraft/ metalcraft/ glasscraft/ luthiery/ living/
  upholstery/ finishing/ restoration/ packaging/ aftercare/   ← craft verticals
  workshop/ production/ supply/                    ← shop-floor operations + MES + supply chain
  erp/ quality/ studio/ marketplace/ sustainability/ compliance/ academy/  ← business surfaces
  apps/ ai/ biome/ integration/                    ← platform + cross-domain hub
  db/              ← Drizzle schema, migration, seed, connection config
  api/             ← REST/WebSocket gateway, RBAC, rate limits, observability
  infrastructure/  ← MQTT/Kafka/MinIO/edge/Grafana topology

libs/contracts/athena/   ← @contracts/athena: events, GraphQL SDL, gRPC proto, OpenAPI
```

The diagram below shows how the layers depend on each other and where data
crosses the boundary to the Rust kernel, the database, and other domains.

```mermaid
flowchart TB
  subgraph Foundation
    core["@athena/core\ntypes · Zod schemas · calculators · adhesive matrix"]
    contracts["@contracts/athena\nevents · GraphQL · gRPC · OpenAPI"]
  end

  subgraph Platform_Edges
    db["@athena/db\nDrizzle · Timescale · pgvector"]
    api["@athena/api\nREST · WS · RBAC · rate limit · metrics"]
    infra["@athena/infrastructure\nMQTT · Kafka · MinIO · edge nodes"]
  end

  subgraph Engineering
    cad["@athena/cad"]
    kernel["cad-topology-rust\n(Rust + WASM)"]
    cam["@athena/cam"]
    sim["@athena/simulation"]
    smart["electronics · firmware · iot · acoustics"]
  end

  subgraph Domain_Logic
    craft["craft verticals\nwood · metal · glass · luthiery · living · …"]
    floor["workshop · production · supply\ncnc · additive · robotics"]
    biz["erp · quality · marketplace · studio\nsustainability · compliance · academy"]
  end

  integration["@athena/integration"]
  external["Seshat · Brigid · Freya · Cybele/Aglaea\nEuterpe · Demeter · Maat · Asase"]

  core --> cad & cam & sim & craft & floor & biz & smart & api & db
  cad --> kernel
  contracts --> api
  api --> db
  infra -.deploys.-> api
  integration --> external
  core --> integration
  contracts --> integration
```

## Foundation — `@athena/core`

`@athena/core` is the package every other Athena library depends on; its public
surface is re-exported through four modules in `libs/athena/core/src/index.ts`:

- **`types.ts`** — the domain's nominal type system. Branded identifiers
  (`ProductId`, `VariantId`, `BOMId`, `MaterialLotId`, `WorkOrderId`,
  `MachineId`, `CustomerId`, `SupplierId`, `CADModelId`) prevent passing one ID
  where another is expected. It models materials (`WoodSpecies` with Janka
  hardness and radial/tangential shrinkage; `MetalAlloy` with tensile/yield
  strength and machinability; `GlassType`, `Textile`, `Adhesive`, `Finish`,
  `CompositeType`, `BioMaterial`, `Fastener`, `MaterialLot`), products
  (`FurnitureProduct`, `MusicalInstrument`, and the extending `SmartFurniture`
  and `LivingFurniture`), workshop equipment (`Machine`, `HandTool`,
  `PowerTool`, `KilnType`, `SprayBooth`, `DustCollection`, `SafetyEquipment`),
  manufacturing (`WorkOrder`, `RoutingOperation`, `CNCProgram`, `RobotProgram`,
  `QualityCheckpoint`, `NonConformance`, `ProductionBatch`, `OEERecord`,
  `KanbanCard`), and business records (`Customer`, `Quote`, `SalesOrder`,
  `Invoice`, `Supplier`, `PurchaseOrder`, `WarrantyRecord`, `CostEstimate`).

  > **Note on the model.** The sibling `features.md` / `specifications.md` pages
  > describe three "anchor objects" — `DesignArtifact`, `FabricationJob`, and a
  > unified `Tool` with a `ready → due → locked_out → retired` lifecycle. The
  > implemented `@athena/core` realized the same intent with a
  > **WorkOrder-centric** model instead: `WorkOrderStatus`
  > (`draft → released → scheduled → in_progress → blocked → quality_hold → completed → cancelled`),
  > `MachineStatus`, and `condition` fields on hand tools. CAD versioning lives
  > in `@athena/db` (`athena_cad_models` / `athena_cad_model_versions`) and
  > `@athena/api`, not as a single `DesignArtifact`. Treat the WorkOrder model
  > as canonical; the anchor-object tables in the other two pages are the
  > original contract, not the as-built shape.

- **`schemas.ts`** — a Zod schema for essentially every type above, with
  **domain refinements** rather than shape-only validation: `MoneySchema`
  rejects sub-cent amounts; `MetalAlloySchema` rejects compositions summing over
  100.5%; `TextileSchema` requires fiber percentages to sum to 100;
  `OEERecordSchema` bounds availability/performance/quality to `[0,1]` and
  requires `periodEnd > periodStart`; `WarrantyRecordSchema` requires
  `endDate > startDate`. These are the runtime gate at API and ingestion
  boundaries.

- **`calculators.ts`** — real engineering math, not placeholders: unit
  conversions (length/mass/temperature), `calculateStressMpa` /
  `calculateStrain` / `isStressWithinAllowable` (with a safety factor), an
  `estimateEquilibriumMoistureContent` curve for wood, a sheet-metal gauge
  table, glass-weight, board-foot and linear-foot calculators,
  `calculateStringResonantFrequencyHz` (Mersenne's law for luthiery),
  `calculateHelmholtzFrequencyHz` (enclosure port tuning), RGB↔CMYK conversion,
  and a `parseGCode` / `validateGCode` pair that tokenizes G/M/T words and flags
  motion commands missing axis words.

- **`material-compatibility.ts`** — a `MATERIAL_COMPATIBILITY_MATRIX` mapping
  adhesive chemistries to material families with bond strength and workshop
  notes (PVA→wood, hide glue→reversible luthiery joints, epoxy→wood/metal/glass/
  composite, etc.), plus `recommendAdhesivesForFamilies` which ranks candidates
  by strength.

## Cross-Domain Contracts — `@contracts/athena`

`libs/contracts/athena/` is the integration contract surface, deliberately kept
out of `@athena/core` so external domains can depend on contracts without
pulling in the implementation. `src/index.ts` re-exports five module families:

- **`events.ts`** — `AthenaDomainEventSchema` with seven typed event kinds
  (`athena.product.created`, `athena.production.started`/`.completed`,
  `athena.quality.passed`/`.failed`, `athena.iot.telemetry.received`,
  `athena.shipment.dispatched`), each carrying `correlationId`, `aggregateType`,
  and `occurredAt`, plus the canonical Kafka topic names.
- **`grpc.ts`** — a proto3 IDL string defining `AthenaCadKernel`
  (`ValidateModel`, `ExportModel`), `AthenaSimulation` (`RunSimulation`), and
  `AthenaCnc` (`GenerateToolpath`) — the internal low-latency service contracts.
- **`graphql.ts`** — a GraphQL SDL string for product/material/production
  queries.
- **`openapi.ts`** / **`api-schemas.ts`** / **`integration.ts`** — the REST and
  cross-domain request/response schemas.

## Persistence — `@athena/db`

`libs/athena/db/src/schema.ts` defines **29 Drizzle tables** plus four Postgres
enums (`athena_product_status`, `athena_work_order_status`,
`athena_machine_status`, `athena_quality_result`). The schema spans the whole
domain: products and a self-referential category tree, lot-tracked material
inventory, CAD models _with branchable version history_
(`athena_cad_models.active_version_id` → `athena_cad_model_versions` keyed by
`(modelId, revision)`), workshop facilities/zones/machines/tools, production and
work orders with routing operations, suppliers/purchase-orders/receiving,
quality inspections and non-conformances, customers/quotes/orders, IoT devices,
living-system species plans, instrument specifications, CNC and robot programs,
and an employee skill matrix.

Three storage classes are mixed deliberately, matching the spec's intent:

- **Relational** rows for products, orders, inventory, and quality.
- **Time-series** hypertable-style tables keyed by `(id, time)` —
  `athena_machine_telemetry` (spindle load, temperature, vibration, tool wear)
  and `athena_living_sensor_readings` (pH, EC, humidity, light, water level) —
  with the migration enabling the `timescaledb` extension.
- **Vector** columns — `vector('embedding', { dimensions: 1536 })` on
  `athena_products` and a general `athena_ai_embeddings` table, with `pgvector`
  enabled.

The bootstrap migration `drizzle/0000_athena_initial_schema.sql` enables
`uuid-ossp`, `pgcrypto`, `pg_trgm`, `vector`, and `timescaledb`.
`src/connection.ts` distinguishes a **PgBouncer-pooled URL (port 6432)** from a
**direct URL (5432)** and carries statement timeout, pool size, and
`application_name`. `src/seed.ts` ships real reference data — the West-African
wood species mentioned above, with botanical names, Janka hardness, and density.

## API and Realtime — `@athena/api`

`libs/athena/api/src/index.ts` is a complete, self-contained gateway layer:

- **Route table** — `ATHENA_ROUTE_DEFINITIONS` enumerates every endpoint (CAD
  models + versions + export, production orders + scheduling, inventory
  receipts/adjustments, procurement, IoT devices + telemetry) with its HTTP
  method, required roles, optional Zod body schema, and a per-route rate-limit
  window. `dispatchAthenaRoute` does `:param` path matching;
  `authorizeAthenaRole` enforces the role set
  (`designer | machinist | operator | manager | customer | service_agent`);
  `createAthenaRateLimitKey` builds the limiter key.
- **Request handler** — `createAthenaRestApi` validates the body against the
  route schema (returning a structured `400` on failure), checks authorization
  (`403`), dispatches, and returns proper status codes (`200/201/202/204/404`).
- **State** — backed by `createInMemoryAthenaApiStore`, a fully-working
  in-memory store (CAD model archival, version sequencing, inventory
  adjustments, telemetry-driven device state). This is the **honest seam**: it
  is a real REST API, but it is not yet wired to the Drizzle schema in
  `@athena/db`.
- **Realtime** — `createAthenaWebSocketServer` with four channels (machine
  status, production tracking, sensor feed, quality events) and
  `subscribe`/`publish`/`subscriberCount` semantics.
- **Observability and resilience** — `ATHENA_PROMETHEUS_METRICS` names (API
  latency/throughput, machine utilization, OEE, telemetry ingest), a
  correlation-ID structured-log builder, and an `isAthenaCircuitOpen`
  circuit-breaker predicate. The OpenAPI 3.1 path object
  (`ATHENA_API_OPENAPI_SPEC`) and Kafka topic map are exported here too.

## Deployment Topology — `@athena/infrastructure`

`libs/athena/infrastructure/src/index.ts` declares the operational fabric as
data: the `ATHENA_ENVIRONMENT_KEYS` contract (database, MQTT, Kafka, InfluxDB,
MinIO, gateway port), MQTT topic templates (`athena/machines/+/telemetry`,
`athena/living/+/sensors`, `athena/devices/+/ota/status`), Kafka topic
definitions with partition counts and retention windows, MinIO bucket names (CAD
models, CNC programs, firmware images, quality media, assembly instructions),
edge-node service assignments (CNC cell, living-furniture controller,
quality-vision), and Grafana dashboard definitions. This package is
configuration/topology, not a running service.

## The Geometry Kernel — `cad-topology-rust`

The one non-TypeScript package, `libs/athena/cad-topology-rust/`, is where the
Phase-136 "sovereign CAD kernel" ambition is actually realized in part. It is
plain Rust (`std` only, no external crates), which keeps it portable and lets it
compile to `wasm32-unknown-unknown` for browser delivery.

`src/kernel.rs` (≈2,270 lines) implements:

- **Linear algebra and meshes** — `Point2/3`, `Vector3` (dot/cross/normalize),
  `BoundingBox` (union/intersection/volume), and `TriangleMesh` with
  `surface_area`, an edge-count-based `is_watertight`, and transforms.
- **B-rep topology** — `BrepVertex/Edge/Loop/Face/Shell/Solid`, built from a
  mesh in `BrepSolid::from_mesh`, with `box_solid`, signed-tetrahedron
  `volume_mm3` (divergence theorem), `validate_topology` (dangling-reference
  checks), and `calculate_brep_mass_properties` (bounding box, centroid, and a
  per-axis inertia tensor when a density is supplied).
- **Feature operations** — `extrude_profile`, `revolve_profile`,
  `sweep_profile`, `loft_profiles`, `shell_solid`, `apply_draft_angle`,
  `fillet_edges`, `chamfer_edges`, and linear/circular/mirror patterns via
  `Transform3`.
- **Free-form geometry** — `NurbsCurve` and `NurbsSurface` with de-Boor basis
  evaluation, Boehm **knot insertion**, **degree elevation**, surface offset,
  and tessellation; `subdivide_mesh_midpoint` for refinement.
- **Constraints** — `solve_geometric_constraints` runs an iterative relaxation
  over `Distance`, `Angle`, `TangentToLine`, `Coincident`, and `Symmetry`
  constraints.
- **WASM boundary** — `browser_cad_wasm_manifest()` plus
  `#[no_mangle] extern "C"` exports (`athena_cad_kernel_version`,
  `athena_box_volume_mm3`) targeting WebGL2/ WebGPU front-ends.

`src/lib.rs` adds `optimize_simp_grid` — a **SIMP (Solid Isotropic Material with
Penalization) topology optimizer** over a voxel grid, with a load-driven
sensitivity field, volume-fraction normalization, compliance tracking, and an
iteration history; its tests assert that material concentrates toward the load
path and that fixed voxels stay solid.

> **Honest approximations (documented, not stubs).** `boolean_solids`
> (union/intersection/difference) operates on **axis-aligned bounding boxes** —
> it returns an _estimated_ volume and AABB slab decomposition, not an exact
> B-rep Boolean. `fillet_edges`/`chamfer_edges` tag edges and apply a
> volume-removal heuristic (removal factors `0.215`/`0.5`) rather than
> reconstructing exact blend surfaces. The constraint solver is sequential
> relaxation, not the Newton/Levenberg-Marquardt graph-decomposition solver the
> Phase-136 spec ultimately wants. These are real, bounded algorithms chosen for
> a first kernel; they are the kernel's main upgrade points.

## Engineering, Craft, Production, and Business Layers

The remaining ~30 TypeScript packages each follow the same shape: an `index.ts`
that exports a typed **capability registry** (id, label, pillar,
`locallyActionable`, and the `evidence` files backing each claim) plus one
sibling module per sub-discipline carrying the real logic. They are genuine
domain code, not CRUD shells — for example:

- **Engineering / smart products** — `@athena/cad` (TS geometry + history +
  parametric + assembly + drawing + format exchange, delegating heavy geometry
  to the Rust kernel), `@athena/cam` (`toolpaths.ts` generates 2D/profile
  toolpaths with feeds, nesting, and collision fixtures), `@athena/simulation`,
  `@athena/electronics`, `@athena/acoustics`, `@athena/firmware`, `@athena/iot`.
- **Materials** — `@athena/materials` splits into wood/metal/glass/composite-bio
  and adhesive-fastener science plus a `material-selection-engine`.
- **Craft verticals** — `@athena/woodcraft`'s `joinery-intelligence.ts` ranks
  joint types and emits a `AthenaCncJoineryToolpath` (e.g. a parametric dovetail
  layout with pin/tail geometry and CNC operations); `@athena/luthiery`
  (1072-line test suite), `@athena/metalcraft`, `@athena/glasscraft`,
  `@athena/living`, `@athena/upholstery`, `@athena/finishing`,
  `@athena/restoration`, `@athena/packaging`, `@athena/aftercare`.
- **Production floor** — `@athena/cnc`, `@athena/additive`, `@athena/robotics`,
  `@athena/workshop` (space/tools/safety/energy), `@athena/production` (MES:
  work orders, scheduling, BOM, lean, capacity), `@athena/supply` (procurement,
  inventory, logistics, traceability).
- **Business and platform** — `@athena/erp`, `@athena/quality`,
  `@athena/studio`, `@athena/marketplace`, `@athena/sustainability`,
  `@athena/compliance`, `@athena/academy`, `@athena/apps` (application
  _contracts_ for the eventual mobile/web surfaces — no app is deployed),
  `@athena/ai`, `@athena/biome`.

## Cross-Domain Integration — `@athena/integration`

`libs/athena/integration/src/index.ts` registers a capability list and
re-exports nine adapter modules, one per neighboring domain: `brigid`
(workshop-automation foundations Athena is meant to build on), `seshat`
(craft/heritage knowledge), `freya` (fashion/luxury manufacturing),
`aglaea-cybele` (textiles + BIM coordination), `euterpe` (luthiery/acoustics for
music creation), `demeter` (plant intelligence for living furniture), `asase`
(food-producing biomes / aquaponics), `maat` (organization intelligence), and an
`additional-domain-integration` catch-all. Each adapter is a real typed surface
— `seshat-integration.ts`, for instance, version-pins the Seshat packages it
consumes and defines joinery/material/design/workshop/biophilic/academy adapters
with explicit input and output contracts. Concentrating these here keeps the
other 30+ packages free of direct dependencies on external-domain schemas.

## Invariants, Failure Modes, and Extension Points

- **Validate at the edge.** `@athena/core`'s Zod schemas with domain refinements
  are the gate; the REST handler in `@athena/api` returns a structured `400`
  before any handler runs. New entities should arrive with both a `types.ts`
  interface and a refined `schemas.ts` schema.
- **Branded IDs are load-bearing.** The `Brand<T, Name>` pattern in `types.ts`
  is the compile-time guard against ID confusion across the ~40 packages; reuse
  the existing brands rather than passing bare `string`.
- **The store/DB gap is the headline failure mode.** `@athena/api` persists to
  an in-memory map. Wiring `AthenaRestApiStore` to the Drizzle tables in
  `@athena/db` (and honoring the PgBouncer vs direct connection split) is the
  most consequential next step; until then, API data does not survive a restart.
- **Geometry precision is the kernel's failure mode.** Any workflow that needs
  an _exact_ Boolean result, a true fillet surface, or a globally-consistent
  constraint solve must treat the current Rust kernel results as estimates. The
  upgrade path is exact B-rep Booleans and a graph-decomposition constraint
  solver, both isolated inside `cad-topology-rust`.
- **Capability registries are the extension contract.** Each package's
  `index.ts` registry, with its `evidence` file list, is how a new
  sub-discipline announces itself and how the domain is audited for substance
  vs. stubs. Add a registry entry _and_ its backing module together.
- **WASM is a real delivery target.** Because the Rust kernel is `std`-only with
  `#[no_mangle]` exports, it can ship to the browser without a binding layer —
  the extension point for an in-browser CAD/HMI surface.

## Relationship to Neighboring Domains

The boundaries below reflect ownership decisions; the integration adapters make
them explicit rather than implicit.

- **Seshat** owns canonical craft/design/heritage knowledge; Athena consumes it
  through `seshat-integration.ts` and must not silently duplicate it. The
  long-running question of where Seshat ends and Athena begins is still open and
  should be resolved as both domains mature.
- **Brigid** owns industrial-scale factory automation (PLC/SCADA/energy). Athena
  is intended to layer furniture/instrument semantics on top of Brigid, not to
  re-implement generic automation.
- **Freya** owns fashion/luxury manufacturing; the seam is upholstery and
  textiles. **Cybele/Aglaea** own the built environment and BIM; Athena makes
  the furniture and fixtures that go inside, bridged via the `aglaea-cybele`
  adapter.
- **Euterpe / Demeter / Asase / Maat** consume or feed Athena for music
  instruments, plant intelligence, food-biome systems, and business rollups
  respectively.
- **Neith** is the planned substrate for the _full_ sovereign Phase-136 kernel
  (runtime, renderer, GPU, file I/O, UI). As built, `cad-topology-rust` is
  **standalone** and does not yet depend on Neith; that dependency is part of
  the Phase-136 remainder, not current reality.
