# Seshat Domain — Features

> **Seshat** is the Dwelling Arts and Craftsmanship Intelligence Platform of the
> Oshun monorepo. Named after the ancient Egyptian goddess of writing,
> measurement, knowledge, and record-keeping — the divine scribe who measured
> the foundations of temples with a knotted cord and recorded the deeds of
> pharaohs — Seshat provides 11 libraries covering woodworking and craft
> knowledge, AI-powered interior design, digital fabrication pipelines (CNC
> routing, laser cutting, 3D printing), spatial harmony traditions (Feng Shui,
> Vastu Shastra, biophilic design, sacred geometry), smart dwelling IoT
> integration, sustainability and circular-economy design scoring, maker
> education, workshop management, and data persistence. The domain bridges
> millennia of accumulated wisdom about how to build and inhabit sacred space
> with the precision of modern digital fabrication technology.
>
> Seshat ships as 11 TypeScript libraries (`libs/seshat/*`) of deterministic,
> pure-function domain logic plus a few in-memory stores. There is no runtime
> service, API gateway, or event bus; the only runtime dependency is `zod`.

---

Seshat addresses a real problem: the knowledge required to design, build, and
inhabit a well-crafted space is deep, fragmented, and hard to encode in
software. A single furnished room draws on materials science (wood species and
seasonal movement), spatial harmony (Feng Shui sector analysis, Vastu
orientation), colour psychology (emotional impact, accessibility contrast),
digital fabrication (CNC toolpaths, laser cutting parameters), sustainability
(embodied carbon, lifecycle assessment), and safety (ventilation, ergonomics).
Seshat encodes each of these disciplines as domain-specific computational
functions, so any application in the Oshun platform can compose them rather than
reinventing them.

The eleven libraries are consumed directly by application code — there is no
Seshat service to call over HTTP. This section describes what each library
provides.

---

## Common Foundation (`@seshat/common`)

`@seshat/common` is the shared vocabulary of the entire domain. It defines the
types that flow between libraries — a `Room` from `@seshat/core` can be passed
directly into `@seshat/harmony`'s Bagua analysis, and a `WoodSpecies` from
`@seshat/craft` can be passed into `@seshat/fabrication`'s feeds-and-speeds
calculator, without any translation. It also ships the curated constant
databases that every library draws on: wood species properties, joint strength
ratings, Bagua areas, sacred geometry constants, and more.

- **Material Type System**: Strongly typed representations of wood species,
  sheet goods, metals, polymers, textiles, stone, and composite materials. Each
  material type carries physical properties (density, hardness, workability) and
  fabrication compatibility flags (CNC-safe, laser-cuttable, 3D-printable),
  ensuring downstream pipelines receive only materials they can process.
- **Measurement and Unit Conversions**: Consistent handling of imperial and
  metric measurements — essential in woodworking where US tools use inches and
  fractions while European tools use millimetres. Conversion utilities include
  fractional inch representation (e.g., 3/4 inch = 0.75 inch = 19.05 mm) to
  prevent the decimal-to-fraction errors that cause misfit joints.
- **Colour System Types**: Hex, RGB, and HSL colour representations (`RGBColor`,
  `HSLColor`, `DesignColor`, `ColorPalette`) with conversion utilities and WCAG
  contrast calculation, used across the design and harmony subsystems.
- **Geometry Primitives**: 2D types (`Point2D`, `Vector2D`, `Polygon2D`,
  `LineSegment2D`, `BoundingBox2D`, `Dimensions2D`) and 3D types (`Point3D`,
  `Vector3D`, `BoundingBox3D`, `Dimensions3D`, `EulerAngles`, `Transform3D`)
  shared by both the design and fabrication subsystems, avoiding parallel type
  hierarchies.

---

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

`@seshat/core` is the glue layer. It does not own any domain logic itself — that
lives in the specialist libraries — but it provides the infrastructure that all
of them rely on: a project lifecycle state machine, a workflow dependency graph
engine, configuration, structured logging, and feature flags. Applications
typically start here, creating a `Project` and a `Workflow`, then calling the
specialist libraries as the workflow progresses.

- **Project Lifecycle Management**: `ProjectManager` is an in-memory store for
  Seshat projects, tracking category, an eleven-phase lifecycle, priority,
  budget (in integer cents), collaborators, tags, and associated room IDs. Phase
  transitions are governed by an explicit state machine; budget expenditure is
  checked against the allocation. (Project file storage, version history, and
  branching are not implemented.)
- **Workflow DAG Engine**: A dependency-graph engine builds and validates
  multi-step workflows — Kahn's-algorithm cycle detection and topological sort,
  step-readiness checks, blocker resolution, progress computation, and validated
  step-status transitions. `WORKFLOW_TEMPLATES` provides a default phase
  sequence per project category (woodworking, interior design, spatial harmony,
  smart dwelling, fabrication, craft, renovation, workshop setup).
- **Module Registry**: A capability map (`MODULE_CAPABILITIES`) records which
  capabilities each Seshat module exposes. Core references the other libraries
  only as identifiers — it does not import them — so applications compose
  libraries directly.
- **Cross-Cutting Services**: Section-oriented Zod-validated configuration
  (`ConfigManager`), a structured domain error hierarchy (`SeshatError` with
  numeric codes and severities), a self-contained structured logger
  (`SeshatLogger`), and a feature-flag system with deterministic percentage
  rollout (`FeatureFlagManager`, 10 defined flags).

---

## Woodworking and Craft Knowledge (`@seshat/craft`)

`@seshat/craft` is a woodworking knowledge engine: the accumulated expertise of
master craftspeople encoded as deterministic functions. It covers every stage of
a woodworking project — selecting species and joints, computing wood movement,
choosing and sharpening tools, selecting and layering finishes, and planning
cuts and timelines. All functions are pure: they take typed inputs and return
typed results with no side effects.

### Joinery Engineering

Joinery is the art of connecting pieces of wood — the structural and aesthetic
foundation of fine woodworking. The joint type chosen determines the strength,
appearance, and longevity of a piece, and a single poor joint choice can cause
catastrophic failure years after construction.

- **Joinery Catalogues**: Three databases document the craft's joints.
  `JOINT_DATABASE` (in `@seshat/common`) covers 20 Western, universal, and
  Japanese joints with strength ratings, difficulty, tool requirements, and
  applications. `SASHIMONO_JOINTS` is a deep database of Japanese cabinetmaking
  joints (dovetail, sickle scarf, mortise-and-tenon, metal-ring splice, puzzle
  splice, and more) with romanized/Japanese/English names, step-by-step cutting
  sequences, common mistakes, and best use cases. `KUMIKO_PATTERNS` documents
  geometric lattice patterns with strip angles and symbolism.
- **Joint Strength Data**: Each catalogue joint carries a `JointStrength` rating
  — tensile, shear, compression, racking, and overall on a 1–10 scale —
  reflecting real woodworking knowledge of how each joint resists load.
- **Joint Geometry Calculation**: `calculateDovetailLayout` computes pin and
  tail positions for a dovetail; `calculateMortiseTenonSize` sizes a tenon
  (thickness, width, length, optional haunch) for a stock dimension and load
  type; `calculateDrawboreOffset` computes the drawbore pin offset;
  `calculateBoxJoint` lays out finger joints; `calculateKumikoNotch` computes
  kumiko half-lap notch geometry.
