# Seshat Domain — Technical Specifications

> Technical specification for the Seshat dwelling-arts and craftsmanship domain:
> domain objects, enums and literal-union types, computation result shapes,
> validation schemas, the project state machine, configuration, and module
> surfaces. Every entity, field, enum value, and function named below is
> traceable to source under `libs/seshat/*`.

---

This document is the authoritative reference for engineers integrating with or
extending Seshat. It lists the precise names, types, and constraints for every
schema, enum, function, and constant exposed by the domain's eleven libraries.
Where the features document explains _what_ something does and _why_, this
document specifies _exactly how_ it is shaped — field types, valid values, error
codes, state machine transitions.

---

## Status

**Implemented** as eleven TypeScript libraries under `libs/seshat/`. There is no
`apps/seshat` or `services/seshat` — Seshat ships purely as importable libraries
with no runtime service, no HTTP/API gateway, and no event bus. The TODOS Phase
36 backlog (`TODOS.md`) describes an API gateway and event infrastructure as
future scope; none of that is present in the workspace.

---

## Technology Stack

The table below lists the technology choice for each layer of the domain. The
most important constraint for integration is the runtime: only `zod` (and `uuid`
for `@seshat/core`) — no database drivers, no HTTP clients, no message bus
adapters.

| Layer      | Technology                                                |
| ---------- | --------------------------------------------------------- |
| Language   | TypeScript (ESM, `"type": "module"`)                      |
| Runtime    | Node.js                                                   |
| Validation | Zod (`catalog:`) — the only runtime dependency            |
| Testing    | Vitest                                                    |
| Build      | Nx (`@nx/js:tsc`) per `project.json`; tags `scope:seshat` |

Every `libs/seshat/*/package.json` declares exactly one runtime dependency,
`zod`, and one dev dependency, `vitest`. `@seshat/core` additionally imports
`uuid`. No library depends on any `@oshun/*` package or on a database driver,
message bus, or AI runtime.

---

## Library Structure (11 Libraries)

The following table maps each library to its npm package name and primary
responsibility. The dependency direction is important: every domain library may
import from `@seshat/common`; `@seshat/database` deliberately imports nothing
from the other domain libraries; `@seshat/core` does not import the other domain
libraries at runtime — it references them only as identifier strings.

| Library          | Package                  | Responsibility                                                          |
| ---------------- | ------------------------ | ----------------------------------------------------------------------- |
| `core`           | `@seshat/core`           | Project lifecycle, workflow DAG engine, config, errors, logging, flags  |
| `common`         | `@seshat/common`         | Shared types, real-world constant databases, geometry/unit/color utils  |
| `craft`          | `@seshat/craft`          | Joinery, wood materials science, tools, finishing, project planning     |
| `design`         | `@seshat/design`         | Style analysis, parametric design, floor-plan analysis, mood boards     |
| `fabrication`    | `@seshat/fabrication`    | CNC feeds/speeds + G-code, laser settings, 3D-print estimation, nesting |
| `harmony`        | `@seshat/harmony`        | Feng Shui, Vastu, biophilic, sacred geometry, colour, synthesis         |
| `smart`          | `@seshat/smart`          | IoT device registry, sensor processing, automation, wellness            |
| `sustainability` | `@seshat/sustainability` | Carbon footprint, LCA, circular design, certification, waste audit      |
| `academy`        | `@seshat/academy`        | Skill assessment, learning paths, certification, mentorship matching    |
| `workshop`       | `@seshat/workshop`       | Workshop layout, tool inventory, safety, scheduling, dust/electrical    |
| `database`       | `@seshat/database`       | Zod row schemas, declarative migration definitions, seed data           |

Dependency direction: every domain library imports types from `@seshat/common`;
`@seshat/database` defines its own Zod schemas without importing
`@seshat/common` (a deliberate decoupling, per its file header). `@seshat/core`
does not import the other domain libraries — it lists them only as identifier
strings in `SeshatModuleSchema` / `MODULE_CAPABILITIES`.

---

## Domain Orchestration (`@seshat/core`)

### Project Entity

The `ProjectSchema` is the central entity for tracking a dwelling-arts project
through its lifecycle. Budget is tracked in integer cents to avoid
floating-point rounding errors. The `roomIds` array links a project to the
physical spaces it concerns.

`ProjectSchema` (Zod object, `core/src/types.ts`):

| Field             | Type                          | Notes                                          |
| ----------------- | ----------------------------- | ---------------------------------------------- |
| `id`              | `string` (UUID)               | `z.string().uuid()`                            |
| `name`            | `string` 1–255                |                                                |
| `description`     | `string` ≤2000, optional      |                                                |
| `category`        | `ProjectCategory`             | see enum below                                 |
| `phase`           | `ProjectPhase`                | see state machine below                        |
| `priority`        | `ProjectPriority`             | default `medium`                               |
| `budget`          | `Budget`, optional            |                                                |
| `ownerId`         | `string` (UUID)               |                                                |
| `collaboratorIds` | `string[]` (UUID)             | default `[]`                                   |
| `tags`            | `string[]` (≤50 chars, ≤20)   | default `[]`                                   |
| `roomIds`         | `string[]` (UUID)             | default `[]`                                   |
| `createdAt`       | `string` (ISO datetime)       |                                                |
| `updatedAt`       | `string` (ISO datetime)       |                                                |
| `targetDate`      | `string` (ISO datetime), opt. |                                                |
| `completedAt`     | `string` (ISO datetime), opt. | set automatically on transition to `completed` |

`Budget` =
`{ allocatedCents: int ≥0, spentCents: int ≥0, currency: 3-char, default "USD" }`.
Budget is tracked in integer cents.

`CreateProjectInputSchema` picks `name`, `category`, `ownerId` and re-adds
optional `description`, `priority`, `budget`, `tags`, `targetDate`.

### Project Enums

These enums control the type and lifecycle of a project. Note that
`ProjectPhase` here is the eleven-value core lifecycle enum; a separate
ten-stage craft-phase union exists in `@seshat/common` for woodworking-specific
project phases — they are distinct concepts serving different purposes.

```typescript
ProjectCategory =
  | 'interior_design' | 'woodworking' | 'renovation' | 'spatial_harmony'
  | 'smart_dwelling' | 'fabrication' | 'craft' | 'workshop_setup';

ProjectPhase =
  | 'concept' | 'planning' | 'design' | 'material_sourcing' | 'fabrication'
  | 'assembly' | 'finishing' | 'installation' | 'review' | 'completed'
  | 'archived';

ProjectPriority = 'low' | 'medium' | 'high' | 'urgent';
```

### Project Phase State Machine

`ProjectManager` (`core/src/project-manager.ts`) is an in-memory `Map`-backed
store. Phase transitions are strictly controlled by `VALID_TRANSITIONS`, shown
below. The design allows any non-archived phase to revert to `planning` for
rework — this reflects the reality that dwelling projects frequently cycle back
when design iterations reveal problems. The `archived` state is terminal.

`transitionPhase` enforces `VALID_TRANSITIONS`:

