# Athena Domain - Technical Specifications

> Planned Maker Intelligence and Workshop Operations Platform (TODO Phases 67
> and 136)

This document is the design contract for the Athena domain. It specifies the
TypeScript interfaces, state machines, API families, persistence plan,
cross-domain boundaries, and acceptance criteria that future Athena packages
must implement. Reading this alongside `features.md` (the behavioral description
of each package) and `architecture.md` (the bounded context and layering model)
gives a complete picture of what Athena will be.

## Status

**Planned / design-level specification.** No workspace packages exist for this
domain. A directory scan of `libs/`, `apps/`, and `services/` returns no
`athena` entry, and no `package.json` declares an `@athena/*` name anywhere in
the monorepo. Every schema, enum, state machine, API family, event, and
requirement documented below is therefore a _design contract_ drawn from the
domain's planning documents, not a description of running code.

This specification is grounded exclusively in:

- `DOMAINS/athena/features.md` — the domain feature description.
- `DOMAINS/athena/architecture.md` — the planned bounded context.
- `TODOS/phase-67.md` — "Athena: Maker Intelligence & Workshop Operations
  Platform" (1,636 planned tasks across 37 library sections).
- `TODOS/phase-136.md` — "Athena Sovereign CAD / EDA / CAM / GIS Kernel" (425
  planned tasks across 10 library sections).

When packages are created, each section here becomes the acceptance contract for
its package, and this document must be re-grounded in the implemented code (real
TypeScript interfaces, Zod schemas, Drizzle migrations, route handlers, event
constants). Until then it remains a planned specification.

## Scope and Purpose