- **Joint Selection Wizard**: `selectJoint` scores and ranks joint
  recommendations from `JointSelectionCriteria` — application, load type, skill
  level, available tools, aesthetic requirement, material thickness, and
  reversibility — returning each option with a score, reasoning, and warnings.
  `findSashimonoJoint`, `findKumikoPattern`, `getJointsByTradition`, and
  `getJointsForApplication` support catalogue lookup.

### Materials Science

- **Wood Species Database**: Over 30 domestic and exotic hardwood and softwood
  species with scientifically accurate physical data — Janka hardness (the force
  required to embed a 0.444-inch steel ball to half its diameter into the wood
  face, the industry standard for hardness comparisons), density, grain pattern
  and texture, durability classification, and tangential and radial shrinkage
  coefficients from green to oven-dry moisture content (essential for
  calculating seasonal wood movement). Each species also carries nine
  per-operation workability ratings (sawing, planing, turning, carving, gluing,
  finishing, nailing, screwing, bending). Species lookup, fuzzy key resolution,
  side-by-side comparison, similar-species search, and project-driven
  recommendation are all provided.
- **Wood Movement Calculations**: Wood expands and contracts seasonally as
  ambient humidity changes — a wide cherry tabletop can move 5–8 mm across its
  width from winter to summer in a heated interior. The library calculates
  equilibrium moisture content (Fahrenheit and Celsius variants), predicts
  seasonal movement, analyses current moisture state against an application's
  recommended range, and estimates kiln drying time — the foundation for joinery
  decisions that must accommodate wood movement without splitting.
- **Grain Orientation Analysis**: `analyzeCutOrientation` classifies a board as
  quartersawn, flatsawn, or riftsawn from its ring angle and reports
  dimensional-stability implications and the tangential-to-radial shrinkage
  ratio.
- **Visual Wood Identification**: `identifyWood` produces a ranked species match
  from observed visual characteristics (grain pattern, texture, colour,
  end-grain pore structure) with confidence scores.
- **Bill of Materials Generation**: `generateBOM` turns a parts list into a
  costed bill of materials with board-feet totals, a waste factor, and a
  per-species breakdown.

### Tool Management

- **Tool Database**: `getToolDatabase` exposes a tiered tool catalogue
  (`TOOL_TIERS`); `suggestToolUpgrade` recommends tool acquisitions for a
  maker's situation.
- **Feeds, Speeds & RPM**: `calculateFeedsAndSpeeds` and `calculateOptimalRPM`
  compute recommended spindle speed, feed rate, chip load, depth of cut, and
  stepover for a tool-and-material combination (returned as a `CNCFeedSpeed`),
  enabling consistent, safe results.
- **Sharpening Assessment**: `getSharpnessAssessment` evaluates an edge tool's
  condition (razor-sharp → damaged), recommends an action (strop, hone, sharpen,
  regrind), and reports the primary/secondary bevel angles and a grit
  progression to restore the edge.
- **Sanding Progression**: `calculateSandingProgression` plans a grit sequence
  from a starting to a target grit for a wood type, and `getFinishSandingGrit`
  gives the recommended final grit for a finish.

### Finishing Techniques

- **Finish Database**: `FINISH_DATABASE` is a catalogue of `FinishProfile`
  records covering all major finish categories — penetrating oils, wax, lacquer,
  shellac, oil-based and waterborne polyurethane, conversion varnish, and more —
  each with build type, sheen options, application methods, coat counts, dry and
  cure times, durability/water/heat/UV resistance ratings, food-safety, VOC
  level, recommended surfaces, known incompatibilities, and application tips.
- **Finish Lookup & Filtering**: `getFinish`, `getFinishesByType`,
  `getFoodSafeFinishes`, and `getLowVOCFinishes` query the database by name,
  type, food-safety, or VOC level.
- **Finish Selection (`selectFinish`)**: Given selection criteria — indoor /
  outdoor use, food contact, water-exposure level, desired look, applicator
  skill, time constraint, low-VOC preference, and wood species — returns ranked
  finish recommendations with reasoning.
- **Finish Compatibility (`checkFinishCompatibility`)**: Checks whether two
  finishes can be layered, reporting issues, required preparation steps, and the
  recommended wait time between layers; `getFinishSandingGritByKey` gives the
  recommended sanding grit for a finish.

### Project Planning

- **Project Template Library**: `PROJECT_TEMPLATES` is a curated catalogue of
  woodworking projects with dimensions, recommended species, joints used,
  required skills, and estimated hours. Templates are queryable by name,
  difficulty category, and joint type.
- **Cut List Generation**: `generateCutList` turns a parts specification into a
  cut list, accounting for kerf — standard (0.125") and thin-kerf (0.09375")
  constants are provided — and joinery allowances.
- **Time Estimation**: `estimateProjectTime` produces a phased estimate (design,
  milling, joinery, assembly, finishing hours) with a skill-level multiplier —
  helping makers commit to realistic project timelines.
- **Difficulty Assessment**: `assessDifficulty` scores a project across seven
  weighted factors (joint complexity, joint variety, curved cuts, material
  difficulty, finishing complexity, assembly complexity, precision required) and
  returns an overall difficulty label with an experience recommendation.

---

## Interior Design Intelligence (`@seshat/design`)

`@seshat/design` is a library of deterministic, rule-based design analysis
functions over structured inputs. It computes design intelligence — style
classification, layout scoring, parametric geometry, budget estimation — from
typed data. It does not generate images, run AI/ML models, or call external
services; "visualisation" types describe a scene as structured data
(`RoomVisualization`, `RenderSettings`, `MaterialSurface`, `LightingSource`),
not a rendered picture.

### Style Analysis

- **Rule-Based Style Classification**: `classifyStyle` scores a room's
  attributes (colours, materials, furniture styles, patterns) against
  `STYLE_DATABASE` — a record keyed by all 24 supported `DesignStyle` values
  (modern, contemporary, minimalist, Scandinavian, industrial, mid-century, Art
  Deco, bohemian, traditional, farmhouse, coastal, Japanese, Mediterranean,
  rustic, transitional, eclectic, Art Nouveau, brutalist, tropical, shabby chic,
  Memphis, Bauhaus, Wabi-Sabi, Hygge). Each entry carries era, notable
  designers, signature furniture, elements to avoid, and complementary/clashing
  styles. The classifier produces a weighted composite score and a confidence
  value.
- **Style Consistency Scoring**: `checkStyleConsistency` detects stylistic
  clashes across multiple rooms — a Danish-modern sofa in a Baroque-influenced
  room scores low — identifies the offending rooms, grades the result A–F, and
  suggests transition strategies.
- **Style Interpolation**: `interpolateStyles` blends two aesthetic directions
  at a configurable ratio, expressing the result as a colour palette, material
  list, furniture list, patterns, and key features, with a harmony score.
- **Style Lookup Helpers**: `getStyleInfo`, `getComplementaryStyles`, and
  `getClashingStyles` expose the style database for discovery.

### Parametric and Generative Design

- **Parametric Furniture Definitions**: `createParametricDesign` builds a
  parametric model from dimensional parameters with min/max/step constraints and
  dependency formulas; `validateParametricConstraints` checks a parameter set.
  Changing a parameter updates derived dimensions and component counts.
- **Topology Optimisation**: `optimizeTopology` takes load definitions and
  support fixtures and computes a reduced-material structure, reporting volume
  reduction, strength-to-weight ratio, maximum stress, displacement, and a
  safety factor.