| From                | Allowed next phases                               |
| ------------------- | ------------------------------------------------- |
| `concept`           | `planning`, `archived`                            |
| `planning`          | `design`, `material_sourcing`, `archived`         |
| `design`            | `planning`, `material_sourcing`, `archived`       |
| `material_sourcing` | `planning`, `fabrication`, `assembly`, `archived` |
| `fabrication`       | `planning`, `assembly`, `finishing`, `archived`   |
| `assembly`          | `planning`, `finishing`, `archived`               |
| `finishing`         | `planning`, `installation`, `review`, `archived`  |
| `installation`      | `planning`, `review`, `archived`                  |
| `review`            | `planning`, `completed`, `archived`               |
| `completed`         | `archived`                                        |
| `archived`          | (terminal — no transitions)                       |

Any phase may revert to `planning` for rework, and any non-archived phase may
move to `archived`. Invalid transitions throw `InvalidPhaseTransitionError`.
`recordExpense` throws `BudgetExceededError` when `spentCents + amount` would
exceed `allocatedCents`. Helpers: `isValidTransition`, `getNextPhases`.
`ProjectManager` methods: `create`, `get`, `list` (filter by category / phase /
ownerId / tag), `transitionPhase`, `recordExpense`, `getBudgetUtilization`,
`delete`, `count`, `clear`.

### Workflow DAG Engine

The workflow engine models a project as a directed acyclic graph of steps, where
steps can only begin when their dependencies are complete. This prevents
out-of-order execution — for example, you cannot begin `finishing` until
`assembly` is complete, and you cannot begin `assembly` until
`material_sourcing` is done.

`Workflow` =
`{ id (UUID), projectId (UUID), steps: WorkflowStep[], createdAt }`.
`WorkflowStep` =
`{ id, name, description?, status: StepStatus, phase: ProjectPhase, dependsOn: string[], estimatedMinutes?, actualMinutes?, module? }`.

`StepStatus = 'pending' | 'in_progress' | 'blocked' | 'completed' | 'skipped'`.

`workflow-engine.ts` provides pure DAG functions:

- `detectCycle` / `topologicalSort` — Kahn's algorithm; `topologicalSort` throws
  `CycleDetectedError` on a cycle.
- `isStepReady`, `getReadySteps`, `getBlockers` — dependency readiness.
- `computeProgress` → `WorkflowProgress` (`totalSteps`, `completedSteps`,
  `skippedSteps`, `inProgressSteps`, `blockedSteps`, `pendingSteps`,
  `completionPercentage`, `estimatedRemainingMinutes`).
- `transitionStep` — validates against `VALID_STEP_TRANSITIONS`; throws
  `WorkflowStepBlockedError` when starting a step with unmet dependencies.
- `generateWorkflow` — builds a sequential-dependency workflow from a phase
  list.

`WorkflowTemplate` + `WORKFLOW_TEMPLATES` define a default phase sequence per
`ProjectCategory` (8 templates); `getWorkflowTemplate(category)` looks one up.

### Module Registry

The module registry is a capability discovery mechanism. Rather than importing
all Seshat libraries at once, an application can query which modules are
available and what they can do before deciding which to load.

`SeshatModule` enum: `harmony`, `design`, `craft`, `academy`, `smart`,
`workshop`, `fabrication`, `sustainability`, `common`, `database`.
`MODULE_CAPABILITIES` maps each module to a `readonly string[]` of capability
identifiers (e.g.
`harmony → ['feng_shui', 'vastu_shastra', 'biophilic_design', 'sacred_geometry', 'bagua']`).
`ModuleHealth` is a type (`module`, `status`, `latencyMs`, `lastCheckedAt`) with
no runtime probe.

### Configuration

`SeshatConfigSchema` composes six section schemas — one per major subsystem —
each defaulting to an empty object when no configuration is provided. This means
Seshat works out of the box with zero configuration, and features can be enabled
progressively.

The six section schemas are `harmony`, `design`, `craft`, `smart`,
`fabrication`, and `sustainability`. Notable section fields include:

- `HarmonyConfig.defaultTradition` (`feng_shui|vastu_shastra|biophilic|western`)
- `DesignConfig.renderQuality` (`draft|standard|high|photorealistic`) and
  `arEnabled`
- `SmartConfig.mqttBrokerUrl` (optional URL) and `devicePollingIntervalMs`
- `FabricationConfig.cncSupportEnabled`, `print3dSupportEnabled`,
  `materialWasteThresholdPct`
- `SustainabilityConfig.localRadiusKm`

`ConfigManager` holds the validated config in memory: `get`, `getSection`,
`update` (deep-merges then re-validates), `onChange` (returns an unsubscribe
function), `reset`. `createConfigFromEnv` reads `SESHAT_SECTION_KEY`-style
environment keys, coercing `true`/`false`/integers/floats.

### Errors

All Seshat errors extend `SeshatError`, which carries a numeric code, a severity
level, and a structured context record. The numeric codes are grouped by
functional area so that error monitoring can route by area without parsing the
message string.

`SeshatError extends Error` carries `code` (`SeshatErrorCodeValue`), `severity`
(`SeshatErrorSeverity` enum: `info|warning|error|critical`), and a `context`
record; `toJSON()` serialises it. `SeshatErrorCode` is a numeric code map
grouped by area:

- Project: 1001–1004
- Workflow: 2001–2004
- Module: 3001–3003
- Config: 4001–4002
- Validation: 5001–5003
- Feature Flags: 6001–6002

Concrete subclasses: `ProjectNotFoundError`, `InvalidPhaseTransitionError`,
`BudgetExceededError`, `WorkflowStepBlockedError`, `CycleDetectedError`,
`ModuleUnavailableError`, `FeatureDisabledError`. Type guard: `isSeshatError`.

### Logging

`SeshatLogger` is a self-contained structured logger (no Pino dependency).
`LOG_LEVELS`: `trace 10` … `fatal 60`. Emits `SeshatLogEntry` objects to one or
more `LogSink` functions; `defaultConsoleSink` writes JSON to the console,
`MemoryLogSink` captures entries for tests. `child()` creates a logger with
extended context. Base context is always `{ domain: 'seshat' }`.

### Feature Flags

The feature flag system controls capability exposure per user without branching
library code. The percentage rollout uses a deterministic FNV-1a hash keyed on
`userId`, so a given user always gets the same result for a given flag — this
prevents the "flag flipping" experience where a feature appears and disappears
on successive page loads.

`FeatureFlagManager` evaluates flags with deterministic FNV-1a-hash percentage
rollout keyed on `userId`, plus manual overrides. `SESHAT_FEATURES` defines 10
flags:

- `HARMONY_FENG_SHUI_V2`
- `HARMONY_VASTU_SHASTRA`
- `DESIGN_AR_PREVIEW`
- `DESIGN_PHOTOREALISTIC_RENDER`
- `CRAFT_AI_JOINERY`
- `SMART_DWELLING_MQTT`
- `FABRICATION_CNC`
- `FABRICATION_3D_PRINT`
- `SUSTAINABILITY_CARBON_TRACKING`
- `ACADEMY_MENTORSHIP_MATCHING`

`evaluate` returns `{ key, enabled, reason }` where `reason` is one of
`override`, `rollout-all`, `rollout-none`, `rollout-hash`, `default`, `unknown`.

---

## Shared Types & Constants (`@seshat/common`)

`@seshat/common` exports an extensive type vocabulary plus real-world constant
databases. It declares the platform identity in its header as eight pillars:
Spatial Harmony, Interior Design, Craftsman's Forge, Maker's Academy, Smart
Dwelling, Workshop Management, Digital Fabrication, Sustainability.

### Branded ID & Measurement Types