Athena is the planned Oshun domain for maker operations and workshops. It is
named for the Greek goddess of crafts, practical arts, invention, and strategic
wisdom — patroness of artisans, known by the epithet **"Ergane"** ("the
worker"). The domain covers the full software stack for autonomous furniture
manufacturing, musical-instrument luthiery, multi-material workshop operations,
and smart/living furniture production: embedded firmware and IoT device control,
CAD/CAM design, CNC toolpath generation, robotic fabrication, acoustic
simulation, supply chain, quality assurance, and e-commerce.

The planning split is two phases:

- **Phase 67 — Maker and Workshop Operations.** The workshop operating system:
  core entities, craft verticals, smart-product engineering, the production
  floor, and the business and learning surfaces around them.
- **Phase 136 — Sovereign CAD / EDA / CAM / GIS Kernel.** Makes Athena the owner
  of a sovereign engineering design kernel that replaces proprietary CAD, EDA,
  CAM, and GIS applications. The division of labour is fixed: **Neith** provides
  the low-level runtime, renderer, GPU compute, file I/O, UI, collaboration, and
  platform substrate; **Athena** owns the engineering semantics — geometry,
  constraints, manufacturing outputs, design validation, and the domain feature
  set. The kernel is planned in Rust with optional WASM delivery, interoperating
  with STEP / IGES / JT / Parasolid / ACIS, and feeding both desktop authoring
  (`@athena/cad-studio`) and headless batch pipelines.

## Planned Package Prefix

- Libraries: `@athena/*`.
- Cross-domain contracts: `libs/contracts/athena/` (`@contracts/athena`),
  holding cross-domain API contracts and Zod schemas (phase-67 task 67.1.1.36).

## Planned Technology Stack

The phase documents fix the following stack choices for the domain:

- **TypeScript** — orchestration, APIs, business logic, dashboards.
- **Rust** — CAD kernel, simulation engines, CNC toolpath generation, real-time
  control, the Phase 136 geometric kernel and constraint solver (with optional
  WASM delivery).
- **C / C++** — firmware (ESP32, STM32), DSP audio processing, machine
  controller interfaces.
- **Python** — ML/AI models: computer vision, defect detection, acoustic
  analysis, generative design.
- **Node.js** runtime with native modules for industrial protocol bridges.
- **PostgreSQL** with **TimescaleDB** for sensor telemetry, **pgvector** for AI
  embeddings, **PostGIS** for logistics.
- **Redis** for real-time caching, **MQTT** for IoT messaging, **Matter/Thread**
  for smart-home integration.
- **InfluxDB** for high-frequency machine telemetry.
- **Kafka** for event streaming across the factory floor and enterprise systems.
- **Docker / Kubernetes** for edge deployment, **WASM** for browser-based CAD
  and HMI interfaces.
- **React Native** for mobile apps; **WebGL / WebGPU** for 3D visualization.

ORM and migrations are planned on **Drizzle ORM** (phase-67 task 67.1.2.20),
with **PgBouncer** connection pooling (67.1.2.22).

---

## Core Domain Objects

`features.md` defines three core domain objects that anchor every package, with
five branded ID types. The `@athena/core` package (phase-67 §67.2) is the
foundation: the primitives every other package depends on. The TypeScript shapes
below are the design contract carried in the current `specifications.md` and
`features.md`; expanded entity coverage from the phase doc follows.

### Branded Identifier Types

All core entity references use nominal (branded) string types so that an ID of
one kind cannot be passed where another is expected at compile time. The five
primary ID types used across the anchor objects are:

| Type               | Underlying | Identifies                                        |
| ------------------ | ---------- | ------------------------------------------------- |
| `WorkshopId`       | `string`   | A workshop / shop facility.                       |
| `DesignId`         | `string`   | A `DesignArtifact`.                               |
| `MaterialLotId`    | `string`   | A received lot of material with chain-of-custody. |
| `FabricationJobId` | `string`   | A unit of physical making.                        |
| `ToolId`           | `string`   | A physical or machine tool.                       |

These are nominal (branded) string types so an ID of one kind cannot be passed
where another is expected. `@athena/core` is planned to provide factory
functions for the wider ID family — `ProductId`, `VariantId`, `BOMId`,
`InstrumentId`, `ComponentId` — alongside these five (phase-67 task 67.2.2.11).

### `DesignArtifact`

A `DesignArtifact` represents any design output of the maker workflow: a CAD
model, a production drawing, a G-code toolpath, embedded firmware, a cutting
pattern, or a set of assembly instructions. The key design decision is that
`DesignArtifact` has a strict lifecycle — only a `released` artifact can drive a
fabrication job or appear in the marketplace, which prevents untested or
unapproved designs from reaching the shop floor or customers.

```typescript
interface DesignArtifact {
  id: DesignId;
  artifactType:
    | 'cad_model'
    | 'drawing'
    | 'toolpath'
    | 'firmware'
    | 'pattern'
    | 'assembly_instruction';
  version: string;
  materialRequirements: MaterialLotId[];
  status: 'draft' | 'validated' | 'released' | 'archived';
}
```

| Field                  | Type              | Required | Meaning                                                                                      |
| ---------------------- | ----------------- | -------- | -------------------------------------------------------------------------------------------- |
| `id`                   | `DesignId`        | Yes      | Stable branded identifier for the artifact.                                                  |
| `artifactType`         | enum (6 values)   | Yes      | The kind of design output (see enum below).                                                  |
| `version`              | `string`          | Yes      | Version label. Released artifacts are versioned and reproducible (Hard Requirement 2).       |
| `materialRequirements` | `MaterialLotId[]` | Yes      | The material lots the artifact's bill of material depends on; drives costing and provenance. |
| `status`               | enum (4 values)   | Yes      | Lifecycle state; see the `DesignArtifact` state machine below.                               |

#### `artifactType` enum

| Value                  | Meaning                                                                        |
| ---------------------- | ------------------------------------------------------------------------------ |
| `cad_model`            | A parametric or B-rep 3D CAD model (produced by `@athena/cad` / `cad-studio`). |
| `drawing`              | A production / shop technical drawing generated from a model.                  |
| `toolpath`             | A CAM toolpath that post-processes to G-code (produced by `@athena/cam-*`).    |
| `firmware`             | Embedded software for a smart product (produced by `@athena/firmware`).        |
| `pattern`              | A cutting / sewing pattern (e.g. upholstery, textile work).                    |
| `assembly_instruction` | A sequenced set of assembly steps for a product.                               |

#### `DesignArtifact.status` enum

| Value       | Meaning                                                                                                        |
| ----------- | -------------------------------------------------------------------------------------------------------------- |
| `draft`     | Work in progress; not yet checked.                                                                             |
| `validated` | Passed design validation (geometry / buildability checks); still work in progress.                             |
| `released`  | Frozen and approved; **only `released` artifacts may drive a `FabricationJob` or back a marketplace listing**. |
| `archived`  | Superseded by a newer revision but retained for traceability.                                                  |

### `FabricationJob`

A `FabricationJob` is a unit of physical making — the execution of a released
design on the shop floor. It links a workshop, a design, a fabrication process,
and a status. The status lifecycle models the real-world flow from planning
through active fabrication, inspection, and either successful completion or
failure. The guard on the `queued → running` transition is the enforcement point
for Hard Requirement 1: a job cannot start on a locked-out tool, and an
uncertified artisan cannot be assigned to a certification-required tool.

```typescript
interface FabricationJob {
  id: FabricationJobId;
  workshopId: WorkshopId;
  designId: DesignId;
  process:
    | 'cnc'
    | 'additive'
    | 'woodcraft'
    | 'metalcraft'
    | 'glasscraft'
    | 'electronics'
    | 'assembly'
    | 'finishing';
  status:
    | 'planned'
    | 'queued'
    | 'running'
    | 'inspection'
    | 'complete'
    | 'failed';
}
```

| Field        | Type               | Required | Meaning                                                        |
| ------------ | ------------------ | -------- | -------------------------------------------------------------- |
| `id`         | `FabricationJobId` | Yes      | Stable branded identifier for the job.                         |
| `workshopId` | `WorkshopId`       | Yes      | The workshop the job runs in.                                  |
| `designId`   | `DesignId`         | Yes      | The `DesignArtifact` the job executes.                         |
| `process`    | enum (8 values)    | Yes      | The fabrication process used (see enum below).                 |
| `status`     | enum (6 values)    | Yes      | Lifecycle state; see the `FabricationJob` state machine below. |

#### `FabricationJob.process` enum

| Value         | Meaning                                                    |
| ------------- | ---------------------------------------------------------- |
| `cnc`         | Subtractive CNC machining (`@athena/cnc`).                 |
| `additive`    | Additive manufacturing / 3D printing (`@athena/additive`). |
| `woodcraft`   | Woodworking craft processes (`@athena/woodcraft`).         |
| `metalcraft`  | Metalworking craft processes (`@athena/metalcraft`).       |
| `glasscraft`  | Glasswork craft processes (`@athena/glasscraft`).          |
| `electronics` | Electronics fabrication (`@athena/electronics`).           |
| `assembly`    | Assembly of components into a finished product.            |
| `finishing`   | Surface finishing processes (`@athena/finishing`).         |

#### `FabricationJob.status` enum

| Value        | Meaning                                                         |
| ------------ | --------------------------------------------------------------- |
| `planned`    | Created and scheduled, not yet released to the floor.           |
| `queued`     | Released; waiting for a machine / work centre to free up.       |
| `running`    | Actively being fabricated.                                      |
| `inspection` | Fabrication finished; awaiting the quality gate.                |
| `complete`   | Passed inspection; terminal success state.                      |
| `failed`     | Reached from `running` or `inspection`; terminal failure state. |

### `Tool`

A `Tool` is any physical or machine tool in the workshop — from a hand chisel to
a 5-axis CNC router to a collaborative robot. The two safety-relevant fields are
`certificationRequired` (an operator needs a documented certification before
being assigned this tool) and `maintenanceStatus` (the current availability and
safety state of the tool). Both fields are enforced at job assignment, not just
tracked for reference.

```typescript
interface Tool {
  id: ToolId;
  toolType:
    | 'hand_tool'
    | 'cnc_machine'
    | 'printer'
    | 'robot'
    | 'kiln'
    | 'lathe'
    | 'loom'
    | 'test_fixture';
  certificationRequired: boolean;
  maintenanceStatus: 'ready' | 'due' | 'locked_out' | 'retired';
}
```

| Field                   | Type            | Required | Meaning                                                                        |
| ----------------------- | --------------- | -------- | ------------------------------------------------------------------------------ |
| `id`                    | `ToolId`        | Yes      | Stable branded identifier for the tool.                                        |
| `toolType`              | enum (8 values) | Yes      | The kind of tool (see enum below).                                             |
| `certificationRequired` | `boolean`       | Yes      | Whether an artisan must hold a certification to be assigned this tool.         |
| `maintenanceStatus`     | enum (4 values) | Yes      | Maintenance / safety state; see the Tool Certification & Safety state machine. |

#### `Tool.toolType` enum

| Value          | Meaning                                                         |
| -------------- | --------------------------------------------------------------- |
| `hand_tool`    | A non-powered or hand-held tool (chisel, plane, hammer, clamp). |
| `cnc_machine`  | A CNC router / mill.                                            |
| `printer`      | An additive-manufacturing machine.                              |
| `robot`        | A workshop robot or machine-tending arm.                        |
| `kiln`         | A glass-annealing/fusing, wood-drying, or ceramic kiln.         |
| `lathe`        | A turning machine.                                              |
| `loom`         | A weaving / textile machine.                                    |
| `test_fixture` | A fixture used for inspection / testing.                        |

#### `Tool.maintenanceStatus` enum

| Value        | Meaning                                                                                                                          |
| ------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `ready`      | The tool passed its last maintenance check; jobs may run.                                                                        |
| `due`        | A scheduled maintenance interval has elapsed; jobs may still run but the operator is warned and the next check is escalated.     |
| `locked_out` | The tool failed inspection, reported an incident, or was manually locked by a supervisor; **no `FabricationJob` may run on it**. |
| `retired`    | The tool is permanently withdrawn; it cannot be used and cannot return to service.                                               |

---

## State Machines

The four state machines below are the behavioral backbone of `@athena/core`.
They enforce the domain's safety and traceability guarantees at the transition
level — not as runtime checks scattered across packages, but as a single
authoritative source that every package calls. Each transition is stamped with
the actor who triggered it and the timestamp, creating an audit trail.

`@athena/core` owns the two primary artifact/job transition graphs, rejecting
illegal transitions and stamping each transition with actor and timestamp
(phase-67 task 67.2 state-machine spec; `features.md` "Foundation").

### `DesignArtifact` Lifecycle

States: `draft`, `validated`, `released`, `archived`.

| From        | To          | Trigger                                                                                                                    |
| ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------- |
| `draft`     | `validated` | The model passes design validation — geometry buildability checks (`@athena/cad`); for a `toolpath` artifact, geometry QA. |
| `validated` | `released`  | The artifact is frozen and approved; for a `toolpath`, only after passing the Manufacturing Validation Gate (below).       |
| `released`  | `archived`  | A newer revision supersedes the artifact; the old version is retained for traceability.                                    |

- `released` is the only status from which an artifact may drive a
  `FabricationJob` or back a marketplace listing.
- `archived` is terminal: a superseded artifact is retained but not reactivated;
  a new revision is a new artifact version.
- AI assistance proposes changes but never auto-releases an artifact (phase-136
  "Kernel-Wide Features → AI assistance").

### `FabricationJob` Lifecycle

States: `planned`, `queued`, `running`, `inspection`, `complete` (terminal),
`failed` (terminal).

| From         | To           | Trigger / Guard                                                                                                         |
| ------------ | ------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `planned`    | `queued`     | The job is released to the production floor.                                                                            |
| `queued`     | `running`    | A machine / work centre is free **and** the job's design is `released` **and** the required tools are not `locked_out`. |
| `running`    | `inspection` | Fabrication completes.                                                                                                  |
| `running`    | `failed`     | Fabrication aborts (machine fault, material failure, operator stop).                                                    |
| `inspection` | `complete`   | The job passes the craft vertical's `inspection`-stage quality gate.                                                    |
| `inspection` | `failed`     | The job fails the quality gate.                                                                                         |

Guards on `queued → running` (Hard Requirement 1, see below):

- The job's `DesignArtifact` must be in status `released`.
- Every required `Tool` must have `maintenanceStatus` other than `locked_out`
  and other than `retired`.
- For any required `Tool` whose `certificationRequired` is `true`, the assigned
  artisan must hold a current certification; an uncertified assignment is
  **rejected**, not warned.

### Tool Certification and Safety Lockout State Machine

Owned across `@athena/workshop` and `@athena/quality`, this enforces Hard
Requirement 1 (`features.md` "Production Floor"). A `Tool`'s `maintenanceStatus`
follows:

| State        | Job execution                                                  | Transitions out                                                                                                |
| ------------ | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `ready`      | Allowed.                                                       | → `due` when a maintenance interval elapses; → `locked_out` on failed inspection / incident / supervisor lock. |
| `due`        | Allowed, with an operator warning and an escalated next check. | → `ready` on a passed maintenance check; → `locked_out` on failed inspection / incident / supervisor lock.     |
| `locked_out` | **Blocked entirely.** The lockout records actor and reason.    | → `ready` only via an explicit passed-maintenance event; → `retired`.                                          |
| `retired`    | **Blocked entirely.**                                          | None — `retired` is terminal; the tool cannot return to service.                                               |

Independently of `maintenanceStatus`, a `certificationRequired` tool checks the
assigned artisan's certification record at job assignment.

### Work Order Lifecycle (`@athena/production`)

`@athena/production` adds a higher-level work-order state machine that drives
`FabricationJob`s through their state graph (phase-67 task 67.20.1.2):

`created → released → in-progress → quality hold → completed → shipped`

with state transitions and authorization. A `quality hold` state can spawn a
rework work order specifying rework operations, material additions, and
additional time (67.20.1.6).

---

## Hard Requirements

Four platform requirements constrain every package and are non-negotiable
(`features.md` "Hard Requirements"; `specifications.md` "Requirements"):

1. **Tool certification and safety state.** Machine-control workflows enforce
   tool certification and `maintenanceStatus`. A `FabricationJob` cannot run on
   a `locked_out` or `retired` tool, and cannot be assigned to an artisan
   lacking the required certification for a `certificationRequired` tool.
2. **Versioned, reproducible releases.** Released `DesignArtifact`s — including
   `cad_model`, `drawing`, `toolpath`, and `firmware` types — are versioned and
   reproducible. Re-running a `released` toolpath against the same stock and
   machine profile produces the same G-code.
3. **Provenance with evidence.** Material provenance and sustainability claims
   retain their supporting evidence. A claim ("FSC-certified oak", "recycled
   aluminium") is backed by a `MaterialLot` record with attached documentation,
   not asserted free-standing.
4. **Marketplace traceability.** Every marketplace listing links back to the
   `released` `DesignArtifact` it sells and the quality records of the
   `FabricationJob`s that produced it.

---

## Domain Entity Inventory (`@athena/core`)

The three anchor objects (`DesignArtifact`, `FabricationJob`, `Tool`) are the
minimum contract needed for cross-package coordination. The full `@athena/core`
package goes considerably deeper, modeling every entity class a workshop
business needs. The tables below describe the planned TypeScript types with
their key attributes; each will ship with a Zod schema for runtime validation.

Beyond the three anchor objects, `@athena/core` (phase-67 §67.2) is planned to
model the following entities and enumerations.

### Material Types (§67.2.1)

| Type            | Key planned attributes                                                                                                                                          |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WoodSpecies`   | Botanical name, common names, Janka hardness, density, grain pattern, workability, stability, toxicity, sustainability status (CITES, FSC).                     |
| `MetalAlloy`    | Composition, tensile strength, yield strength, hardness (Rockwell / Brinell / Vickers), melting point, thermal conductivity, weldability, machinability rating. |
| `GlassType`     | Composition (soda-lime, borosilicate, lead crystal), coefficient of thermal expansion, annealing temperature, softening point, optical properties.              |
| `Textile`       | Fibre content, weave pattern, weight (GSM), Martindale abrasion rating, Wyzenbeek cycles, colorfastness, fire rating.                                           |
| `Adhesive`      | Chemistry (PVA, epoxy, polyurethane, cyanoacrylate, hide glue, contact cement), open time, clamp time, shear strength, gap-filling capacity, temperature range. |
| `Finish`        | Chemistry (lacquer, varnish, shellac, polyurethane, oil, wax, water-based), VOC content, dry time, cure time, hardness, UV resistance.                          |
| `CompositeType` | Matrix material, reinforcement (carbon fibre, fibreglass, Kevlar), layup method, mechanical properties.                                                         |
| `BioMaterial`   | Mushroom leather, mycelium composites, hemp-lime, bamboo laminate, cork, reclaimed materials, with sustainability metrics.                                      |
| `Fastener`      | Category (screw, bolt, nail, dowel, cam lock, barrel nut, threaded insert), material, drive type, dimensions, load ratings.                                     |
| `MaterialLot`   | Lot number, supplier, purchase date, quantity, unit cost, location, chain-of-custody certification references.                                                  |

A **material compatibility matrix** records which adhesives work with which
materials, galvanic corrosion pairs, and thermal-expansion mismatches
(67.2.1.12).

### Product Types (§67.2.2)

| Type                   | Key planned attributes                                                                                                                                                                                |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `FurnitureProduct`     | Category (seating, table, storage, bed, desk, shelving, cabinet, outdoor), dimensions, weight, materials BOM, finish specification, assembly method.                                                  |
| `MusicalInstrument`    | Family (string, wind, percussion, keyboard, electronic), sub-type, tuning, range, materials, dimensions, acoustic specifications.                                                                     |
| `SmartFurniture`       | Extends `FurnitureProduct` with embedded electronics BOM, sensor list, actuator list, connectivity (BLE / WiFi / Matter), firmware version, power source.                                             |
| `LivingFurniture`      | Extends `FurnitureProduct` with plant species, grow-system type (NFT, DWC, ebb-flow, aeroponics), lighting spec, or aquarium type (freshwater, saltwater, reef), filtration, life-support parameters. |
| `ProductVariant`       | Configurable dimensions, material options, finish options, color options, hardware options.                                                                                                           |
| `BillOfMaterials`      | Multi-level BOM hierarchy (assembly → subassembly → part → raw material), quantities, waste factors, cost rollup.                                                                                     |
| `AssemblyInstruction`  | Step sequence, required tools, fastener list, illustrations, estimated time per step.                                                                                                                 |
| `ProductSpecification` | Engineering drawings, 3D model references, tolerance specifications, acceptance criteria.                                                                                                             |

#### `ProductLifecycle` enum (§67.2.2.9)

`Concept`, `Prototype`, `Production`, `Active`, `EndOfLife`, `Discontinued`,
`Archived`.

#### `ProductCategory` enum (§67.2.2.10)

A full taxonomy: 50+ furniture sub-categories and 40+ instrument sub-categories.

### Workshop and Equipment Types (§67.2.3)

| Type              | Key planned attributes                                                                                                                                                                        |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Workshop`        | Location, zones (woodshop, metalshop, finishing, assembly, electronics lab, CNC bay, storage), dimensions, capacity, operating hours.                                                         |
| `Machine`         | Category (CNC router, CNC mill, lathe, table saw, bandsaw, jointer, planer, drill press, welder, laser cutter, 3D printer, glass kiln), specifications, maintenance schedule, current status. |
| `HandTool`        | Category (chisel, plane, saw, hammer, screwdriver, clamp, measuring), specification, calibration status, assigned location.                                                                   |
| `PowerTool`       | Motor specs, RPM range, dust-collection compatibility, safety features, maintenance interval.                                                                                                 |
| `DustCollection`  | System layout, CFM requirements per machine, ductwork sizing, filter specifications, blast-gate configuration.                                                                                |
| `SprayBooth`      | Dimensions, airflow (CFM), filter type (dry / water wash), exhaust requirements, fire suppression.                                                                                            |
| `KilnType`        | Category (glass annealing, glass fusing, wood drying, ceramic), max temperature, chamber dimensions, heating elements, controller type.                                                       |
| `CompressedAir`   | Compressor specifications, distribution layout, CFM per outlet, pressure regulators, dryer/filter.                                                                                            |
| `SafetyEquipment` | PPE, fire extinguisher, first aid, emergency stop, light curtain, safety interlock, with inspection schedule and compliance status.                                                           |

#### `MachineStatus` enum (§67.2.3.9)

`Available`, `InUse`, `Maintenance`, `Breakdown`, `Setup`, `Calibrating`,
`Offline`.

### Manufacturing Types (§67.2.4)

| Type                | Key planned attributes                                                                                                                     |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `WorkOrder`         | Order number, product, quantity, priority, due date, routing (operation sequence), assigned machines, assigned operators, status tracking. |
| `RoutingOperation`  | Operation name, work centre, setup time, cycle time, tooling requirements, instructions, quality checkpoints.                              |
| `CNCProgram`        | Machine type, file format (G-code, HPGL), tool list, material, stock dimensions, estimated run time, simulation result.                    |
| `RobotProgram`      | Robot model, cell configuration, waypoints, speed/acceleration, gripper actions, safety-zone references.                                   |
| `QualityCheckpoint` | Measurement type (dimensional, visual, acoustic, strength), specification limits, gage R&R, sampling plan.                                 |
| `NonConformance`    | Defect category, severity, root cause (5-why), corrective action, disposition (rework, scrap, use-as-is, return), cost impact.             |
| `ProductionBatch`   | Batch number, product, quantity started, quantity completed, quantity scrapped, start/end time, yield percentage.                          |
| `OEERecord`         | Availability, performance, and quality factors with Pareto loss categorization.                                                            |
| `KanbanCard`        | Part, quantity, source location, destination, signal type (production, withdrawal, supplier).                                              |

### Business Types (§67.2.5)

| Type             | Key planned attributes                                                                                    |
| ---------------- | --------------------------------------------------------------------------------------------------------- |
| `Customer`       | Contact info, type (retail / wholesale / designer / architect), order history, preferences, credit terms. |
| `Quote`          | Line items, material costs, labor costs, overhead, margin, validity period, approval chain.               |
| `SalesOrder`     | Customer, line items, delivery address, shipping method, payment terms, fulfillment status.               |
| `Invoice`        | Line items, tax calculations, payment status, aging.                                                      |
| `Supplier`       | Contact info, materials supplied, lead times, quality rating, payment terms, certifications.              |
| `PurchaseOrder`  | Supplier, line items, delivery date, receiving status, three-way match (PO, receipt, invoice).            |
| `ShippingRecord` | Carrier, tracking number, package dimensions, weight, insurance, delivery confirmation.                   |
| `WarrantyRecord` | Product, customer, start date, duration, coverage terms, claims history.                                  |
| `CostEstimate`   | Material cost, labor cost, machine cost, tooling cost, overhead allocation, profit margin.                |

Business-type Zod schemas carry monetary-precision validation (67.2.5.10).

### Bills of Material and Work Instructions

A BOM links a design to its `MaterialLot` requirements and component quantities;
work instructions sequence the steps a `FabricationJob` executes (`features.md`
"@athena/core"). `@athena/production` extends this to a multi-level BOM with
engineering-vs-manufacturing BOM versions, effectivity dates, cost rollup
through all levels, where-used analysis, BOM diff, phantom levels, and
configurable variant-driven BOM (phase-67 §67.20.3).

### Shared Utilities and Validators (§67.2.6)

`@athena/core` is planned to provide: unit conversion for workshop units
(imperial/metric, board feet, sheet goods, linear feet, weight, volume);
engineering calculation validators (stress, strain, deflection, thermal
expansion, acoustic frequency, fluid flow); wood equilibrium-moisture-content
calculators; metal gauge conversion tables; glass weight calculator; board-foot
and linear-foot calculators with waste-factor estimation; acoustic frequency
calculators (resonant frequency, Helmholtz resonance, string vibration, air
column modes); color-space converters (RGB, CMYK, LAB, Munsell, RAL, Pantone,
NCS); and a G-code validator and parser.

---

## Event Contracts

`@athena/core` is planned to own typed domain events consumed by other packages
and downstream domains (`features.md` "@athena/core"; phase-67 task 67.1.3.18).
The named events are:

| Event                | Source / meaning                                           |
| -------------------- | ---------------------------------------------------------- |
| `design.released`    | A `DesignArtifact` transitioned to `released`.             |
| `job.status_changed` | A `FabricationJob` changed `status`.                       |
| `tool.locked_out`    | A `Tool` transitioned to `maintenanceStatus = locked_out`. |
| `material.received`  | A `MaterialLot` was received into inventory.               |
| `quality.recorded`   | A quality record was filed against a job.                  |

The factory-floor event bus is planned on **Kafka**. Phase-67 task 67.1.3.18
additionally names enterprise-level domain events on the bus — `OrderPlaced`,
`ProductionStarted`, `QualityPassed`, `ShipmentDispatched` — and task 67.1.4.3
plans Kafka topic families for machine events, production events, quality
events, and IoT events.

---

## Persistence

Athena's data has unusually varied characteristics: relational product and order
records, high-frequency machine telemetry, large binary files (CAD models, CNC
programs, firmware), and AI embeddings for defect detection and design
similarity. Each type is stored in the most appropriate system rather than
shoehorned into a single database.

Phase-67 §67.1.2 plans the PostgreSQL schema. The domain database is added to
the `docker-compose.dev.yml` `POSTGRES_MULTIPLE_DATABASES` set (task 67.1.4.10)
and to the per-domain isolation model.

### Relational Schemas (PostgreSQL, Drizzle ORM)

| Schema area           | Key fields / structure                                                                    |
| --------------------- | ----------------------------------------------------------------------------------------- |
| Products              | Furniture, instruments, components, with a hierarchical category model.                   |
| Materials inventory   | Lumber, metals, glass, electronics, textiles, adhesives, finishes, with **lot tracking**. |
| CAD models            | Models, assemblies, drawings, with **version history and branching**.                     |
| Workshop facilities   | Zones, machines, tool inventory.                                                          |
| Production            | Production orders, work orders, routing sheets, with **BOM explosion**.                   |
| Supplier / purchasing | Supplier database, purchase orders, receiving records.                                    |
| Quality               | Inspection records, test results, non-conformance reports.                                |
| Customer orders       | Customer orders, quotes, project timelines.                                               |
| IoT                   | Device registry, firmware versions, telemetry endpoints.                                  |
| Living furniture      | Plant species, aquatic species, nutrient schedules, water-chemistry logs.                 |
| Musical instruments   | Dimensions, tonewoods, bracing patterns, setup parameters.                                |
| CNC programs          | Toolpath files, post-processor configurations.                                            |
| Robot programs        | Cell configurations, safety-zone definitions.                                             |
| Workforce             | Employee records, certifications, skill matrices, training progress.                      |

### Time-Series Storage

- **TimescaleDB hypertables** for machine telemetry — CNC spindle load,
  temperature, vibration, tool wear (67.1.2.15) — and for living-furniture
  sensors — pH, EC, temperature, humidity, light intensity, water level
  (67.1.2.16).
- **InfluxDB** for high-frequency CNC and IoT sensor data, with retention
  policies governing the data lifecycle (67.1.2.19).

### Vector and Cache Layers

- **pgvector** extension for AI embeddings: defect detection, design similarity,
  material grain analysis (67.1.2.17).
- **Redis** caching strategy for real-time workshop dashboards, machine status,
  and IoT telemetry (67.1.2.18).

### Object Storage

**MinIO** buckets for CAD files, CNC programs, firmware binaries, product
images, and inspection photos (67.1.4.5).

### Seed Data

Seed data for wood species, metal alloys, glass types, standard joinery, and
instrument templates (67.1.2.21).

---

## API Surface

Athena's API surface is multi-protocol because its consumers have different
needs: a web dashboard uses REST and GraphQL, a workshop floor console needs
real-time WebSocket updates for machine status, and internal services
(simulation, CNC kernel) communicate via gRPC for low-latency calls.

Phase-67 §67.1.3 plans an API gateway with route-based microservice dispatch.

### Transports

- **REST** — endpoint families for CAD model CRUD / versioning / export,
  production order management and scheduling, inventory management and
  procurement, and IoT device management and telemetry ingestion. An **OpenAPI
  3.1** specification is generated for all REST endpoints (67.1.3.12).
- **GraphQL** — a schema for complex product, material, and production queries
  (67.1.3.2).
- **WebSocket** — a server for real-time machine status, production tracking,
  and live sensor feeds (67.1.3.7).
- **gRPC** — service definitions for internal Athena service communication: CAD
  kernel, simulation, CNC (67.1.3.8).

### API Families (planned)

The current `specifications.md` and `features.md` group the planned API surface
into the following families. Each is the public contract for the corresponding
package(s):

- **Design / engineering** — design, CAD, CAM, toolpath, simulation, and
  artifact-version APIs.
- **Workshop operations** — workshop scheduling, machine reservation, job
  execution, and safety-lockout APIs.
- **Materials and supply** — material, supplier, quality, finishing, and
  sustainability APIs.
- **Business and lifecycle** — marketplace, ERP, academy, aftercare,
  restoration, and compliance APIs.

### Cross-Cutting API Concerns

- **Authentication / authorization** — middleware with role-based access. The
  named roles are `designer`, `machinist`, `operator`, `manager`, `customer`
  (67.1.3.9).
- **Rate limiting** — applied to public API endpoints and IoT ingestion
  (67.1.3.10).
- **Validation** — Zod validation schemas for all API request/response types
  (67.1.3.11).
- **Observability** — health-check endpoints per microservice (67.1.3.13);
  Prometheus metrics for API latency, throughput, machine utilization, and OEE
  (67.1.3.14); OpenTelemetry distributed tracing across all services
  (67.1.3.15); structured logging with correlation IDs (67.1.3.16).
- **Resilience** — circuit-breaker patterns for external service calls (supplier
  APIs, shipping APIs, payment gateways) (67.1.3.17).

---

## Package Catalogue — Phase 67 (Maker and Workshop Operations)

The following catalogue lists all 37 planned packages for Phase 67, grouped by
architectural layer. Each entry gives a one-line summary, the key capabilities
from `features.md`, and the task count from `TODOS/phase-67.md`. Together they
total **1,636 planned tasks**. Each package will live at `libs/athena/<name>/`.

### Foundation

- **`@athena/core`** — core types, entities, enums, shared abstractions; owns
  the `DesignArtifact` and `FabricationJob` state machines and the event
  contracts. (§67.2, 65 tasks.)

### Engineering Layer

- **`@athena/cad`** — parametric 3D CAD for the maker workflow: a Rust + WASM
  geometric kernel (B-rep solid modeling, NURBS, Boolean operations, fillet /
  chamfer, extrude / revolve / sweep / loft, shell, draft, patterns, subdivision
  surfaces, geometric constraint solver, mass-property and collision
  calculations), parametric feature tree, 2D sketcher and constraint solver,
  parametric joinery and hardware insertion, assembly modeling, 2D drafting with
  GD&T, file interchange (STEP, IGES, STL, OBJ, 3MF, DXF/DWG, SVG, SKP,
  Parasolid, glTF/GLB, USDZ, IFC), and generative design / topology
  optimization. The model passes design validation before promotion from `draft`
  to `validated`. (§67.3, 83 tasks.)
- **`@athena/cam`** — CAM for the maker workflow: 2D / 2.5D / 3D / 3+2 / 5-axis
  toolpath generation, drilling cycles, wood-specific strategies, sheet-goods
  nesting, rest machining, turning and engraving toolpaths, laser and waterjet
  toolpaths; generic G-code generation with configurable dialect (Fanuc, Haas,
  Siemens, Heidenhain, Mach3, GRBL, LinuxCNC) and a post-processor framework; a
  tool library, feeds-and-speeds calculator, tool-wear tracking; and machining
  simulation (voxel material removal, collision detection, surface-finish
  prediction, cycle-time estimation). (§67.4, 45 tasks.)
- **`@athena/electronics`** — schematic capture, PCB layout, component library,
  design-rule checking and verification, and manufacturing output. (§67.13, 39
  tasks.)
- **`@athena/acoustics`** — speaker design and modeling, enclosure design, DSP /
  crossover design, instrument acoustics, and room acoustics for workshop and
  showroom. (§67.14, 48 tasks.)
- **`@athena/firmware`** — firmware development platform: RTOS foundation,
  peripheral drivers, communication stacks, DSP / audio firmware, OTA update
  system, and testing / debugging. Firmware ships as `firmware`-type
  `DesignArtifact`s that are versioned and reproducible. (§67.12, 52 tasks.)
- **`@athena/iot`** — smart-furniture IoT platform: hardware abstraction layer,
  sensor integration, actuator control, connectivity and protocols, smart-home
  integration, and power management. (§67.11, 56 tasks.)
- **`@athena/simulation`** — FEA, acoustic, thermal / fluid, ergonomic,
  manufacturing-process simulation, and a workshop digital twin. (§67.18, 49
  tasks.)

### Materials Layer

- **`@athena/materials`** — material science: wood, metal, glass, composite /
  bio-material, and adhesive / fastener science, plus a material selection
  engine (Ashby methodology, weighted scoring, substitution recommender, cost
  estimator). Substitution logic proposes alternatives when a `MaterialLot` is
  unavailable, ranked by property match, and never substitutes across a
  structural-property gap the design depends on. (§67.5, 72 tasks.)

### Craft Layer

Each craft vertical specializes the core for one material discipline, defining
operations, tools and characteristic defects, discipline tolerances and the
`inspection`-stage quality gate, and work-instruction / provenance
documentation.

- **`@athena/woodcraft`** — joinery, steam / laminate bending, wood turning,
  carving / sculpting, veneering / marquetry, lumber processing. (§67.6, 62
  tasks.)
- **`@athena/metalcraft`** — welding, forging / casting, sheet-metal
  fabrication, machining, surface and heat treatment. (§67.7, 50 tasks.)
- **`@athena/glasscraft`** — glass blowing / hot working, kiln forming / fusing,
  stained / architectural glass, lampworking. (§67.8, 32 tasks.)
- **`@athena/luthiery`** — string, wind, percussion, keyboard, and electronic
  instrument making; tonewood selection and acoustic analysis; instrument setup
  and restoration. Produces acoustic specifications and integrates with
  `@athena/acoustics`. (§67.9, 101 tasks.)
- **`@athena/living`** — living furniture: hydroponic systems, aquarium systems,
  terrarium / bioactive systems, aquaponic integration, automated life-support
  systems, and a plant / aquatic species database. (§67.10, 76 tasks.)
- **`@athena/upholstery`** — fabric / leather intelligence, cushion / foam
  engineering, pattern making and cutting, sewing and assembly. (§67.22, 29
  tasks.)
- **`@athena/finishing`** — wood finishing, metal finishing, glass finishing,
  spray-booth management, and color science / matching. (§67.23, 33 tasks.)
- **`@athena/restoration`** — antique-furniture restoration, instrument
  restoration, 3D scanning / reverse engineering, and historical-period
  analysis; adds a condition-assessment step that grades an incoming piece
  before a restoration job is planned. (§67.35, 19 tasks.)
- **`@athena/packaging`** — flat-pack design, custom crating / protection,
  assembly-instruction generation, AR assembly guidance. (§67.34, 16 tasks.)
- **`@athena/aftercare`** — warranty management, repair / maintenance, IoT
  monitoring and OTA, spare-parts management, living-furniture care. (§67.29, 20
  tasks.)

### Production Floor

- **`@athena/cnc`** — subtractive machining execution: CNC routing, 3/4/5-axis
  milling, turning, laser cutting / engraving, waterjet / plasma cutting, and
  machine-controller integration. Runs `cnc`-process `FabricationJob`s. (§67.15,
  51 tasks.)
- **`@athena/additive`** — additive manufacturing: FDM / FFF printing, resin
  (SLA / DLP) printing, powder-bed / metal printing, and a slicer with support
  generation. Runs `additive`-process jobs. (§67.16, 30 tasks.)
- **`@athena/robotics`** — workshop robotics: robot-arm programming,
  collaborative robotics, automated material handling, vision-guided robotics,
  robotic finishing and assembly. A robot is a `Tool` of type `robot` and is
  subject to the certification and lockout requirement. (§67.17, 35 tasks.)
- **`@athena/workshop`** — workshop operations: space planning / layout, tool
  inventory and tracking, safety systems (LOTO, PPE tracking, E-stop, incident
  reporting, SawStop monitoring, chemical safety / SDS), environmental controls,
  and energy management. Co-owns the Tool Certification and Safety Lockout state
  machine. (§67.19, 43 tasks.)
- **`@athena/production`** — the MES: work-order management, production
  scheduling (finite-capacity, job-shop dispatching rules, Gantt visualization),
  multi-level BOM management, quality control and SPC, lean manufacturing (VSM,
  kanban, 5S, kaizen, OEE, takt time), and capacity planning. Drives
  `FabricationJob`s through their state graph. (§67.20, 53 tasks.)
- **`@athena/supply`** — supply chain: supplier management and scorecards,
  procurement and purchasing (MRP, EOQ, blanket orders), inventory management
  (bin locations, lot tracking, reorder points, FIFO/FEFO), logistics and
  shipping, and material traceability (FSC/PEFC chain-of-custody, CITES, Lacey
  Act, EUTR, conflict minerals). (§67.21, 39 tasks.)

### Business, Marketplace, Academy

- **`@athena/erp`** — CRM / client management, order management, costing /
  pricing engine, financial integration, project management, HR / workforce.
  Margin is computed from BOM material cost and labor. (§67.25, 37 tasks.)
- **`@athena/quality`** — dimensional inspection, material testing, acoustic
  quality testing, durability / environmental testing, and metrology /
  calibration. Owns the `inspection`-stage gate, defect tracking per craft
  vertical, and anomaly detection across jobs. Co-owns the Tool Certification
  and Safety Lockout state machine. (§67.24, 25 tasks.)
- **`@athena/studio`** — collaborative design space: photorealistic rendering,
  AR/VR experience, product configurator, client collaboration portal, portfolio
  management. (§67.26, 34 tasks.)
- **`@athena/marketplace`** — catalog, 3D product viewer, pricing engine,
  multi-channel sales, custom-order pipeline. Every listing links to a
  `released` `DesignArtifact` and the producing jobs' quality records. (§67.27,
  24 tasks.)
- **`@athena/sustainability`** — carbon-footprint tracking, lifecycle assessment
  (LCA), circular economy, certification management, waste management. Claims
  are backed by evidence. (§67.28, 23 tasks.)
- **`@athena/compliance`** — furniture-safety standards, electrical safety,
  environmental regulations, workshop-safety regulations, musical-instrument
  standards; regulatory records and audit trails. (§67.30, 24 tasks.)
- **`@athena/academy`** — technique database, safety training, apprenticeship
  programs, machine-operation training, video / interactive tutorials.
  Certification completion feeds the tool-certification check. (§67.31, 21
  tasks.)

### Platform

- **`@athena/apps`** — the application suite: a smart-furniture control app (iOS
  / Android), a living-furniture monitor app, a workshop management app, an
  inventory scanner app, a quality inspection app, an AR assembly guide app, and
  a customer portal. (§67.32, 27 tasks.)
- **`@athena/ai`** — computer vision for quality, generative design AI,
  predictive maintenance, demand forecasting, acoustic AI, material recognition,
  NLP for design briefs. Supports other packages rather than being a standalone
  surface. (§67.33, 28 tasks.)
- **`@athena/biome`** — factory-biome / living-workshop intelligence: biophilic
  factory design, phytoremediation / air bioremediation, acoustic
  bioremediation, factory ecosystem management, biome IoT / environmental
  monitoring, worker-wellbeing integration, safety / hazard integration.
  (§67.36, 51 tasks.)
- **`@athena/integration`** — the cross-domain hub. (§67.37, 62 tasks; see
  Cross-Domain Boundaries below.)

---

## Package Catalogue — Phase 136 (Sovereign CAD / EDA / CAM / GIS Kernel)

The Phase 136 catalogue covers the 10 kernel packages totalling **425 planned
tasks**. The descriptions below are necessarily dense: these packages are
engineering applications in their own right, and the specifications capture the
feature parity target against the proprietary tools they replace. For each
package, the detail reflects the expected acceptance criteria when
implementation begins. The kernel is planned in Rust with optional WASM
delivery; **Neith** provides the runtime, renderer, GPU, file I/O, UI, and
collaboration substrate on which these packages run.

### `@athena/kernel` — Geometric Modeling Kernel (§136.1, 75 tasks)

The boundary-representation (B-rep) + NURBS + mesh geometry engine, planned to
parity with Parasolid / ACIS / Open CASCADE.

- **Topology** — B-rep data structures (`Vertex`, `Edge`, `Loop`, `Face`,
  `Shell`, `Body`, `Compound`); half-edge / winged-edge representation choice
  with benchmarks; orientation and manifold validation; topological equality and
  hashing; an attribute store (material / color / custom); topological
  transactions with rollback; a **body history graph for persistent IDs** and
  feature-edit identity across regenerations (so feature references survive
  edits); non-manifold repair; tolerant topology with per-entity tolerance.
- **Curves** — line / ray / segment; circle / arc / ellipse; parabola /
  hyperbola; Bézier (cubic and degree-n); B-spline with knot insertion /
  removal; NURBS with weights; Hermite / interpolation curves; offset curve with
  self-intersection repair; composite curve; arc-length parameterization.
- **Surfaces** — plane / cylinder / cone / sphere / torus; Bézier, B-spline, and
  NURBS surfaces; ruled / loft, revolution, and sweep (single- and double-rail)
  surfaces; Coons patch; Gordon surface; trimmed surface with inner loops;
  subdivision surface (Catmull-Clark / Loop); T-spline surface; offset surface;
  surface-surface and surface-curve intersection.
- **Boolean and feature operations** — union / difference / intersection on
  solids; tolerant Boolean on shells and sheets; imprint; extrude (with draft);
  revolve (full and partial); sweep (path, guide curve, twist); loft with guide
  curves and tangency; hole (simple, counterbore, countersink, tapped, pipe);
  fillet (constant, variable, setback); chamfer (equal, unequal,
  angle-distance); draft (neutral plane, parting line); shell; rib / web; emboss
  / deboss; wrap text / profile onto surface; thicken; split / trim / extend;
  boundary fill (heal gaps); replace face; move face / delete face.
- **Analysis and validation** — mass properties (volume, centroid, inertia
  tensor, radii of gyration); curvature analysis (Gauss, mean, principal); zebra
  / isocurve visualization; draft analysis; undercut detection; wall-thickness
  analysis; clearance / interference (minimum distance); short- edge /
  sliver-face detection; self-intersection detection; tolerance healing. A model
  passing geometry QA is eligible to become a `validated` `DesignArtifact`.

### `@athena/constraint` — 2D & 3D Constraint Solver (§136.2, 30 tasks)

The geometric constraint solver for parametric sketching and assembly mates.

- **2D sketch solver** — DOF analysis and rank estimation; geometric constraints
  (coincident, horizontal, vertical, parallel, perpendicular, tangent,
  concentric, equal, symmetric, midpoint, collinear); dimensional constraints
  (length, distance, angle, radius, diameter); fixed entity and rigid set;
  driven-vs-driving dimension; automatic inference during sketching; under- /
  over-constrained detection with red/green highlight; a global solver
  (Newton-Raphson + SLP); reusable sketch blocks; external references to model
  geometry.

  The solver classifies a sketch as **well-constrained** (one solution, fully
  determined), **under-constrained** (degrees of freedom remain — the sketch can
  still be dragged), or **over-constrained** (redundant or conflicting
  constraints — the solver reports the conflicting set rather than silently
  dropping one). Driven dimensions are reported, not solved for. The solver
  returns a human-readable explanation of why a sketch failed.

- **3D assembly mates** — standard mates (coincident, parallel, perpendicular,
  tangent, distance, angle); advanced mates (symmetric, width, path,
  linear-coupler, limit); mechanical mates (cam, gear, hinge, rack-pinion,
  screw, universal joint); contact-set / interference-aware mates; exploded
  views; time-based motion animation; rigid / flexible sub-assemblies; mate
  references (self-mating parts); smart fastener / hardware insertion; a mate
  controller with position snapshots.
- **Solver internals** — symbolic constraint-graph builder; decomposition into
  rigid clusters; graph-based (Hoffmann et al.) solver; numeric fallback
  (homotopy continuation); diagnostic mode with conflicting constraints; solver
  caching for incremental edits; multi-threading across independent clusters;
  inequality constraint (≥ / ≤) support; tolerance-aware solving; a WASM
  portable solver for the Neith Browser. The solve is **deterministic** so it
  can be replayed exactly, and regression tests pin known sketches to known
  solutions.

### `@athena/cad-studio` — Parametric CAD Authoring (§136.3, 75 tasks)

The end-user mechanical CAD application surface on the kernel: a sketcher
(primitives, construction vs geometry lines, trim / extend / offset / mirror /
pattern, 2D fillet / chamfer, image / PDF underlay, DXF import, copy edges /
faces, sketch text, slots / rectangles / polygons, multi-plane 3D sketch); a
feature tree with fold-down children, reorder / suppress / rollback state, named
selections, direct-edit move-face mode, push-pull on imported dumb bodies,
synchronous-tech hybrid mode, patterns (linear, circular, table-driven,
curve-driven, sketch-driven), mirror feature / bodies, configurations / variants
table, global variables and expressions; sheet metal (base / edge flange,
sketched bend, K-factor / bend-allowance / bend-deduction tables, miter flange /
jog, hem / swept flange, corner relief, unfold to flat pattern, DXF export with
bend lines, nesting, gauge table, formed / rolled sheet metal); weldments and
structural members; Class-A surface modeling (boundary surface with tangency /
curvature continuity, patch / fill with G0/G1/G2/G3, trim / extend / knit, draft
continuous surface, T-spline / SubD, zebra / reflection-line evaluation,
curvature comb, repair imported surfaces); 2D drafting (multiple sheet sizes ISO
/ ANSI, standard views auto-create, section / detail / broken / auxiliary views,
dimensioning, GD&T per ASME Y14.5 / ISO 1101, surface-finish and welding
symbols, BOM / parts list, balloons, title blocks and revision tables, DWG/DXF
round-trip, PDF export with layers, drawing-package batch print, drawing
check-set workflow, model-based-definition annotations); and configurations /
PDM (configuration table, design-table links, part-family catalogs, revision
control with Git-LFS / sovereign vault, check-in / check-out, ECO / ECR
workflow, item master with part-number policy, BOM export, attribute search,
**released-state lock**).

### `@athena/sim` — Simulation (§136.4, 65 tasks)

Sovereign physics simulation on the CAD kernel: **FEA** (linear static, modal /
eigenvalue, harmonic, transient dynamics, nonlinear, thermal, thermomechanical
coupling, buckling, fatigue, crash / drop-test, element and material libraries,
contact, boundary-condition library, post-processing); **CFD** (incompressible
and compressible Navier-Stokes, turbulence models, multiphase, porous media,
moving mesh, conjugate heat transfer, mesh generator, boundary layers, GPU
solver, aeroacoustics, external aero, electronics cooling, HVAC system sim);
**mold flow and plastics** (fill, packing, cooling, warpage, fiber orientation,
gate / runner optimization, weld lines / air traps, shrinkage, material
database); **topology optimization and generative design** (SIMP, level-set,
lattice / infill, manufacturing constraints, multi-material, generative design,
organic-shape export, mass-target / compliance minimization, load-case
combination, result smoothing to a CAD-reusable body); and **multi-body
dynamics** (rigid-body joint library, force / moment / spring / damper, contact
with friction, motor / actuator, flexible body, control-system co-sim via FMI
3.0, motion animation, force plots, interference during motion, reaction-force
export to FEA).

### `@athena/eda` — Electronic Design Automation (§136.5, 50 tasks)

Sovereign KiCad / Altium replacement: **schematic capture** (hierarchical
sheets, symbol library, ERC, net classes and buses, differential-pair
annotation, power rails and net-ties, off-sheet connectors, annotation / refdes
auto-assign, BOM generation with supplier linkage, multi-language symbol
standards); **PCB layout** (footprint library, stackup editor with controlled
impedance, layer types, placement with push-and-shove, autorouter — grid /
topological / neural, interactive routing with walkaround, differential-pair
routing, length matching / tuning, impedance-controlled trace widths, via types
— through / blind / buried / microvia, copper pour / zone / teardrop, design
rules, DRC, 3D viewer with STEP export, rigid-flex support); **manufacturing
output** (Gerber X2 / X3, Excellon drill files with NPTH / PTH, IPC-2581, ODB++,
pick-and-place CPL, assembly drawings, panelization, fabrication notes, vendor
presets, 3D-printed enclosure export); **SPICE and simulation** (analog SPICE —
DC / AC / transient / noise, mixed-signal, behavioral Verilog-A / Verilog-AMS,
model library, Monte Carlo and worst-case, temperature sweep, harmonic balance,
parasitic extraction, waveform viewer, FFT / distortion); **signal / power
integrity / EMC** (impedance profile, eye diagram, crosstalk, PDN impedance, DC
IR drop, decoupling-capacitor optimization, EMC pre-compliance, full-wave 3D EM
solver — FDTD / MoM / FEM, S-parameter export, IBIS / IBIS-AMI); **thermal on
PCB** (steady-state and transient thermal, component power-dissipation library,
heat-sink / airflow integration, thermal-via auto-design).

### CAM, CNC, and Additive (§136.6 – 136.8)

- **`@athena/cam-milling`** (§136.6, 35 tasks) — subtractive machining toolpaths
  and post-processing: 2.5-axis (facing, contour / pocket / bore / drill /
  engrave, adaptive clearing, rest machining, chamfer / thread mill); 3-axis
  finishing (parallel / radial / morphed spiral, scallop / constant-Z, pencil
  trace, corner-finishing rest, flow-line); 4- and 5-axis (index 4-axis,
  continuous 4-axis, swarf / flow 5-axis, projection 5-axis, tool-axis control);
  turning; **toolpath simulation and verification** (cut visualization,
  material-removal stock model, collision check against tool / holder / fixture
  / machine, kinematic simulation of a 5-axis machine, cycle-time estimate);
  post-processors (Fanuc, Haas, Siemens SINUMERIK, Heidenhain, Mazak, Okuma,
  Tormach / Langmuir, LinuxCNC / Mach4, a custom post-processor SDK, probing /
  in-process inspection cycles).
- **`@athena/cam-additive`** (§136.7, 30 tasks) — FDM / SLA / SLS / metal
  slicer: FDM slicer (uniform and adaptive layer slicing, infill patterns,
  support generation, brim / raft / skirt, bridging, ironing, seam placement,
  variable layer height, multi-material, Z-hop / retraction control, per-feature
  speed tuning, per-layer fan control, calibration, material profile library,
  multiple G-code flavors); SLA / MSLA / DLP (resin slicing with anti-aliasing,
  light-off delay, resin-tuned supports, hollowing with drain holes, per-layer
  exposure profiling); SLS / metal print (powder-bed slicing, laser scan
  pattern, hatching / stripe patterns, contour / offset, thermal pre-heat
  simulation, stress-compensating pre-deform, metal supports, per-region laser
  power / speed, parts-nesting for the build plate).
- **`@athena/cam-other`** (§136.8, 15 tasks) — laser / waterjet / plasma / robot
  pathing: laser cutting (vector and raster) and engraving with dither; waterjet
  with kerf compensation; plasma with pierce-height profile; oxy-fuel cutting;
  EDM wire cut; a 6/7-DOF robot-arm kinematic solver; robot trajectory planning;
  singularity avoidance; collision-free path planning (RRT / PRM); ABB / KUKA /
  UR / Fanuc post-processors; robot welding and painting toolpaths; multi-robot
  coordination; a gripper / end-effector library.

### `@athena/gis` — GIS / Mapping (§136.9, 40 tasks)

The geospatial application surface (QGIS / ArcGIS / Cesium / Mapbox
replacement): a **spatial engine** (PROJ-class projection engine, spatial
queries, topology rules, spatial index — R-tree / quad-tree / H3 / S2, raster
algebra, zonal statistics, watershed / viewshed analysis, hillshade / slope /
aspect, interpolation — IDW / kriging / spline, network analysis); **vector /
raster I/O** (GDAL-class raster, OGR-class vector, WMS / WMTS / WFS / WCS / WPS
clients, PostGIS / DuckDB-spatial / Spatialite backends, cloud-optimized GeoTIFF
streaming, Zarr, STAC catalogs, OpenStreetMap PBF ingest, Copernicus / Landsat /
Sentinel ingest, LAS / LAZ LIDAR point clouds); **cartography**
(Mapbox-compatible GL style editor, SLD import, anti-overlap label placement,
symbology, data-driven symbolization, print-layout composer, atlas / data-driven
pages, 3D globe view, terrain mesh with quantized-mesh tiles, OGC 3D Tiles); and
a **vector tile server** (Tippecanoe-class tile builder, MBTiles / PMTiles
output, live vector-tile server, cache / CDN layer, glyph and sprite server,
versioned style server, authentication / rate-limit, TileJSON catalog,
RGB-encoded terrain tile server, on-device / edge mirror).

### `@athena/simulation-coupling` — Multi-Physics / Digital Twin (§136.10, 10 tasks)

Cross-domain linking: an FMI 3.0 master algorithm and slave wrapper for CAD /
sim; SSP / SSP-Traceability; digital-twin binding to a live sensor feed; a
reduced-order-model (ROM) training pipeline and ROM export to an embedded
runtime; co-simulation with Neith Engine physics; hardware-in-the-loop hooks; a
sim-vs-test calibration workflow; sensitivity / DOE campaigns.

---

## Manufacturing Validation Gate

The Manufacturing Validation Gate is the most safety-critical section of the
specification. It sits between CAM toolpath generation and `released` status: a
toolpath that has not passed this gate cannot drive a `FabricationJob`. This is
important because an unvalidated toolpath can collide a cutting tool with a
fixture, gouge a finished surface, or leave uncut material that causes
dimensional failures downstream.

`features.md` nominates the CAM validation gate as the spec's focus. Before a
`toolpath` `DesignArtifact` may transition to `released`, it passes a hard
validation gate. A path that fails any check is blocked from release.

The gate runs:

1. **Material-removal simulation** — confirms the path actually clears the
   intended stock (`@athena/cam` voxel-based stock model; phase-67 task
   67.4.4.1, phase-136 task 136.6.5.2).
2. **Tool collision detection** — confirms the cutter does not strike the part,
   fixture, or clamps (67.4.4.2 / 136.6.5.3).
3. **Holder / gouge detection** — confirms the tool holder clears the workpiece
   and the cutter does not gouge the finished surface.
4. **Remaining-stock analysis** — confirms no uncut material is left
   (rest-machining detection; 67.4.1.9).
5. **Cycle-time estimate** — with realistic acceleration / deceleration and
   tool-change times (67.4.4.6 / 136.6.5.5).
6. **Cost estimate** — for the toolpath.
7. **Tolerance stack checks** — verifies tolerance compliance against the design
   model (67.4.4.8 deviation map).

On pass, the gate also emits an **inspection plan** for the resulting
`FabricationJob`, feeding the `inspection`-stage quality gate.

---

## Validation Rules, Invariants, and Constraints

These invariants summarize the non-negotiable rules that the implementation must
enforce. They are derived from the Hard Requirements and state machines
described above, collected here as a quick checklist for reviewers verifying a
new implementation.

- A `FabricationJob` may transition `queued → running` only when its
  `DesignArtifact` is `released` and every required `Tool` is neither
  `locked_out` nor `retired` (Hard Requirement 1).
- A `FabricationJob` cannot be assigned to an artisan lacking the certification
  required by a `certificationRequired` `Tool`; the assignment is rejected, not
  warned (Hard Requirement 1).
- Only a `released` `DesignArtifact` may drive a `FabricationJob` or back a
  marketplace listing.
- A `toolpath` `DesignArtifact` may only become `released` after passing the
  Manufacturing Validation Gate.
- Re-running a `released` toolpath against the same stock and machine profile
  must produce the same G-code (Hard Requirement 2, reproducibility).
- The Phase 136 constraint solver's solve must be deterministic so it can be
  replayed exactly; regression tests pin known sketches to known solutions.
- An over-constrained sketch must report the conflicting constraint set rather
  than silently dropping a constraint.
- A material substitution must never cross a structural-property gap that the
  design depends on.
- A sustainability or provenance claim must be backed by a `MaterialLot` record
  with attached evidence (Hard Requirement 3).
- AI assistance proposes changes only; it never auto-releases an artifact.
- Every state transition on the `DesignArtifact` and `FabricationJob` machines
  is stamped with actor and timestamp; illegal transitions are rejected.
- A `Tool` in `locked_out` clears only via an explicit passed-maintenance event;
  `retired` is terminal.

---

## Configuration and Environment Inputs

Phase-67 §67.1.4 plans the following environment / infrastructure inputs:

- **Environment variables** — `.env` additions for all Athena services,
  including `ATHENA_DATABASE_URL` and `ATHENA_MQTT_URL` (67.1.4.7).
- **Domain database** — added to `docker-compose.dev.yml`'s
  `POSTGRES_MULTIPLE_DATABASES` (67.1.4.10), consistent with the monorepo's
  domain-isolated database model.
- **MQTT broker** — Mosquitto / EMQX, for IoT device communication and machine
  telemetry (67.1.4.2).
- **Kafka topics** — for factory-floor event streaming: machine events,
  production events, quality events, IoT events (67.1.4.3).
- **InfluxDB / TimescaleDB** — for sensor time-series storage with Grafana
  dashboards (67.1.4.4).
- **MinIO buckets** — for CAD files, CNC programs, firmware binaries, product
  images, inspection photos (67.1.4.5).
- **Edge nodes** — a Docker-based edge-computing simulation environment for the
  workshop floor (67.1.4.6).
- **Grafana dashboards** — templates for workshop KPIs: machine utilization,
  OEE, production throughput, defect rates (67.1.4.8).
- **Nx / build wiring** — `project.json` per Athena library with build / test /
  lint targets (67.1.1.37); path mappings in `tsconfig.base.json` for the
  `@athena/*` namespace (67.1.1.38); ESLint scope tag `scope:athena` in module
  boundaries (67.1.1.39); Vitest configuration with coverage thresholds
  (67.1.1.40); implicit dependencies in the Nx graph (67.1.1.41);
  `pnpm-workspace.yaml` library paths (67.1.1.42).

---

## Cross-Domain Boundaries

`architecture.md` and `features.md` fix Athena's bounded-context relationships.
The Seshat ownership question must be explicitly resolved before any Athena
package is implemented.

- **Seshat** — currently owns design, craft, fabrication, smart manufacturing,
  sustainability, and maker education, and is the canonical owner of design /
  craft / fabrication intelligence unless Athena is activated. Athena is a
  planned expansion into a deeper maker / workshop operating system that
  overlaps Seshat's scope. Before any Athena package is implemented, ownership
  must be explicitly resolved — either split the bounded contexts with a
  documented boundary, or fold Athena's workstreams into Seshat with a
  documented migration. **Athena must not silently duplicate Seshat.**
- **Brigid** — owns generic / industrial-scale factory automation infrastructure
  (PLCs, SCADA, energy). **Athena is built on top of Brigid**, consuming its
  capabilities and adding furniture / instrument domain intelligence. The
  `@athena/integration` package plans Brigid adapters for PLC frameworks, SCADA,
  digital twin, predictive maintenance, industrial communication (OPC UA, MQTT,
  Modbus), energy management, safety systems, robotics, industrial AI, and
  cybersecurity.
- **Freya** — owns luxury-goods fashion / beauty manufacturing semantics.
- **Cybele** — owns construction and built-environment domains; Athena
  manufactures the furniture and fixtures that go inside buildings, with an IFC
  / BIM interoperability bridge.
- **Euterpe** — digital music creation and theory; Athena builds the physical
  instruments musicians play, and `@athena/luthiery` / `@athena/acoustics`
  integrate with Euterpe.
- **Neith** — for Phase 136, provides the runtime, renderer, GPU compute, file
  I/O, UI, collaboration, and platform substrate beneath the sovereign kernel;
  Athena owns the engineering semantics on top, and the constraint solver ships
  a WASM build for the Neith Browser.
- **Maat** — business rollups; `@athena/integration` plans a Maat adapter.
- **Demeter** — plant intelligence consumed by `@athena/living`.

`@athena/integration` (phase-67 §67.37) is the cross-domain hub. Athena links to
these domains rather than re-modeling their facts.

---

## Acceptance Criteria and Verification Expectations

`architecture.md` ("Verification Expectations") and the phase docs fix the test
gates the implementation must meet:

- Geometry / CAD tests — golden geometry fixtures, Boolean stress tests;
  phase-67 task 67.3.1.18 requires a minimum 500 geometric-kernel test cases.
- CAM toolpath tests — machining-simulation tests.
- Machine-safety tests — covering the Tool Certification and Safety Lockout
  state machine and job-execution guards.
- Material-property tests — phase-67 task 67.5.6.7 requires a minimum 250
  material-science test cases.
- Production-flow tests — phase-67 task 67.21.5.6 requires a minimum 150
  supply-chain test cases; 67.24.5.5 requires a minimum 150 quality test cases.
- Core-type tests — phase-67 task 67.2.6.10 requires a minimum 300 test cases
  for core types and utilities.
- Marketplace tests and compliance / audit tests.
- For Phase 136 — solver regression suites, import/export conformance tests, EDA
  design-rule suites, GIS projection tests, performance benchmarks, and
  reproducible sample projects.