- **Genetic Design Evolution**: `evolveDesign` runs a genetic algorithm over a
  population of `DesignCandidate`s scored on a multi-objective
  `DesignFitnessScore` (cost, aesthetics, strength, sustainability, ergonomics),
  returning the best candidate, a convergence history, and the top candidates.
- **Pattern Generation**: `generateVoronoiPattern` produces organic Voronoi cell
  patterns; `generateShelvingSystem` computes a complete shelving system (shelf
  positions, upright count, pin spacing, material volume, load capacity).

### Floor Plan Intelligence

- **Floor Plan Analysis**: `analyzeFloorPlan` evaluates a set of `Room` objects
  for room proportions (golden-ratio proximity, squareness, usable-area ratio),
  natural light (window-to-floor ratio, estimated lux, daylight autonomy), and
  circulation efficiency, producing graded scores and suggestions.
- **Traffic Flow Analysis**: `analyzeTrafficFlow` identifies circulation paths
  and bottlenecks, classifying paths as primary/secondary/service and reporting
  the circulation percentage.
- **Accessibility & Clearance Checks**: `checkAccessibility` audits a layout
  against ADA-style requirements (path width, turning radius, door clearance,
  reach range); `checkClearances` reports clearance violations between furniture
  items and walls with severity grading.
- **Kitchen Work Triangle**: `analyzeWorkTriangle` measures the sink–stove–
  fridge triangle, flags short-leg / long-leg / traffic-crossing violations, and
  grades efficiency.
- **Furniture Layout Generation**: `generateFurnitureLayout` places furniture to
  balance clearance, visual balance, conversation grouping, focal point, and
  walkability; `LAYOUT_PRESETS` provides predefined arrangements queryable by
  room type, and `recommendLayoutPreset` suggests one.

### Mood Board Analysis

- **Mood Board Analysis**: `analyzeMoodBoard` derives a design brief from a set
  of mood-board inputs — extracted colours with proportions and roles, detected
  styles, materials, patterns, mood descriptors, suggested room types, and a
  coherence score.
- **Palette Extraction**: `extractMoodBoardPalette` produces a dominant
  `ColorPalette`; `generateStyleTags` assigns weighted style tags.
- **Natural-Language Brief Parsing**: `parseDesignBrief` performs keyword-based
  extraction of design intent from free-form text — room type, style keywords
  (via a synonym dictionary), budget range, colour and material preferences,
  furniture mentions, constraints (pet-friendly, child-safe, wheelchair
  accessible, etc.), and aesthetic keywords, with a parse-confidence score.

### Product Discovery

- **Product Matching**: `matchProducts` scores candidate products against a
  search specification (style fit, dimension fit, material fit, colour fit) and
  classifies a budget tier.
- **Budget Estimation**: `estimateRoomBudget` produces a furnishing budget for a
  room and style across line items, with low/high ranges, tax, and delivery
  estimates; `STYLE_MULTIPLIERS` and `QUALITY_MULTIPLIERS` adjust pricing.
  `compareBudgetTiers` and `classifyBudgetTier` support tier analysis.

---

## Design-to-Fabrication Pipeline (`@seshat/fabrication`)

The fabrication library bridges the gap between a designed piece and the
instructions needed to physically produce it on digital fabrication equipment.
It takes dimensional inputs and material specifications and produces the control
programs and parameter sets that drive CNC routers, laser cutters, and 3D
printers — plus the nesting algorithms that minimize material waste.

### CNC Toolpath Generation

CNC (Computer Numerical Control) routers execute precise cutting paths based on
G-code — a numerical control programming language specifying tool movements,
feed rates, spindle speeds, and depths.

- **G-Code Output for 3-Axis CNC Routers**: Generate production-ready G-code for
  the most common workshop configuration — three axes (X left-right, Y
  front-back, Z up-down). The library handles tool offset compensation, safe
  retract heights, and emergency stop positions.
- **Feeds and Speeds Calculation**: The correct combination of spindle RPM and
  feed rate (movement speed) varies dramatically by material and tool type — too
  fast and the tool breaks or burns; too slow and finish quality degrades. The
  library computes optimal SFM (surface feet per minute, the speed at which the
  cutting edge contacts material), chip load (the amount of material each flute
  removes per revolution), and recommends RPM and feed rate for any
  material-tool combination.
- **Toolpath Optimisation**: Minimise air cutting (time spent moving the tool
  when not in material), efficient part nesting on a single sheet, and optimal
  lead-in/lead-out strategies that avoid plunge marks. A 30-minute job can often
  be reduced to 20 minutes with good toolpath planning.
- **Kerf Compensation**: The router bit removes material equal to its diameter.
  The library applies correct inside/outside offset compensation — inside cuts
  (pocket, slot) require the tool centre path to be larger than the finished
  dimension; outside (profile cut) smaller — ensuring parts fit as designed.
- **Machining Time Estimation**: Predict job duration from toolpath length, feed
  rate, number of passes, and tool change time — essential for production
  scheduling and customer quoting.
- **Chip Load & SFM Tables**: `CHIP_LOAD_TABLE` gives a min/max chip-load range
  per workpiece-material family (21 families — hardwoods, softwoods, plywood,
  MDF, aluminium alloys, steels, plastics, composites); `SFM_TABLE` and
  `UNIT_POWER_TABLE` supply surface speeds and unit power. The feeds-and-speeds
  calculator interpolates within these ranges, preventing tool breakage and
  surface-quality problems.

### Laser Cutting Parameters

- **Material-Specific Laser Settings (`calculateLaserSettings`)**: Computes
  power percentage, speed, pass count, kerf, focus offset, and air-assist for a
  material, thickness, machine spec, and operation mode. `MATERIAL_PROFILES`
  stores a per-material reference profile (`LaserMaterial` covers plywood, MDF,
  balsa, hardwood, acrylic, leather, cardboard, cork, fabric, anodized
  aluminium, and more) with reference power/speed/passes, CO₂ and diode kerf
  widths, and safety notes.
- **Operation Modes**: The `LaserOperationMode` type distinguishes full-depth
  cuts from engraving, scoring, and marking; settings are computed per mode.
- **Pass Count for Thick Materials**: The settings calculator increases pass
  count for materials beyond a single-pass thickness limit.
- **Kerf Compensation**: `MATERIAL_PROFILES` records per-material kerf width;
  `calculateLaserSettings` reports the kerf so a consumer can compensate
  precision-fit joints. `generateLaserToolpath` orders cuts (interior before
  exterior); `calculateLaserMaterialUsage` reports sheet utilisation and waste.

### 3D Printing Specifications

- **Print Settings Calculation (`calculatePrintSettings`)**: From a model mesh,
  print material, and quality preset, computes a `PrintJobSettings` — layer
  height, wall count, top/bottom layers, infill percentage and pattern, print
  and travel speeds, nozzle and bed temperatures, support strategy, adhesion
  type, retraction, and fan speed. `LAYER_HEIGHTS` and `DEFAULT_INFILL` provide
  presets.
- **Material Database**: `MATERIAL_DB` profiles the supported `PrintMaterial`
  values — PLA, ABS, PETG, nylon, TPU, resin, wood-fill, carbon-fiber, and
  metal-fill — with their printing characteristics.
- **Print Time Estimation (`estimatePrintTime`)**: Estimates print duration as a
  breakdown of extrusion, travel, and layer-change time from the model and
  settings, reporting layer count and total path lengths.