Type safety for IDs prevents accidentally passing a `RoomId` where a `ToolId` is
expected. Branded types give compile-time guarantees beyond what a plain
`string` provides.

Branded string IDs: `ProjectId`, `MaterialId`, `ToolId`, `DeviceId`, `RoomId`,
`FloorId`, `BuildingId`, `UserId`, `CourseId`, `LessonId`, `AutomationId`.
Measurement: `LengthUnit`, `AreaUnit`, `VolumeUnit` (includes `board_feet`),
`AngleUnit`, `TemperatureUnit`, `WeightUnit`; generic `Measurement<U>` and its
aliases.

### Geometry Types

These geometry primitives are the lowest-level shared vocabulary. They appear in
floor plan analysis, Feng Shui chi flow simulation, fabrication nesting, and
parametric design — a single consistent set prevents duplicate type hierarchies
across libraries.

2D: `Point2D`, `Vector2D`, `BoundingBox2D`, `Polygon2D`, `LineSegment2D`,
`Dimensions2D`. 3D: `Point3D`, `Vector3D`, `BoundingBox3D`, `Dimensions3D`,
`EulerAngles`, `Transform3D`.

### Spatial / Architectural Types

`CompassDirection` (8-point), `CardinalDirection`, `IntercardinalDirection`,
`CompassBearing`. `RoomType` is a 26-value union (`bedroom`, `bathroom`,
`kitchen`, … `attic`, `basement`). `Room`, `DoorOpening`, `WindowOpening`,
`Floor`, `Building`, `FloorPlan` describe a building hierarchy. `Building`
carries `orientation` (degrees from true north), optional `latitude` /
`longitude` / `yearBuilt`, and `buildingType`
(`residential|commercial|mixed|industrial|institutional`).

### Feng Shui & Vastu Types

These types implement the conceptual vocabulary of both traditions, enabling
harmony analysis functions to produce richly typed results that downstream code
can inspect without string parsing.

`BaguaArea` (9 values: `wealth`, `fame`, `love`, `family`, `health`,
`creativity`, `knowledge`, `career`, `helpful_people`). `FiveElement`
(`wood|fire|earth|metal|water`). `ElementCycle`
(`generating|controlling|weakening|insulting`). `FlyingStarNumber` (1–9),
`FlyingStar`, `FlyingStarChart`, `KuaNumber`. `ChiFlowType`
(`sheng_chi|sha_chi|si_chi`). `FengShuiRemedyType` (14 values).
`FengShuiAnalysis`, `BaguaAreaAssessment`.

Vastu types: `VastuDirection` (9), `VastuPada` (17-value Purusha Mandala union:
`ishanya`, `parjanya`, … `soma`, `brahma`). `VastuElement`
(`prithvi|jala|agni|vayu|akasha`). `VastuDevta`, `VastuDefectType` (12),
`VastuRemedy`, `VastuZone`, `VastuAnalysis`.

### Design Philosophy Types

`WabiSabiPrinciple` (7: `fukinsei`, `kanso`, `koko`, `shizen`, `yugen`,
`datsuzoku`, `seijaku`). `HyggeElement` (12). `BiophilicPattern` (14, Terrapin
Bright Green framework). `BiophilicPatternInfo`. `SacredGeometryType` (10).
`SacredGeometry`. `PlatonicSolid` (5). `PlatonicSolidInfo`.

### Material, Joinery, Tool & Project Types

The material and joinery type system is especially rich because it encodes
woodworking knowledge directly into types — a function that accepts
`WoodSpecies` gets automatic IDE documentation for every property the species
carries.

`MaterialCategory` (17). `GrainPattern` (8). `GrainDirection` (4).
`MaterialGrade` (`FAS|select|no1_common|no2_common|no3_common|utility`).
`WoodMoistureContent`. `WoodWorkability` (nine 1–10 sub-ratings). `WoodSpecies`
(full physical-property record). `FinishType` (14). `FinishInfo`. `AdhesiveType`
(10). `AdhesiveInfo`.

`JointType` is a 30-value union spanning Western, Japanese (`sashimono`,
`kumiko`, `kanawa_tsugi`, `kawai_tsugi`, `okkake_daisen_tsugi`) and Chinese
(`mitered_mortise_tenon`, `cloud_lift_panel`) joinery, along with
`JointTradition`, `JointStrength` (tensile/shear/compression/racking/overall
rated 1–10), `JointDifficulty` (1–10), `JointInfo`, `CuttingSequence`,
`CuttingStep`.

`ToolCategory` (29 values). `ToolPowerSource`. `HandTool`, `PowerTool`,
`CNCTool`. `ToolCondition`. `MaintenanceSchedule`. `MaintenanceTask`.

Project domain: `ProjectDifficulty` (`beginner|intermediate|advanced|master`).
`ProjectType` (15). `ProjectPhase` (a 10-stage craft-phase union, distinct from
`@seshat/core`'s phase enum — these are craft-specific phases, not lifecycle
phases). `Project`, `CutList`, `CutListItem`, `BillOfMaterials`, `HardwareItem`,
`MaterialEstimate`, `FinishEstimate`, `AdhesiveEstimate`.

### IoT / Smart Home Types

`SmartDeviceType` (8). `SensorType` (15). `DeviceProtocol` (9: `zigbee`,
`zwave`, `wifi`, `bluetooth`, `thread`, `matter`, `lora`, `modbus`, `knx`).
`SmartDevice`, `SensorReading`. `AutomationTriggerType` (9).
`AutomationTrigger`. `AutomationActionType` (7). `AutomationAction`,
`AutomationRule`, `HomeEnvironment`.

### Design / Visualization Types

`DesignStyle` (24-value union, covering all major Western and Eastern interior
design styles). `ColorHarmony` (6). `RGBColor`, `HSLColor`, `DesignColor`,
`ColorPalette`. `RenderQuality` (`draft|preview|standard|high|production`).
`RenderFormat`. `MoodBoardItem`, `DesignBrief`, `DesignStyleInfo`.

### Sustainability, Learning & Fabrication Types

Sustainability: `SustainabilityRating` (`A`–`F`). `CertificationType` (10:
`fsc`, `pefc`, `cradle_to_cradle`, `greenguard`, `leed`, `breeam`, `well`,
`living_building_challenge`, `energy_star`, `blue_angel`). `CarbonFootprint`,
`LifeCycleAssessment`. `CircularDesignPrinciple` (10).
`SustainabilityAssessment`.

Learning: `SkillLevel` (`novice`…`master`, 6 levels). `AssessmentType` (7).
`CertificationLevel`
(`foundation|practitioner|professional|master|grand_master`). `LearningPath`,
`CourseModule`, `LessonPlan`, `StudentProgress`.

Fabrication: `CNCOperationType` (9). `PrintMaterial` (9). `GCodeCommand`,
`CNCToolpath`, `PrintSettings`, `LaserSettings`.

### Events Type (declaration only)

The event types below describe the domain events Seshat _could_ emit if an event
bus were wired up. They are pure type declarations — no publisher, subscriber,
or transport exists in any `libs/seshat/` library. They appear here so that the
Phase 36 event infrastructure can be implemented against a pre-agreed type
contract.

`SeshatEventType` is a 12-value union:

- `project_created`, `project_updated`, `project_completed`
- `material_added`, `material_depleted`
- `tool_maintenance_due`
- `sensor_alert`, `automation_triggered`
- `lesson_completed`, `certification_earned`
- `design_saved`, `render_completed`