- **Material Usage Estimation (`estimatePrintMaterialUsage`)**: Computes the
  volume of model fill, infill, walls, supports, and adhesion, with filament
  length, weight in grams, an estimated cost, and an applied waste factor.

### 2D Nesting and Sheet Optimisation

Material sheets are expensive. The nesting algorithms maximise how many parts
fit on each sheet, and enforce orientation constraints that preserve grain
direction for wood and composite materials.

- **Bin-Packing (`nestParts`)**: Rectangular part nesting using a
  bottom-left-fill algorithm with multi-rotation support and kerf accounting,
  packing parts across as many sheets as needed to maximise material
  utilisation.
- **Grain Direction Constraint**: A `NestingPart` flagged `grainSensitive` is
  restricted to grain-preserving rotations (0° and 180°), so wood and composite
  parts stay correctly oriented relative to the sheet's grain.
- **Cut Sequence Optimisation (`optimizeCutSequence`)**: Orders cuts so interior
  cuts (holes, pockets) precede the exterior profile — a large outer profile cut
  removing structural support before interior parts are complete would cause
  parts to shift mid-job.
- **Sheet Estimation & Waste Reporting**: `estimateSheetsRequired` predicts the
  number of sheets needed; `calculateWasteWithKerf` and the `NestingResult`
  report per-sheet and overall utilisation and waste percentages including the
  kerf applied.

---

## Spatial Harmony Engine (`@seshat/harmony`)

The harmony library implements traditional spatial wisdom traditions as
computational models, enabling systematic application of principles that have
guided human habitation for millennia. It covers seven traditions — Feng Shui,
Vastu Shastra, biophilic design, sacred geometry, colour psychology, Wabi-Sabi,
and Hygge — and synthesizes them into a unified, weighted score that surfaces
conflicts and agreements between traditions.

### Feng Shui Analysis

Feng Shui (literally "wind-water" in Chinese) is a 3,000-year-old tradition of
arranging the built environment to harmonise the flow of qi (life energy)
through a space. The tradition distinguishes between Form School (physical
landscape and building orientation) and Compass School (directional calculations
based on the occupant's personal data).

- **Bagua Map Overlay**: The Bagua (eight trigrams from the I Ching) maps nine
  life areas — Wealth/Prosperity (southeast), Fame/Reputation (south),
  Love/Marriage (southwest), Family/Health (east), Centre/Wellbeing (centre),
  Creativity/Children (west), Knowledge/Self-Cultivation (northeast), Career
  (north), Helpful People/Travel (northwest) — onto the floor plan as a 3×3 grid
  aligned with either the compass (Classical Feng Shui) or the front door
  (BTB/Western Feng Shui). The library implements both alignment methods with
  explicit notation of which school is being applied.
- **Flying Stars Chart Generation (Xuan Kong)**: `calculateFlyingStarChart`
  casts the natal chart of a building from its 20-year period and facing
  direction — a 9-palace grid where each palace carries a period, mountain, and
  water star with a combined interpretation. `getPeriodForYear` maps a year to
  its period; `calculateAnnualStar` computes the annual visiting star for an
  optional annual overlay. (Monthly star overlays are not implemented.)
- **Kua Number Calculator**: Each person has a personal Kua number calculated
  from birth year and biological sex. The Kua number assigns four favourable
  directions (Sheng Chi — growth; Tien Yi — health; Nien Yen — relationships; Fu
  Wei — stability) and four unfavourable directions (Ho Hai — mishaps; Wu Gui —
  five ghosts; Lui Sha — six killings; Chueh Ming — total loss). Sleeping with
  the head in a favourable direction and orienting the desk toward a favourable
  direction are key Kua-based recommendations.
- **Chi Flow Simulation**: `simulateChiFlow` models qi flow with a simplified
  velocity-field grid computed over a room's polygon — chi enters through doors
  and windows, and the model identifies stagnation zones (dead chi), sha-chi
  sources (rushing chi, poison arrows), and entry/exit points, classifying the
  overall flow as meandering, moderate, rushing, or stagnant and proposing
  remedies. (This is a heuristic flow model, not a full CFD solver.)
- **Five Elements (Wu Xing) Analysis**: The five elemental energies — Wood
  (growth; colours: green, blue), Fire (passion; colours: red, orange, purple),
  Earth (stability; colours: yellow, brown), Metal (precision; colours: white,
  grey), Water (wisdom; colours: black, deep blue) — interact in generating
  cycles (Wood feeds Fire, Fire creates Earth/ash, Earth produces Metal, Metal
  holds Water, Water nourishes Wood) and controlling cycles (Wood depletes
  Earth, Earth absorbs Water, Water quenches Fire, Fire melts Metal, Metal cuts
  Wood). Rooms are assessed for elemental balance, with recommendations for
  restoring harmony through colour, shape, material, and object selection.
- **Poison Arrow (Sha Chi) Detection**: Sharp corners, exposed overhead beams,
  T-junction roads pointing at a building, and stairways aligned with entrance
  doors all direct cutting energy toward specific positions. The algorithm
  identifies these configurations in the floor plan and suggests remedies.
- **Room-Specific Analysis**: Bedroom analysis focuses on bed placement in the
  "command position" (visible to the door but not directly in line with it);
  kitchen analysis focuses on stove position and avoiding stove facing the door;
  home office analysis optimises for career and creativity sectors.

### Vastu Shastra Analysis

Vastu Shastra (literally "science of dwelling" in Sanskrit) is the ancient
Indian science of architecture, established in the Vedic period, that prescribes
rules for building design, space organisation, and compass orientation to
harmonise a structure with natural forces and cosmic energies.

- **Purusha Mandala Grid Overlay**: The Purusha Mandala is a sacred geometric
  diagram — typically a 9×9 grid (81 squares) — representing the cosmic being
  Vastu Purusha whose body is mapped across the property. Different grid zones
  are presided over by different devas (divine forces), prescribing appropriate
  room functions for each zone: northeast (Ishanya) — sacred space, water
  features, and study; southeast (Agneya) — fire and kitchen; southwest
  (Nairiti) — master bedroom and heavy storage; northwest (Vayavya) — guest
  rooms and vehicles.
- **Cardinal Direction Room Placement**: Vastu prescribes specific rooms for
  specific compass directions — the main entrance should face north or east; the
  kitchen should be in the southeast (fire quadrant); the master bedroom in the
  southwest; bathrooms in the northwest; pooja (prayer) room in the northeast.
  The library scores any floor plan against these prescriptions.
- **Element and Deity Zone Compliance Scoring**: Score any floor plan against
  Vastu's zone prescriptions — each room's current function is compared against
  the Vastu-prescribed function for that zone, producing a compliance score and
  prioritised list of modifications ordered by impact.
- **Entrance Orientation Assessment**: The direction the main door faces, the
  direction it swings open, and the features visible immediately upon entry are
  all significant in Vastu. The library scores entrance orientation and
  identifies common violations (toilet visible from entrance, staircase
  immediately opposite the entry, main door in the southwest).

### Biophilic Design

Biophilic design is grounded in the biophilia hypothesis — humans evolved in
nature and retain an innate affinity for natural environments. Biophilic design
incorporates natural patterns, materials, and sensory stimuli to reduce
physiological stress, improve cognitive performance, and increase occupant
wellbeing.

- **14 Biophilic Design Patterns Assessment**: `assessBiophilicDesign` scores a
  space against the 14 patterns of biophilic design (the Terrapin Bright Green
  framework) — visual and non-visual connection with nature, non-rhythmic
  sensory stimuli, thermal and airflow variability, presence of water, dynamic
  and diffuse light, connection with natural systems, biomorphic forms and
  patterns, material connection with nature, complexity and order, prospect,
  refuge, mystery, and risk/peril. Each pattern carries stress-reduction and
  cognitive-performance contribution scores (from `BIOPHILIC_PATTERNS`), and the
  result groups patterns into the three categories (nature in the space, natural
  analogues, nature of the space).
- **Plant Recommendation Engine**: `recommendPlants` recommends indoor plants
  filtered by light requirement, maintenance tolerance, air-purification
  priority, and pet-safety, drawing on a built-in plant database
  (`PlantRecommendation` records with scientific names, watering needs, light
  tolerance, NASA Clean Air Study purification data, and Feng Shui element).
- **Air Quality Consideration**: Plant recommendations carry NASA Clean Air
  Study purification ratings and the specific pollutants each species removes
  (benzene, formaldehyde, trichloroethylene), so air-quality priority feeds
  directly into the recommendation.

### Sacred Geometry

Sacred geometry applies geometric ratios found throughout nature to human
environments — these proportions appear in phyllotaxis (leaf arrangement), shell
growth spirals, and the architecture of sacred buildings across unrelated
ancient cultures.

- **Proportion Analysis**: `analyzeProportions` evaluates dimensions against the
  golden ratio and Fibonacci ratios, reporting golden-ratio deviation, the
  nearest Fibonacci ratio match, harmonic-proportion comparisons, an overall
  proportion score, and recommendations. `isGoldenRatio` and `isFibonacciRatio`
  are direct ratio tests.
- **Golden-Ratio Construction Helpers**: `goldenDivision` splits a length at the
  golden section; `goldenRectangleSubdivisions` produces a recursive
  golden-rectangle subdivision sequence.
- **Sacred-Geometry Coordinate Generation**: `generateGoldenSpiralPoints`,
  `generateVesicaPiscis`, and `generateFlowerOfLife` compute the point sets and
  circle centres for those figures, returning coordinate data (not rendered SVG
  or DXF files) that a consumer can draw or export.

### Colour Psychology

- **60-30-10 Colour Rule**: The dominant rule in interior colour composition —
  60% dominant colour (typically walls), 30% secondary colour (typically large
  furniture), 10% accent colour (cushions, throws, artwork, accessories). The
  library validates any proposed colour scheme against this rule and suggests
  adjustments.
- **Emotional Impact Scoring**: Empirical colour psychology research mapped to
  room function recommendations — blue and green (calming, productive —
  recommended for offices and bedrooms), yellow (stimulating and energising —
  recommended for kitchens and playrooms), red (increases appetite and
  excitement — effective for dining rooms), purple (creative and contemplative),
  white (spacious, clean), and warm neutrals (welcoming, grounded).
- **WCAG Contrast for Interior Signage**: Accessibility compliance — wayfinding
  signs, room labels, and safety notices must meet WCAG 2.1 contrast ratios
  (4.5:1 for normal text, 3:1 for large text) to be readable by people with low
  vision.
- **Colour Temperature by Room Activity**: Warm light (2700–3000 K, incandescent
  appearance) for relaxation spaces; neutral white (3500–4000 K) for kitchens
  and offices; cool daylight (5000–6500 K) for studios and retail displays —
  recommendations aligned with circadian rhythm support and functional lighting
  needs.

### Multi-Tradition Synthesis

When a space is analysed through multiple harmony traditions, they will
sometimes agree (both Feng Shui and Vastu recommend unobstructed entrance areas)
and sometimes conflict (Feng Shui's kitchen placement may differ from Vastu's).
The synthesis layer resolves these intelligently rather than leaving the
contradiction to the application developer.

- **Unified Harmony Report**: `synthesizeHarmony` combines per-tradition scores
  across the seven supported `HarmonyTradition` values (Feng Shui, Vastu
  Shastra, Wabi-Sabi, Hygge, biophilic, sacred geometry, colour psychology) into
  a weighted composite `HarmonySynthesis` with an A–F grade and prioritised,
  de-duplicated recommendations.
- **Conflict & Agreement Detection**: When traditions contradict, the synthesis
  surfaces each `TraditionConflict` with both recommendations and a resolution;
  it also records `TraditionAgreement`s where traditions reinforce each other.
- **Configurable Tradition Weights**: A `SynthesisConfig` selects which
  traditions to include and supplies optional per-tradition weights (equal
  weights are used by default), plus a recommendation score threshold.

---

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

`@seshat/smart` models the connected home as a coherent computational system. It
manages the catalogue of IoT devices, processes the continuous stream of sensor
data those devices produce, evaluates automation rules against that data, and
computes wellness scores from environmental readings. All state is held in
in-memory stores backed by plain TypeScript `Map`s; the application layer is
responsible for persisting device registrations and automation rules to a
database.

### IoT Device Management

- **Device Registry**: `DeviceRegistry` catalogues smart-home devices with
  manufacturer, model, communication protocol, firmware version (with firmware
  history), room assignment, and capabilities. Devices can be grouped by room,
  function, or zone (`groupDevices`, `addDeviceToGroup`), and
  `getDevicesNeedingAttention` / `checkDeviceHealth` surface devices with low
  battery, poor signal, or stale firmware.
- **Protocol Support**: Zigbee (mesh network, long range, battery-efficient —
  the dominant protocol for smart lighting and sensors), Z-Wave (similar to
  Zigbee on a different radio frequency, excellent reliability), Matter (the new
  unified standard backed by Apple, Google, Amazon, and Samsung — enables
  cross-brand interoperability without vendor lock-in), Thread (the IP-based
  networking layer that Matter uses), Wi-Fi (high bandwidth — cameras,
  displays), and Bluetooth (short range — locks, presence sensors, wearables).
- **Signal Quality Assessment**: `assessSignalQuality` classifies a device's
  signal strength (dBm) into excellent/good/fair/poor/critical bands, and
  `estimateBatteryDays` projects remaining battery life from a drain rate.
- **Capability Detection**: `detectCapabilities` derives a device's supported
  features from its type and protocol; `validateProtocol` and
  `validateProtocolConfig` check protocol settings.

### Sensor Data Processing

- **Real-Time Sensor Ingestion**: Continuous ingestion of sensor readings —
  temperature (°C/°F), humidity (relative humidity %), CO₂ (ppm — the primary
  indoor air quality indicator, with 1,000 ppm indicating poor ventilation), VOC
  (ppb — volatile organic compounds from off-gassing materials and cleaning
  products), PM2.5 (fine particle count — relevant for wildfire smoke and
  cooking particulates), PM10, lux (light intensity), PIR motion, door/window
  contact state, and energy consumption (watts).
- **Unit Normalisation**: Different sensors report the same physical quantity in
  different units or with different calibration offsets. The library normalises
  all readings to standard units with configurable calibration correction
  factors.
- **Anomaly Detection**: `detectAnomaly` flags readings using a z-score test
  against a configurable threshold, classifying severity (mild/moderate/severe)
  and direction (above/below). `evaluateThresholds` raises alerts when readings
  cross configured `SensorThreshold`s. Moving-average and exponential-moving-
  average helpers smooth a reading series.
- **Sensor Fusion**: `fuseSensorData` combines multiple co-located sensor
  sources into a single higher-confidence value (weighted average), reporting a
  confidence score and each source's contribution.

### Home Automation

- **Scene Management**: `SceneManager` defines, stores, and activates named
  multi-device scenes (`createScene`, `updateScene`, `activateScene`,
  `listScenesByRoom`, `listScenesByTag`) — a "Movie Night" scene dims lights,
  closes blinds, and sets the thermostat. `activateScene` applies each device
  state and reports a per-device `ActionExecutionResult`.
- **Rule Engine**: `AutomationEngine` registers and evaluates automation rules.
  Triggers (`AutomationTriggerExtended`) cover time/cron, sensor thresholds with
  hysteresis and duration, device state, and geofence; rules support `and`/`or`
  trigger logic, conditions, priorities, cooldowns, and schedules. Pure
  evaluators — `evaluateTrigger`, `evaluateCompoundTriggers`,
  `evaluateCondition`, `evaluateRule`, `evaluateRules` — and async executors
  (`executeAction`, `executeRuleActions`) drive rule processing.
- **Circadian Lighting**: `calculateCircadianLighting` recommends a colour
  temperature and brightness for the time of day across phases (wake-up,
  morning, midday, afternoon, evening, night, sleep) — bright cool light in the
  morning, warm dim light in the evening to support natural melatonin rise.

### Wellness Monitoring

- **Indoor Air Quality Scoring**: `assessAirQuality` produces an air-quality
  score and CO₂ rating (excellent → hazardous) from CO₂ and optional VOC and
  PM2.5 readings, with recommendations when quality is poor.
- **Environmental Comfort**: `assessEnvironmentalComfort` aggregates thermal,
  air-quality, humidity, and noise sub-assessments (`assessHumidityComfort`,
  `assessNoiseComfort`) into an overall comfort rating with recommendations.
- **Sleep Quality Assessment**: `assessSleepQuality` scores a night from bed-
  sensor data (movement frequency, temperature stability, restless periods) and
  estimates deep-sleep percentage with coaching recommendations.
- **Ergonomic & Posture Analysis**: `analyzePosture`,
  `calculateWeightDistribution`, `calculateLeanAngle`, and
  `trackSittingDuration` evaluate seated posture from pressure-map data and
  track sitting/standing time, flagging when a break is due.
- **Simplified Thermal Comfort**: `assessThermalComfort` derives a PMV-like
  thermal-sensation estimate (cold → hot) from ambient temperature alone — a
  simplified model; full ASHRAE 55 PMV inputs (radiant temperature, air
  velocity, humidity, clothing, metabolic rate) are not modelled.
- **Wellness Report**: `WellnessReport` composes sitting time, posture, sleep,
  environmental comfort, and circadian-lighting results into an overall wellness
  score with top recommendations.

---

## Sustainability and Circular Design (`@seshat/sustainability`)

`@seshat/sustainability` provides the environmental intelligence layer for
Seshat. It implements formal LCA (Life Cycle Assessment) methodology following
ISO 14040/14044, computes embodied carbon from peer-reviewed emission factors,
scores designs against circular-economy principles, and tracks sustainability
certifications. The numeric reference data (carbon factors, transport emission
factors, grid emission intensities) is sourced from established databases — ICE
(University of Bath), EPA, and Ecoinvent.

### Carbon Footprint Calculation

- **Material Carbon Calculation**: `calculateMaterialCarbon` computes embodied
  carbon from `MATERIAL_CARBON_FACTORS` — per-material kgCO₂e/kg values sourced
  from the ICE database (University of Bath), EPA, and Ecoinvent (kiln-dried
  hardwood ≈0.46, virgin steel ≈1.95, primary aluminium ≈9.16, with recycled
  variants substantially lower). `calculateTotalCarbon` aggregates material,
  transport, manufacturing, use-phase, maintenance, and end-of-life carbon —
  including a wood sequestration credit — into a `CarbonBreakdown`.
- **Transportation Emissions**: `calculateTransportCarbon` computes transport
  carbon from `TRANSPORT_EMISSION_FACTORS` for road, rail, sea, and air, with
  configurable load factors (`DEFAULT_LOAD_FACTORS`) and an optional return
  trip; `calculateSupplyChainCarbon` sums multiple transport legs.
- **Manufacturing & End-of-Life Carbon**: `calculateManufacturingCarbon` uses
  per-process power draw (`PROCESS_POWER_KW`) and grid emission factors
  (`GRID_EMISSION_FACTORS`); `calculateEndOfLifeCarbon` accounts for disposal
  methods and recycling credits (`END_OF_LIFE_FACTORS`).
- **Carbon Payback & Sequestration**: `carbonPaybackPeriod` computes how long a
  lower-emission replacement takes to pay back its upfront embodied-carbon
  difference. Carbon sequestration credits for wood are modelled explicitly
  (`WOOD_CARBON_SEQUESTRATION_PER_KG`, with eligible and partial-sequestration
  material sets), so the `CarbonBreakdown` reports a net total including stored
  carbon. `compareMaterialCarbon` and `describeMaterialCarbon` support
  material-substitution decisions.

### Life Cycle Assessment (LCA)

A formal LCA evaluates environmental impact across the entire product lifecycle
— from raw material in the ground to end-of-life disposal — following ISO
14040/14044 standards.

- **Full LCA (`performLCA`)**: Follows ISO 14040/14044 methodology, computing a
  `LCAResult` with per-stage impacts (extraction, manufacturing, transport, use,
  maintenance, end-of-life), a full carbon breakdown, total energy, water, and
  waste, recyclability and biodegradability percentages, hotspots, improvement
  suggestions, and an overall sustainability rating.
- **Impact Categories**: The `ImpactCategory` type names eight ISO 14044
  categories — global warming potential, acidification, eutrophication, ozone
  depletion, photochemical ozone creation, abiotic depletion, water footprint,
  and land use.
- **Hotspot & Improvement Analysis**: `identifyHotspots` lists life-cycle stages
  contributing more than a quarter of total impact; `suggestImprovements`
  proposes stage-specific improvements with estimated reductions, difficulty,
  and cost impact.
- **Comparative LCA (`compareProducts`)**: Side-by-side LCA for two products,
  reporting carbon/energy/water differences, per-stage comparisons, and a
  preferred product — answering "which version of this design is more
  sustainable?"

### Circular Design Scoring

Circular economy principles extend product lifetimes through design for
disassembly, repairability, and material recovery — minimising waste and
resource consumption.

- **Circularity Scoring (`assessCircularity`)**: Produces a
  `CircularDesignScore` with five subscore groups — durability, repairability,
  recyclability, reusability, and material efficiency — plus an overall 0–100
  score and a sustainability rating. Recyclability depends on mono-material
  design, separable components, and marked materials; a traditional dovetailed
  drawer box scores higher than a glued, stapled one. `quickCircularityScore`
  gives a fast estimate.
- **Repairability Index (`assessRepairability`)**: Computes a repairability
  score on the French repairability-index model — documentation, disassembly
  ease, spare-parts availability, spare-parts price ratio, and product-specific
  features.
- **Design for Disassembly (`designForDisassembly`)**: Produces prioritised
  `DfDRecommendation`s — replace adhesive joints with accessible mechanical
  fasteners, minimise fastener variety, mark materials per ISO 11469 — by
  analysing a product's `JointInfo` fasteners and material markings.

### Certification Support

- **Certification Record Tracking**: `createCertificationRecord` and
  `trackCertification` manage certification records (across the ten supported
  `CertificationType` values — FSC, PEFC, Cradle to Cradle, GREENGUARD, LEED,
  BREEAM, WELL, Living Building Challenge, ENERGY STAR, Blue Angel) with status,
  issue/expiry dates, and scope. `isCertificationValid`, `daysUntilExpiry`,
  `filterCertificationsByStatus`, and `getCertificationsExpiringSoon` support
  lifecycle management.
- **FSC Chain-of-Custody Validation**: `validateChainOfCustody` checks that a
  product's certified content meets its FSC claim threshold (FSC 100%, FSC Mix,
  FSC Recycled, FSC Controlled), reconciling input and output volumes and
  reporting validation errors. `determineMaxFSCClaim` computes the strongest
  claim a given set of inputs supports. (Validation is internal; there is no
  external FSC database lookup.)