`SeshatEvent<T>` is a generic envelope wrapping a payload of type `T`.

### Constant Databases

`common/src/constants.ts` ships curated reference data used across all
libraries. These are real-world values, not placeholders — wood species
properties come from the Wood Handbook (USDA Forest Products Laboratory); joint
strength ratings from woodworking technical literature; protocol specs from
manufacturer documentation.

- `WOOD_SPECIES` — keyed record of **30 wood species** with real Janka hardness,
  density, shrinkage, and per-operation workability ratings.
- `BAGUA_AREAS` (9 entries), `ELEMENT_CYCLES` (20 element-pair relations across
  all four cycles), `VASTU_ZONES` (9 directional zones).
- `GOLDEN_RATIO`, `FIBONACCI_SEQUENCE` (first 20), `SACRED_GEOMETRY` (10
  entries), `PLATONIC_SOLIDS` (5).
- `COLOR_PSYCHOLOGY` (21 colours with emotions, cultural meanings, Feng Shui
  element), `BIOPHILIC_PATTERNS` (14 patterns with stress-reduction /
  cognitive-performance scores), `DESIGN_STYLES` (24 style profiles),
  `JOINT_DATABASE` (20 joints with strength ratings).
- `COMPASS_DEGREES`, `COMPASS_DIRECTIONS`, `LENGTH_TO_MM`, `WEIGHT_TO_G`,
  `JANKA_CATEGORIES`, `CERTIFICATIONS` (10), `SKILL_LEVEL_HOURS` (6 tiers),
  `DEVICE_PROTOCOL_SPECS` (9 protocols with frequency / range / mesh support).

### Utility Functions

`common/src/utils.ts` exports pure functions covering the mathematical
operations needed across all Seshat domains:

- **Geometry**: `calculatePolygonArea` (shoelace formula), `pointInPolygon`
  (ray-casting), `polygonCentroid`, `lineIntersection`, rotations, volume/area
  formulas.
- **Measurement conversion**: `convertLength`, `convertArea`, `convertVolume`,
  `convertWeight`, `convertTemperature`, `convertAngle`, `boardFeetToVolume`.
- **Material maths**: `calculateBoardFeet`, `calculateMoistureExpansion` (using
  a 28% fibre-saturation point), `calculateWoodWeight`, `jankaHardnessCategory`.
- **Compass helpers**: compass bearing and direction utilities.
- **Colour**: `hexToRgb`, `rgbToHex`, `hexToHsl`, `hslToHex`, `colorContrast`
  (WCAG ratio), `generateColorPalette`, `blendColors`.
- **Proportion**: `isGoldenRatio`, `fibonacciSequence`, `harmonicProportion`,
  `ruleOfThirdsGrid`.
- **Scoring**: `normalizeScore`, `weightedAverage`, `letterGrade`,
  `difficultyLabel`.

---

## Craft Specifications (`@seshat/craft`)

`@seshat/craft` is a pure-function woodworking knowledge engine. Domain types in
`craft/src/types.ts` include the following. These are the local, extended types
used inside the craft library, many of which extend or refine the base types
from `@seshat/common`:

`JointDetail` (extends `JointInfo` with cutting sequence, common mistakes, tips,
estimated time, optional angle), `SashimonoJoint`, `KumikoPattern`,
`DovetailSpec`, `MortiseTenonSpec`, `JointSelectionCriteria`,
`JointSelectionResult`, `WoodIdentification`, `WoodComparison`, `GrainAnalysis`,
`MoistureAnalysis`, `MaterialBillItem`, `BillOfMaterials`, `ToolProfile`,
`SharpnessAssessment`, `CNCFeedSpeed`, `SandingProgression`, `FinishProfile`,
`FinishCompatibility`, `FinishSelectionCriteria`, `FinishSelectionResult`,
`WoodworkingProject`, `CutListItem`, `TimeEstimate`,
`ProjectDifficultyAssessment`, `ProjectTemplate`.

### Joinery (`joinery.ts`)

The joinery module contains three constant databases and five geometry
computation functions, plus the joint selection wizard.

**Constant databases:**

- `SASHIMONO_JOINTS` — database of Japanese joints (e.g. `ari-tsugi`,
  `kama-tsugi`, `hozo-sashi`, `kanawa-tsugi`, `kawai-tsugi`), each with
  romanized/Japanese/English names, difficulty, strength ratings, cutting
  sequence, common mistakes, best use cases.
- `KUMIKO_PATTERNS` — geometric lattice patterns (`asanoha`, `izutsu`, `kikko`,
  `sakura`, …) with strip angles, strips-per-unit, symbolism.