- **LEED Contribution Assessment**: `assessLEEDContribution` models which LEED
  credits a project's material choices earn, using `LEED_LEVELS`,
  `LEED_CATEGORY_MAX_POINTS`, and `LEED_VOC_LIMITS`, and returns a
  `LEEDAssessment` with a certification level.
- **Material Sustainability & Reporting**: `assessMaterialSustainability`
  profiles a material's carbon intensity, embodied energy, water use, and
  recyclability; `generateSustainabilityReport` composes LCA, circular-design,
  certification, and supply-chain results into a single report.

> Waste-audit data structures (`WasteAudit`, `WasteEntry`, `WasteStream`,
> `WasteStreamSummary`, `WasteDiversionMethod`) are defined as types, but no
> waste-audit computation function is implemented. Declare-label / Red-List
> chemical screening is not implemented.

---

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

`@seshat/academy` is the learning platform layer of Seshat. It encodes the
curriculum of maker education — skill assessment rubrics, course prerequisites,
certification programs, and mentor–apprentice matching — as computable data
structures and functions. The goal is to give any application the ability to
assess where a student is, generate a personalised learning path to where they
want to be, and certify when they have arrived.

### Skill Assessment

- **Multi-Dimensional Skill Matrix**: Skill is tracked across a large set of
  named sub-skills (`CraftSubSkill`) grouped under 16 craft domains
  (`CraftDomain` — woodworking, joinery, turning, carving, furniture making,
  cabinet making, interior design, spatial harmony, finishing, upholstery,
  digital fabrication, sustainability, restoration, timber framing, marquetry,
  luthiery). Each sub-skill is independently scored, so a maker can be advanced
  at joinery but a beginner at finishing. `buildSkillProfile` aggregates
  per-domain levels into a `StudentSkillProfile`.
- **Rubric-Based Assessment**: `executeAssessment` scores a practical skill test
  against a structured rubric (`ASSESSMENT_RUBRICS`) — weighted criteria with
  level descriptors, a passing score, time limit, and required tools/materials —
  producing per-criterion feedback, a total weighted score, a pass/fail result,
  and a resulting skill level. `scoreToSkillLevel`, `skillLevelToScore`, and
  `meetsSkillRequirement` map between numeric scores and qualitative levels.
- **Skill Gap Identification**: `identifySkillGaps` compares a student's current
  proficiencies against target requirements and reports which skills fall short
  and by how much.
- **Progress Tracking**: Per-domain skill records enable visualising improvement
  over time.

### Learning Path Generation

- **Personalised Learning Paths**: `generateLearningPath` builds a sequenced
  curriculum of course nodes from a learner's goal and skill gaps, drawing on
  `COURSE_CATALOG`, with per-node estimated hours and dependency ordering.
- **Prerequisite Sequencing**: `checkPrerequisites`, `resolvePrerequisiteChain`,
  and `getPrerequisiteTree` ensure foundational courses precede advanced ones —
  you cannot learn to cut a dovetail by hand until you can sharpen a chisel to a
  razor edge.
- **Course Discovery**: `findCoursesForSkills` locates courses that teach a
  desired set of sub-skills.
- **Time-to-Competency Estimates**: `estimateProgressionHours` gives realistic
  hour estimates for advancing between skill levels; `TechniqueEntry` records in
  the knowledge base carry per-technique practice-hours-to-competency.

### Certification System

- **Certification Programs**: `CERTIFICATION_PROGRAMS` defines programs per
  craft domain, each with required sub-skill proficiencies, required courses,
  minimum practice hours, minimum completed projects, portfolio requirements, an
  exam rubric, a passing exam score, and a validity period.
- **Eligibility Checking**: `checkCertificationEligibility` reports whether a
  student meets every program requirement, with an overall progress percentage
  and an estimate of remaining hours to eligibility.
- **Credential Issuance**: `issueCertification` validates the exam score and
  issues a `CertificationRecord` with a generated certificate number and an
  expiry derived from the program's validity period. `getRenewalStatus` and
  `isCertificationValid` track renewal; `getCertificationPathForDomain` lists
  the certification ladder for a domain.

### Mentorship Matching

- **Mentor & Apprentice Profiles**: `MentorProfile` captures expert sub-skills,
  certifications, teaching style, communication preferences, availability time
  slots, capacity, and ratings; `ApprenticeProfile` captures a student's skill
  profile, goals, learning style, and preferences.
- **Multi-Dimensional Matching**: `scoreMentorMatch` produces a compatibility
  score across eight weighted dimensions — skill alignment, schedule
  compatibility, communication match, teaching/learning style compatibility,
  domain relevance, logistical fit, mentor availability, and reputation
  (`DEFAULT_MATCHING_WEIGHTS` sets the weights; each dimension has a dedicated
  scoring function). `findBestMentors` ranks candidate mentors for an
  apprentice, and `validatePairingViability` checks a proposed pairing.

---

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

`@seshat/workshop` models the physical workshop or makerspace as a managed
resource. It handles the layout and safety of the physical space, the inventory
of tools and materials, the scheduling of shared resources, and the engineering
of dust collection and electrical systems. Like the other Seshat libraries that
manage state, it uses in-memory stores; durable persistence is the caller's
responsibility.

### Layout Design

- **Workshop Floor Plan Optimisation**: Model a workshop space and arrange tools
  for optimal workflow — the "wood preparation to joinery to assembly to
  finishing" workflow should flow in one direction without backtracking. The
  library uses graph-based workflow optimisation to suggest layouts that
  minimise tool-to-tool travel distances for the most common operations.
- **Clearance Validation**: `MACHINE_CLEARANCES` records the
  infeed/outfeed/left/right clearance each machine category needs;
  `getMachineClearanceEnvelope` computes a machine's required envelope and
  `validateClearances` reports clearance violations across a layout, graded as
  warning or violation.
- **Layout Analysis**: `designWorkshopLayout` produces a `LayoutAnalysis` with
  an overall score, clearance violations, workflow analysis, space utilisation,
  natural-light coverage, and a safety score, plus recommendations.

### Tool & Material Inventory Management

- **Tool Catalogue with Maintenance History**: An in-memory tool store
  (`addTool`, `getTool`, `updateTool`, `removeTool`, `getAllTools`,
  `getToolsByCondition`) tracks shop tools — purchase date, price, condition,
  ownership status, location, and a maintenance history. `recordMaintenance`
  appends `MaintenanceRecord` entries (blade changes, alignment, bearing
  replacement, etc.).
- **Maintenance Scheduling**: `scheduleMaintenance` produces a
  `MaintenanceSchedule` with a next-due date and priority; `checkMaintenanceDue`
  surfaces tools that have reached or passed their maintenance interval.