- `WESTERN_JOINT_DETAILS` — extended `JointDetail` records for common Western
  joints; `DOVETAIL_RATIOS` and constants `DRAWBORE_OFFSET_STANDARD` (1/16") and
  `DRAWBORE_OFFSET_DELICATE` (1/32").

**Geometry computations:** `calculateDovetailLayout` (pin/tail positions),
`calculateMortiseTenonSize` (tenon thickness/width/length, haunch),
`calculateDrawboreOffset`, `calculateBoxJoint`, `calculateKumikoNotch`.

**Selection / lookup:** `selectJoint` (scored recommendations from
`JointSelectionCriteria`), `findSashimonoJoint`, `findKumikoPattern`,
`getJointsByTradition`, `getJointsForApplication`.

### Materials, Tools, Finishing, Projects

These modules are grouped here because each corresponds to a single source file.
All functions are pure.

- **`materials.ts`**: `getWoodSpecies`, `resolveSpeciesKey`, `compareSpecies`,
  `findSimilarSpecies`, `recommendSpecies`, `calculateEMC` /
  `calculateEMCCelsius` (equilibrium moisture content),
  `predictSeasonalMovement`, `analyzeMoisture`, `calculateDryingTime`,
  `analyzeCutOrientation`, `identifyWood`, `generateBOM`.
- **`tools.ts`**: `calculateFeedsAndSpeeds`, `calculateOptimalRPM`,
  `calculateSandingProgression`, `getFinishSandingGrit`,
  `getSharpnessAssessment`, `suggestToolUpgrade`, `getToolDatabase`.
- **`finishing.ts`**: `FINISH_DATABASE`; `getFinish`, `getFinishesByType`,
  `getFoodSafeFinishes`, `getLowVOCFinishes`, `selectFinish`,
  `checkFinishCompatibility`, `getFinishSandingGritByKey`.
- **`projects.ts`**: `PROJECT_TEMPLATES`, constants `STANDARD_KERF` (0.125") and
  `THIN_KERF` (0.09375"); `getProjectTemplate`, `getProjectsByCategory`,
  `getProjectsByJoint`, `generateCutList`, `estimateProjectTime`,
  `assessDifficulty`.

---

## Design Specifications (`@seshat/design`)

`@seshat/design` has **no Zod schemas and no AI runtime** — it is pure functions
over `@seshat/common` types producing structured analysis objects. The library
models room visualisations as descriptive data structures (`RoomVisualization`,
`RenderSettings`, `MaterialSurface`, `VisualizationFurniture`,
`LightingSource`), not as image generation.

Key types defined in `design/src/types.ts`:

`ParsedDesignBrief`, `DesignConstraint`, `StyleKeyword`, `TimeOfDay` (8 values),
`CameraPerspective` (7), `DesignEra` (13), `StyleScore`, `StyleClassification`,
`StyleInterpolation`, `StyleConsistencyResult`, `StyleDatabaseEntry`,
`ParametricDefinition`, `ParametricConstraint`, `ParametricParameter`,
`JointType` (a design-local 12-value union), `TopologyOptimization`,
`DesignFitnessScore`, `DesignCandidate`, `GeneticDesignResult`,
`VoronoiPattern`, `VoronoiCell`, `ShelvingSystem`, `ShelfSpec`,
`FloorPlanAnalysis`, `RoomProportionScore`, `NaturalLightScore`,
`TrafficFlowResult`, `FurnitureCategory` (15), `FurnitureItem`,
`FurnitureLayout`, `ClearanceCheck`, `WorkTriangleResult`, `LayoutPreset`,
`LayoutArrangement`, `MoodBoardAnalysis`, `ExtractedColor`, `StyleTag`,
`BudgetEstimate`, `BudgetLineItem`, `ProductMatch`, `AccessibilityAudit`.

Functions by area:

- **Style:** `STYLE_DATABASE` (record keyed by all 24 `DesignStyle` values);
  `classifyStyle`, `checkStyleConsistency`, `interpolateStyles`, `getStyleInfo`,
  `getComplementaryStyles`, `getClashingStyles`.
- **Floor plan:** `CLEARANCE_STANDARDS`, `LAYOUT_PRESETS`; `analyzeFloorPlan`,
  `analyzeTrafficFlow`, `analyzeWorkTriangle`, `checkAccessibility`,
  `checkClearances`, `generateFurnitureLayout`, `getLayoutPresets`,
  `recommendLayoutPreset`.
- **Parametric:** `createParametricDesign`, `validateParametricConstraints`,
  `optimizeTopology`, `evolveDesign` (genetic algorithm),
  `generateVoronoiPattern`, `generateShelvingSystem`.
- **Mood board:** `analyzeMoodBoard`, `extractMoodBoardPalette`,
  `generateStyleTags`, `parseDesignBrief` (rule-based natural-language parse).
- **Product discovery:** `STYLE_MULTIPLIERS`, `QUALITY_MULTIPLIERS`;
  `matchProducts`, `classifyBudgetTier`, `estimateRoomBudget`,
  `compareBudgetTiers`, `getStyleMultiplier`, `getQualityMultiplier`.

---

## Fabrication Specifications (`@seshat/fabrication`)

Pure functions, no Zod schemas. Types in `fabrication/src/types.ts` cover
machines and tools, toolpaths/G-code, laser settings, 3D printing parameters,
and nesting. Specific type groups:

- **Machines and tools:** `CNCMachine`, `CuttingTool`, `ToolGeometry`,
  `ToolMaterial`, `ToolCoating`, `WorkpieceMaterial` (21-value family list),
  `FeedSpeedResult`.
- **Toolpaths/G-code:** `ToolpathSegment`, `CNCToolpathExtended`,
  `GCodeProgram`.
- **Laser:** `LaserMachineSpec`, `LaserCutSettings`, `LaserCutJob`,
  `LaserShape`, `LaserMaterial`, `LaserOperationMode`, `LaserSourceType`.
- **3D printing:** `ModelMesh`, `PrinterProfile`, `PrinterTechnology`,
  `PrintJobSettings`, `PrintQuality`, `InfillPattern`, `SupportStrategy`,
  `AdhesionType`, `PrintTimeEstimate`, `MaterialUsageEstimate`, `PrintJob3D`.
- **Nesting:** `NestingPart`, `PlacedPart`, `NestingRotation`,
  `SheetDimensions`, `SheetNestingResult`, `NestingResult`,
  `CutOptimizationResult`, `OrderedCut`.
- **Digital twin (declared but not exercised):** `DigitalTwin`, `TwinError`,
  `SensorSnapshot`, `TwinSyncState`. `fabrication/src/index.ts` exports no
  digital-twin functions and there is no `digital-twin.ts` module.

Implemented functions:

- **CNC (`cnc.ts`):** `calculateFeedsAndSpeeds`, `generateGCode` (returns a full
  `GCodeProgram`), `optimizeToolpath`, `calculateKerfCompensation`,
  `estimateMachiningTime`; tables `SFM_TABLE`, `CHIP_LOAD_TABLE`,
  `UNIT_POWER_TABLE`, constant `MAX_DOC_FACTOR`.
- **Laser (`laser.ts`):** `calculateLaserSettings`, `generateLaserToolpath`,
  `calculateMaterialUsage` (re-exported as `calculateLaserMaterialUsage`); table
  `MATERIAL_PROFILES`.
- **3D printing (`printing3d.ts`):** `calculatePrintSettings`,
  `estimatePrintTime`, `estimateMaterialUsage` (as
  `estimatePrintMaterialUsage`); tables `MATERIAL_DB`, `LAYER_HEIGHTS`, constant
  `DEFAULT_INFILL`.
- **Nesting (`nesting.ts`):** `nestParts` (2D bin-packing),
  `optimizeCutSequence`, `estimateSheetsRequired`, `calculateWasteWithKerf`.

---

## Harmony Specifications (`@seshat/harmony`)

Pure functions producing detailed analysis objects. The result-type vocabulary
in `harmony/src/types.ts` is large. The types are organized below by tradition.

**Feng Shui types:** `BaguaAnalysis`, `BaguaSectorResult`, `FlyingStarChart`,
`FlyingStarPalace`, `FlyingStarPeriod`, `FlyingStarInterpretation`,
`KuaNumberResult`, `KuaDirectionSet`, `ChiFlowResult` (with `FlowFieldCell`,
`StagnationZone`, `ShaChiSource`, `ChiEntryPoint`, `ChiFlowRemedy`),
`ElementBalanceResult`, `PoisonArrowDetection`, `PoisonArrow`,
`RoomFengShuiAnalysis`.

**Vastu types:** `VastuFullAnalysis`, `VastuPurushaMandalaResult`,
`VastuMandalaCell`, `BrahmasthanaStatus`, `VastuDirectionResult`,
`VastuRoomPlacementResult`, `VastuDefectResult`, `DwarVedhiResult`,
`VastuRecommendation`.

**Philosophy, biophilic, geometry, colour types:** `WabiSabiAssessment`,
`HyggeAssessment`, `BiophilicAssessment`, `BiophilicPatternScore`,
`BiophilicRecommendation`, `PlantRecommendation`, `SacredGeometryAnalysis`,
`GoldenSpiralResult`, `VesicaPiscisResult`, `FlowerOfLifeResult`,
`ColorPsychologyReport` (with 60-30-10 `ColorProportionAnalysis`,
`ColorTemperatureAnalysis`, WCAG `ColorAccessibilityAnalysis`).

**Synthesis types:** `HarmonyTradition` (7-value union), `HarmonySynthesis`,
`TraditionConflict`, `TraditionAgreement`, `SynthesisRecommendation`,
`SynthesisConfig`.

Functions by source file:

- **Feng Shui (`feng-shui.ts`):** `analyzeBagua`, `analyzeElementBalance`,
  `calculateFlyingStarChart`, `calculateAnnualStar`, `calculateKuaNumber`,
  `simulateChiFlow`, `detectPoisonArrows`, `analyzeBedroom`, `analyzeKitchen`,
  `analyzeHomeOffice`, `analyzeEntrance` (exported as
  `analyzeFengShuiEntrance`), `getPeriodForYear`, element helpers
  (`getGeneratingElement`, `getControllingElement`, `getGeneratedElement`,
  `colorToElement`, `materialToElement`, `shapeToElement`).
- **Vastu (`vastu-shastra.ts`):** `createVastuMandala`, `analyzeDirections`,
  `validateRoomPlacement`, `detectVastuDefects`, `analyzeEntrance` (as
  `analyzeVastuEntrance`), `performFullVastuAnalysis`.
- **Design philosophy (`design-philosophy.ts`):** `assessWabiSabi`,
  `assessHygge`; `HYGGE_ELEMENTS` record.
- **Biophilic (`biophilic-design.ts`):** `assessBiophilicDesign`,
  `recommendPlants`.
- **Sacred geometry (`sacred-geometry.ts`):** `analyzeProportions`,
  `generateGoldenSpiralPoints`, `generateVesicaPiscis`, `generateFlowerOfLife`,
  `isGoldenRatio`, `isFibonacciRatio`, `goldenDivision`,
  `goldenRectangleSubdivisions`.
- **Colour psychology (`color-psychology.ts`):** `analyzeRoomColors`.
- **Synthesis (`synthesis.ts`):** `synthesizeHarmony` — weighted multi-tradition
  composite with conflict detection.

---

## Smart Dwelling Specifications (`@seshat/smart`)

### Domain Types

`IoTDevice` extends the base device type with `groupIds`, `firmware`
(`FirmwareInfo`), `signalStrength`, `capabilities` (`DeviceCapability[]`), and
`metadata`. `DeviceStatus` is a 7-value union: `online`, `offline`, `error`,
`pairing`, `updating`, `sleeping`, `initializing`.

Supporting device types: `DeviceHealth`, `DeviceFilter`, `DeviceGroup`.

Sensor types: `SensorReadingExtended` (carries `rawValue` / `calibratedValue`
and `SensorQuality`: `excellent|good|degraded|poor|invalid`).
`CalibrationParams`, `CalibrationPoint`, `SensorConfig`, `SensorThreshold`,
`AnomalyResult`, `SensorFusionResult`, `SensorFusionSource`.

Automation types: `AutomationRuleDefinition` (extends the base rule with
`triggerLogic`: `and|or`, `cooldownMs`, `schedule`, and tags);
`AutomationTriggerExtended`, `AutomationActionExtended` (webhook + notification
fields), `AutomationCondition`, `GeofenceConfig`, `AutomationSchedule`, `Scene`,
`SceneDeviceState`, `RuleEvaluationResult`, `TriggerEvaluationResult`,
`ActionExecutionResult`.

Per-protocol config interfaces — `ZigbeeConfig`, `ZWaveConfig`, `MatterConfig`,
`WiFiDeviceConfig`, `BLEDeviceConfig`, `ThreadConfig` — unified by the
discriminated union `ProtocolConfig`.

Wellness / ergonomics: `PressureMap`, `PressureCell`, `WeightDistribution`,
`PostureAnalysis`, `SittingEvent`, `SittingDurationResult`,
`SleepQualityResult`, `SleepSensorData`, `CircadianLightingResult`,
`EnvironmentalComfortResult`, `ThermalComfortResult` (simplified ASHRAE 55 PMV),
`AirQualityResult`, `HumidityComfortResult`, `NoiseComfortResult`,
`WellnessReport`.

### Runtime Surfaces

`DeviceRegistry` is an in-memory class (created via `createDeviceRegistry`
factory). Methods:

`registerDevice`, `deregisterDevice`, `getDevice`, `listDevices`,
`getDeviceCount`, `updateDeviceFirmware`, `getFirmwareHistory`,
`checkDeviceHealth`, `recordDeviceError`, `updateLastSeen`,
`updateDeviceStatus`, `groupDevices`, `getGroup`, `listGroups`,
`addDeviceToGroup`, `assignDeviceToRoom`, `getDevicesByRoom`,
`setProtocolConfig`, `getProtocolConfig`, `getProtocolSummary`,
`getDevicesNeedingAttention`, `clear`.

Free functions: `validateProtocol`, `validateProtocolConfig`,
`assessSignalQuality`, `estimateBatteryDays`, `detectCapabilities`.

`SensorEngine` (created via `createSensorEngine`) processes readings; supporting
tables `SENSOR_DEFAULT_UNITS`, `SENSOR_RANGES`. Pure helpers include unit
conversions (temperature, pressure across `pa/hpa/psi/bar/atm/mmhg`, light
`lux ↔ foot_candle`), `calculateLinearCalibration`, `applyCalibration`,
`validateSensorReading`, `processSensorReading`, `calculateMovingAverage`,
`calculateExponentialMovingAverage`, `calculateStats`, `detectAnomaly`
(z-score), `fuseSensorData`, `evaluateThresholds`.

`AutomationEngine` and `SceneManager` (created via `createAutomationEngine`,
`createSceneManager`) evaluate rules and scenes. Pure helpers: `sensorKey`,
`evaluateTrigger`, `evaluateCompoundTriggers`, `evaluateCondition`,
`evaluateConditions`, `evaluateRule`, `evaluateRules`, `executeAction` (async),
`executeRuleActions` (async).

Wellness functions: `calculateWeightDistribution`, `calculateLeanAngle`,
`analyzePosture`, `trackSittingDuration`, `assessSleepQuality`,
`calculateCircadianLighting`, `assessThermalComfort`, `assessAirQuality`,
`assessHumidityComfort`, `assessNoiseComfort`, `assessEnvironmentalComfort`.

---

## Sustainability Specifications (`@seshat/sustainability`)

### Domain Types

`LifeCycleStage` (6: `extraction`, `manufacturing`, `transport`, `use`,
`maintenance`, `end_of_life`). `SystemBoundary`
(`cradle_to_gate|cradle_to_grave|cradle_to_cradle`). `TransportMode`
(`road|rail|sea|air`). `PowerSource` (10 grid/source values).

`MaterialCategory` is a sustainability-local 20-value union that extends the
common material categories with recycled variants: `recycled_steel`,
`recycled_aluminum`, `recycled_plastic`.

`ManufacturingProcess` (19 processes). `CarbonBreakdown` (with
`sequestrationCredit`). `MaterialCarbonInput`, `TransportCarbonInput`,
`ManufacturingCarbonInput`. `ProductDefinition`. `EndOfLifeScenario`,
`DisposalMethod` (8). `ImpactCategory` (8 ISO 14044 categories). `StageImpact`,
`LCAResult`, `ImprovementSuggestion`. `ProductComparison`, `StageComparison`.

`FastenerType` (15). `JointInfo`. `MaterialMarking` (ISO 11469).
`CircularDesignScore` (durability / repairability / recyclability / reusability
/ material-efficiency subscores). `CircularityInput`. `RepairabilityInput`
(French repairability index inputs). `DfDRecommendation`.

`WasteStream` (12). `WasteDiversionMethod` (7). `WasteEntry`, `WasteAudit`,
`WasteStreamSummary`. `CertificationStatus`. `FSCClaimType` (4).
`FSCChainOfCustodyRecord`, `FSCInput`, `FSCOutput`. `CertificationRecord`.
`LEEDCreditCategory` (7). `LEEDCreditContribution`. `LEEDAssessment`.
`SupplyChainEntry`, `MaterialSustainability`, `SustainabilityReport`.

### Functions & Tables

- **Carbon (`carbon.ts`):** `calculateMaterialCarbon`,
  `calculateTransportCarbon`, `calculateManufacturingCarbon`,
  `calculateEndOfLifeCarbon`, `calculateTotalCarbon`, `carbonRating`,
  `compareMaterialCarbon`, `calculateSupplyChainCarbon`, `carbonPaybackPeriod`,
  `describeMaterialCarbon`. Tables/constants: `MATERIAL_CARBON_FACTORS`,
  `WOOD_CARBON_SEQUESTRATION_PER_KG` (1.84 kgCO₂/kg dry wood),
  `SEQUESTRATION_ELIGIBLE`, `PARTIAL_SEQUESTRATION`,
  `TRANSPORT_EMISSION_FACTORS`, `DEFAULT_LOAD_FACTORS`, `PROCESS_POWER_KW`,
  `GRID_EMISSION_FACTORS`, `END_OF_LIFE_FACTORS`.
- **LCA (`lifecycle.ts`):** `performLCA`, `compareProducts`, `identifyHotspots`,
  `suggestImprovements`.
- **Circular design (`circular-design.ts`):** `assessCircularity`,
  `assessRepairability`, `designForDisassembly`, `quickCircularityScore`.
- **Certification (`certification.ts`):** `createCertificationRecord`,
  `trackCertification`, `isCertificationValid`, `daysUntilExpiry`,
  `filterCertificationsByStatus`, `getCertificationsExpiringSoon`,
  `validateChainOfCustody`, `determineMaxFSCClaim`, `assessLEEDContribution`,
  `assessMaterialSustainability`, `generateSustainabilityReport`. Constants
  `LEED_LEVELS`, `LEED_CATEGORY_MAX_POINTS`, `LEED_VOC_LIMITS`.

---

## Academy Specifications (`@seshat/academy`)

### Domain Types

`CraftDomain` is a 16-value union identifying the major areas of craft practice:
`woodworking`, `joinery`, `wood_turning`, `wood_carving`, `furniture_making`,
`cabinet_making`, `interior_design`, `spatial_harmony`, `finishing`,
`upholstery`, `digital_fabrication`, `sustainability`, `restoration`,
`timber_framing`, `marquetry`, `luthiery`.

`CraftSubSkill` is a large union of named sub-skills grouped by domain.
`SkillProficiency`, `AssessmentRubric`, `AssessmentRubricCriterion`,
`SkillAssessmentResult`, `StudentSkillProfile`.

Curriculum: `LessonContentType` (10), `LessonContent`, `AcademyLesson`,
`AcademyCourse`.

Learning paths: `LearningGoal`, `LearningPathNode`, `PersonalizedLearningPath`.

Certification: `CertificationProgram`, `CertificationRecord`,
`CertificationEligibility`.

Mentorship: `TeachingStyle` (6), `LearningStyle` (5), `CommunicationPreference`
(5), `TimeSlot`, `MentorProfile`, `ApprenticeProfile`, `MentorMatch`
(8-dimension compatibility breakdown).

Knowledge base: `TechniqueEntry`.

### Functions & Catalogs

- **Skill assessment (`skill-assessment.ts`):** `SKILL_LEVEL_THRESHOLDS`,
  `ASSESSMENT_RUBRICS`; `scoreToSkillLevel`, `skillLevelToScore`,
  `meetsSkillRequirement`, `calculateWeightedScore`, `executeAssessment`,
  `getSubSkillDomain`, `buildSkillProfile`, `assessmentResultToProficiency`,
  `identifySkillGaps`.
- **Learning paths (`learning-path.ts`):** `COURSE_CATALOG`;
  `compareSkillLevels`, `checkPrerequisites`, `resolvePrerequisiteChain`,
  `findCoursesForSkills`, `generateLearningPath`, `formatDomainName`,
  `formatSkillLevel`, `estimateProgressionHours`, `getPrerequisiteTree`.
- **Certification (`certification.ts`):** `CERTIFICATION_PROGRAMS`;
  `checkCertificationEligibility`, `issueCertification`, `isCertificationValid`,
  `getRenewalStatus`, `getCertificationPathForDomain`,
  `getAllCertificationPrograms`.
- **Mentorship (`mentorship.ts`):** `DEFAULT_MATCHING_WEIGHTS`; per-dimension
  scorers (`scoreSkillAlignment`, `scoreScheduleCompatibility`,
  `scoreCommunicationMatch`, `scoreStyleCompatibility`, `scoreDomainRelevance`,
  `scoreLogisticalFit`, `scoreAvailability`, `scoreReputation`),
  `scoreMentorMatch`, `findBestMentors`, `validatePairingViability`.

---

## Workshop Specifications (`@seshat/workshop`)

### Domain Types

Branded IDs: `WorkshopId`, `ZoneId`, `BookingId`, `IncidentId`, `CircuitId`,
`MaintenanceId`, `DuctRunId`.

Layout: `WorkshopZoneType` (13), `FlooringType` (7), `WorkshopZone`,
`MachineCategory` (22), `MachineClearance`, `MachinePlacement`,
`WorkflowSequence`, `WorkshopLayout`.

Inventory: `ToolCondition` (7), `OwnershipStatus` (4), `ToolInventory`,
`MaintenanceType` (12), `MaintenanceRecord`, `MaintenanceSchedule`.

Materials: `MaterialType` (22), `LumberDimensions`, `MaterialStock`,
`MaterialUsageEntry`, `ReorderRecommendation`, `InventoryReport`.

Safety: `PPEType` (10), `FireSuppressionType` (4), `EmergencyEquipment`,
`SafetySystem`, `IncidentSeverity` (5), `IncidentCategory` (14),
`SafetyIncident`, `MachineSafetyBriefing`, `NoiseExposureResult`.

Scheduling: `BookingStatus` (5), `BookableResourceType` (4), `BookableResource`,
`TimeSlot`, `BookingSlot`, `BookingConflict`, `ResourceUtilization`.

Dust collection: `DuctMaterial` (4), `DuctFitting` (6), `DuctSection`,
`DuctRun`, `DustCollectionSystem`.

Electrical: `BreakerType` (4), `WireGauge` (AWG literal union),
`ElectricalCircuit`, `ElectricalPanelSummary`.

Layout-analysis results: `ClearanceViolation`, `WorkflowAnalysis`,
`LayoutAnalysis`, `SafetyComplianceResult`.

### Functions & Tables

- **Layout (`layout.ts`):** tables `MACHINE_CLEARANCES`,
  `MACHINE_CFM_REQUIREMENTS`, `MACHINE_DUST_PORT_INCHES`,
  `MACHINE_NOISE_LEVELS`, `MACHINE_AMPERAGE`, `COMMON_WORKFLOWS`,
  `FITTING_EQUIVALENT_LENGTH`; functions `getMachineClearanceEnvelope`,
  `validateClearances`, `analyzeWorkflow`, `designWorkshopLayout`,
  `calculateEquivalentLength`, `calculateStaticPressureLoss`,
  `calculateDustCollection`, `recommendWireGauge`, `calculateVoltageDrop`,
  `recommendBreakerType`, `calculateElectricalRequirements`.
- **Inventory (`inventory.ts`):** in-memory tool and material stores —
  `addTool`, `getTool`, `getAllTools`, `updateTool`, `removeTool`,
  `recordMaintenance`, `scheduleMaintenance`, `checkMaintenanceDue`,
  `getToolsByCondition`, `clearToolStore`, `trackMaterialStock`, `getMaterial`,
  `getAllMaterials`, `getMaterialsByType`, `deductMaterial`,
  `getMaterialUsageHistory`, `estimateReorderPoint`,
  `calculateBoardFeetFromDimensions`, `findLowStockMaterials`,
  `clearMaterialStore`, `generateInventoryReport`.
- **Safety (`safety.ts`):** tables `OSHA_NOISE_LIMITS`, `MACHINE_REQUIRED_PPE`;
  functions `maxPermissibleExposureHours`, `assessSafetyCompliance`,
  `reportIncident`, `getAllIncidents`, `getIncidentsBySeverity`,
  `getIncidentsInRange`, `clearIncidentStore`, `generateSafetyBriefing`,
  `calculateNoiseExposure`.
- **Scheduling (`scheduling.ts`):** in-memory booking store —
  `registerResource`, `getResource`, `getAllResources`, `createBooking`,
  `getBooking`, `cancelBooking`, `completeBooking`, `markNoShow`,
  `getBookingsForResource`, `getUpcomingBookings`, `checkAvailability`,
  `detectConflicts`, `calculateUtilization`, `clearSchedulingStore`.

---

## Persistence (`@seshat/database`)

`@seshat/database` provides **Zod row schemas** plus a **declarative migration
system** — it does not depend on Drizzle ORM, Knex, Prisma, or TimescaleDB at
runtime. (The TODOS Phase 36 backlog lists "Prisma/Drizzle migrations" as
planned work; the implemented library is a self-contained schema/migration
description layer.)

### Zod Row Schemas

Each persisted entity has a UUID-validated branded ID schema, a full row schema,
and an insert variant (which omits `createdAt`/`updatedAt` since the database
generates those). The `ProjectStatusSchema` in the database layer is a
**different** type from `@seshat/core`'s `ProjectPhaseSchema`:
`ProjectStatusSchema` is a six-value persistence status (`draft`, `planning`,
`in_progress`, `on_hold`, `completed`, `archived`), while `ProjectPhaseSchema`
is the eleven-phase lifecycle state machine. They are separate concepts.

ID schemas: `ProjectIdSchema`, `MaterialIdSchema`, `ToolIdSchema`,
`DeviceIdSchema`, `RoomIdSchema`, `FloorIdSchema`, `BuildingIdSchema`,
`UserIdSchema`, `CourseIdSchema`, `LessonIdSchema`, `AutomationIdSchema`,
`WorkshopIdSchema`, `DesignIdSchema`.

Row schemas (each yielding a `*Row` inferred type and `*InsertSchema` variant):
`WoodSpeciesSchema`, `MaterialSchema`, `ToolSchema` (with CNC-specific optional
columns), `RoomSchema`, `SmartDeviceSchema`, `SensorReadingSchema`,
`AutomationRuleSchema`, `ProjectSchema`, `CourseSchema`, `LessonSchema`,
`WorkshopSchema`, `DesignSchema`, `BuildingSchema`, `FloorSchema`,
`StudentProgressSchema`, `FengShuiAnalysisSchema`, `VastuAnalysisSchema`,
`SustainabilityAssessmentSchema`.

Supporting object schemas: `DoorOpeningSchema`, `WindowOpeningSchema`,
`CutListSchema`, `BillOfMaterialsSchema`, `ColorPaletteSchema`,
`MoodBoardItemSchema`, `DesignBriefSchema`, `CarbonFootprintSchema`, and the
Feng Shui / Vastu nested schemas.

### Migration Definitions

`migrations.ts` defines a Knex-compatible _description_ layer (not a Knex
dependency): types `ColumnType`, `ColumnDefinition`, `ForeignKeyDefinition`,
`IndexDefinition`, `TableDefinition`, `MigrationDefinition`.

`migration001_initial` creates **18 tables**: `buildings`, `floors`, `rooms`,
`wood_species`, `materials`, `tools`, `smart_devices`, `sensor_readings`,
`automation_rules`, `projects`, `courses`, `lessons`, `student_progress`,
`workshops`, `designs`, `feng_shui_analyses`, `vastu_analyses`,
`sustainability_assessments` — with columns, foreign keys, and indexes fully
specified.

`ALL_MIGRATIONS` is the ordered migration list; `TABLE_NAMES` and `TABLE_COUNT`
are derived; `getTableDefinition(name)` looks one up.
`generateMigrationSQL(migration)` produces `CREATE TABLE` /
`ALTER TABLE … ADD CONSTRAINT` / `CREATE INDEX` SQL strings — it does not
execute anything.

### Seed Data

`seed.ts` ships curated reference data for development and testing:

- `ROOM_TYPES` — 26 room-type info records with typical dimensions, ideal
  lighting, Feng Shui element, and Vastu direction.
- `WOOD_SPECIES_SEEDS` — 25 wood species typed as
  `z.input<WoodSpeciesInsertSchema>`.
- `TOOL_SEEDS` — 20 real woodworking tools.

---

## Validation Rules (Summary)

These rules are enforced at the Zod schema boundary. Violations throw Zod
`ZodError`s that the application layer must handle.

- **Project:** `name` 1–255 chars, `description` ≤2000, IDs must be UUIDs,
  `budget` amounts non-negative integer cents, `currency` exactly 3 chars.
- **Workflow:** step `dependsOn` references must resolve; cycles are rejected by
  `topologicalSort`; step transitions confined to `VALID_STEP_TRANSITIONS`;
  phase transitions confined to `VALID_TRANSITIONS`.
- **Database rows:** wood-species `jankaHardness` 0–5500 lbf, `density` ≤1.5
  g/cm³, shrinkage 0–20% (tangential) / 0–15% (radial); ratings constrained to
  1–10; hex colours validated by regex; scores constrained 0–100; budget `min`
  ≥0 and `max` >0.
- **Sensors:** `validateSensorReading` checks values against `SENSOR_RANGES`;
  anomaly detection uses a configurable z-score threshold.

---

## Acceptance Criteria

- Each of the 11 libraries builds with `npx tsc --noEmit` and ships a Vitest
  suite (`*.test.ts`). Test suites are substantial — for example
  `@seshat/common` has 231 `it()` cases, `@seshat/database` 202,
  `@seshat/smart` 188.
- Domain computations are deterministic pure functions; in-memory stores
  (`ProjectManager`, `DeviceRegistry`, workshop inventory/scheduling stores)
  expose `clear`/`clearStore` helpers for test isolation.
- All numeric reference data (wood properties, joint strengths, carbon factors,
  protocol specs) is sourced from real-world references, not random or
  placeholder values.

---

## Out of Scope (Not Implemented)

The following appear in product narrative or the Phase 36 backlog but have no
implementation in `libs/seshat/`:

- HTTP/REST API gateway, controllers, or routes.
- A domain event bus — `SeshatEventType` / `SeshatEvent` are bare type
  declarations with no publisher or transport.
- AI image generation (Stable Diffusion, ControlNet, depth estimation) — the
  design library produces structured data, not rendered images.
- An ORM-backed runtime database, TimescaleDB hypertables, or pgvector semantic
  search — persistence is Zod schemas plus declarative migration descriptions.
- A live MQTT broker connection — `SmartConfig.mqttBrokerUrl` is a config field
  and `SMART_DWELLING_MQTT` a feature flag, but no MQTT client is implemented.
- Digital-twin runtime — the `DigitalTwin` types are declared but unused.