- **Material Stock Tracking**: A material store (`trackMaterialStock`,
  `getMaterial`, `getMaterialsByType`, `deductMaterial`,
  `getMaterialUsageHistory`) records on-hand quantities and usage;
  `estimateReorderPoint` and `findLowStockMaterials` flag stock that has dropped
  below its reorder point. `calculateBoardFeetFromDimensions` converts lumber
  dimensions to board feet.
- **Inventory Reporting**: `generateInventoryReport` summarises tools by
  condition, tools needing maintenance, materials by type, total inventory
  value, low-stock items, and recent maintenance cost.

### Safety Systems

- **Per-Machine Safety Briefings**: `generateSafetyBriefing` produces a
  `MachineSafetyBriefing` for a machine category — required PPE, a pre-use
  checklist, operating hazards (kickback, entanglement, dust inhalation),
  emergency procedures, prohibited actions, and whether hearing protection is
  mandatory. `MACHINE_REQUIRED_PPE` maps each machine category to its mandatory
  PPE.
- **Safety Compliance Assessment**: `assessSafetyCompliance` scores a workshop
  layout's safety systems (emergency stops, fire suppression, first-aid and
  eye-wash stations, aisle widths, evacuation plan) and returns graded checks,
  critical issues, and warnings.
- **Incident Log and Near-Miss Tracking**: An in-memory incident store
  (`reportIncident`, `getAllIncidents`, `getIncidentsBySeverity`,
  `getIncidentsInRange`) records injuries, near-misses, and property damage —
  classified across 14 incident categories and five severity levels (including
  `near_miss`). Near-miss tracking matters because near-misses precede serious
  injuries (Heinrich's Triangle).
- **Noise Exposure Calculation**: `calculateNoiseExposure` computes an
  OSHA-style time-weighted average and noise dose from per-machine usage
  (`OSHA_NOISE_LIMITS`, `maxPermissibleExposureHours`), reporting whether
  hearing protection is required.

### Scheduling and Booking

- **Shared Resource Booking**: An in-memory booking system (`registerResource`,
  `createBooking`, `getBooking`, `cancelBooking`, `completeBooking`,
  `markNoShow`) reserves machines, zones, workbenches, and classrooms for time
  slots. `createBooking` enforces resource availability windows, min/max
  durations, and a safety-orientation prerequisite.
- **Availability & Conflict Detection**: `checkAvailability` finds open slots;
  `detectConflicts` reports overlapping bookings on the same resource with the
  overlap duration.
- **Utilisation Reporting**: `calculateUtilization` computes a resource's
  utilisation percentage, booking count, average booking duration, and peak
  day/hour over a period — informing purchasing and scheduling decisions.

### Dust Collection Planning

Dust is the hidden hazard in woodworking: fine wood dust (especially MDF and
finishing dust) contains respirable particles below OSHA permissible exposure
limits, and accumulated dust is a fire and explosion risk. The dust collection
functions encode the engineering required to size a safe system.

- **CFM Requirements Calculation**: Every stationary power tool has a minimum
  air volume (CFM — cubic feet per minute) requirement for effective dust
  collection. A 12-inch planer requires approximately 800 CFM; a 10-inch table
  saw approximately 450 CFM. The library calculates total simultaneous CFM
  requirement and recommends dust collector capacity.
- **Duct Sizing and Velocity Calculations**: Proper duct design maintains
  3,500–4,000 FPM (feet per minute) minimum transport velocity — below this
  velocity, dust settles in horizontal ducts creating fire hazards. The library
  sizes main trunk ducts and branch ducts to maintain target velocity at the
  required flow rate.
- **Filtration Stage Design**: Three-stage filtration design — cyclone
  pre-separator (removes more than 98% of heavy chips before the filter,
  extending filter life dramatically), bag filter (collects fine dust), and HEPA
  final stage (captures particles down to 0.3 microns — required for MDF and
  finishing dust which contain respirable particles below OSHA permissible
  exposure limits).

### Electrical Planning

- **Circuit Load & Requirements**: `calculateElectricalRequirements` analyses a
  workshop's machine loads, voltages, and circuits — computing total connected
  load, per-circuit load percentages, and whether any circuit is overloaded
  (`MACHINE_AMPERAGE` provides per-machine draw). It helps prevent the common
  mistake of running too many tools on one circuit.
- **Wire & Breaker Sizing**: `recommendWireGauge` selects an AWG wire gauge for
  an amperage and run length; `calculateVoltageDrop` computes the voltage-drop
  percentage over a run; `recommendBreakerType` chooses a standard/GFCI/AFCI
  breaker for a circuit.

---

## Data Persistence (`@seshat/database`)

`@seshat/database` is a schema-and-migration **description** layer, not a
database client. It depends only on `zod`; it opens no connection and uses no
ORM (Drizzle, Knex, or Prisma) at runtime. This library exists to provide a
single source of truth for what the Seshat database schema looks like, and to
generate the SQL needed to create it, without tying the domain libraries to any
particular database driver or ORM.

The deliberate boundary here is that `@seshat/database` defines its own Zod
schemas independently, without importing from `@seshat/common`. This means
changes to the domain type vocabulary (how Seshat thinks about a room) do not
automatically change the database schema (how Seshat stores a room), and
vice-versa. The two can evolve at different paces, with explicit translation at
the application layer.

- **Zod Row Schemas**: Type-safe Zod schemas validate every persisted entity —
  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, and
  sustainability assessments. Each schema yields an inferred `*Row` type and an
  `*InsertSchema` variant (omitting `createdAt`/`updatedAt`). Branded
  UUID-validated ID schemas exist per entity. These schemas are defined
  independently and do **not** import `@seshat/common`, keeping persistence
  decoupled from the domain type vocabulary.
- **Declarative Migration Definitions**: `migration001_initial` describes 18
  tables — columns, types, nullability, defaults, foreign keys, and indexes — as
  plain objects (`TableDefinition` / `MigrationDefinition`). `ALL_MIGRATIONS`
  lists migrations in order; `getTableDefinition`, `TABLE_NAMES`, and
  `TABLE_COUNT` are derived helpers. `generateMigrationSQL` renders a migration
  into `CREATE TABLE` / `ALTER TABLE` / `CREATE INDEX` SQL strings — it produces
  SQL text but does not execute it.
- **Seed Data**: Curated reference data for development and testing —
  `ROOM_TYPES` (26 room-type info records), `WOOD_SPECIES_SEEDS` (25 real wood
  species), and `TOOL_SEEDS` (20 real woodworking tools).

> Sensor-reading and project-description tables exist as schema definitions, but
> TimescaleDB hypertable compression and pgvector semantic search are not
> implemented — those are described as future scope in the Phase 36 backlog.

---

## Implementation Status

Seshat is implemented as **11 TypeScript libraries** under `libs/seshat/`. There
is no `apps/seshat` or `services/seshat`, no HTTP API gateway, and no domain
event bus — `SeshatEventType` / `SeshatEvent` are bare type declarations with no
publisher or transport. The design library performs rule-based analysis, not AI
image generation. The TODOS Phase 36 backlog describes an API gateway, event
infrastructure, and an ORM-backed database as planned work that is not present
in the workspace.

## Cross-Domain: Real-Time Visualization (Phase 144, planned)

Seshat's room and dwelling designs are a consumer of the Neith real-time
visualization renderers (`@neith/viz-*`): design-library outputs render as
walkthroughs, VR previews, and environment-lit presentations. Seshat owns the
dwelling/design data model; Neith owns the renderer and presentation surface.
