# Aglaea Domain — Features

> **Aglaea** — AI-Powered Fashion, Beauty, and Personal Style Platform

Aglaea (the Greek goddess of beauty, splendor, glory, magnificence, and
adornment — one of the three Charites, or Graces) is a comprehensive fashion,
beauty, skincare, haircare, nail care, fragrance, and personal styling platform.
It combines computer vision analysis, trend forecasting, fabric intelligence,
and AI recommendation engines to deliver hyper-personalized styling advice at
scale.

The core insight driving Aglaea's design is that personal style advice is only
valuable when it accounts for the full picture of the individual. The color of a
garment that flatters one person clashes with another's skin undertone; a
silhouette that creates visual balance for one body type overwhelms another; a
skincare routine that works for oily skin will worsen dry skin. Aglaea builds
that complete picture — through analysis of skin, hair, face shape, body
proportions, and coloring — and then uses it as the foundation for every
recommendation it makes.

**Industry-leading SOTA targets** (from `libs/aglaea/README.md`, benchmarked
against published reference systems — these are accuracy goals for the analysis
and forecasting engines, not measured production numbers): 150+ skin biomarkers,
94%+ body type classification, 91%+ trend forecasting accuracy, 99.99%+ fabric
identification, 90%+ virtual try-on conversion lift, 17–28% return rate
reduction.

Current workspace status: implemented as a pure library domain — 93 packages
under `libs/aglaea/`, with no `apps/aglaea/` or `services/aglaea/`. The package
inventory in `architecture.md` reflects the current monorepo state.

---

## Table of Contents

1. [Core Platform Infrastructure](#1-core-platform-infrastructure)
2. [Personal Analysis Engines](#2-personal-analysis-engines)
3. [Fashion Intelligence](#3-fashion-intelligence)
4. [Beauty and Skincare](#4-beauty-and-skincare)
5. [Haircare Intelligence](#5-haircare-intelligence)
6. [Nail Intelligence](#6-nail-intelligence)
7. [Fragrance Intelligence](#7-fragrance-intelligence)
8. [Outfit and Wardrobe Management](#8-outfit-and-wardrobe-management)
9. [Virtual Try-On](#9-virtual-try-on)
10. [Shopping Intelligence](#10-shopping-intelligence)
11. [Personalization Engine](#11-personalization-engine)
12. [Conversational AI and Coaching](#12-conversational-ai-and-coaching)
13. [Trend Forecasting](#13-trend-forecasting)
14. [Sustainability Intelligence](#14-sustainability-intelligence)
15. [Social, Community, and Gamification](#15-social-community-and-gamification)
16. [Smart Devices and IoT](#16-smart-devices-and-iot)
17. [Platform, API, and Ethical AI](#17-platform-api-and-ethical-ai)

---

## 1. Core Platform Infrastructure

The foundation layer provides the type system, database schema, AI
orchestration, event bus, and shared utilities that every other Aglaea library
builds on. The six packages in this group — `@aglaea/core`, `@aglaea/database`,
`@aglaea/ai-orchestrator`, `@aglaea/sdk`, `@aglaea/events`, and
`@aglaea/testing` — have no dependencies on any other Aglaea library, which
means they can be updated without affecting the rest of the domain.

### 1.1 Type System (`@aglaea/core`)

`@aglaea/core` establishes the domain's shared vocabulary. Every analysis
result, recommendation, and entity in the system is expressed in terms of the
types defined here, so the entire domain speaks a single, validated language.
All types are backed by Zod schemas, which means inputs are validated at module
boundaries and type errors are caught at runtime before they propagate into
analysis or recommendation logic.

- **Color science types**: Colors are represented in RGB, HSL, LAB, and Pantone
  simultaneously. LAB is the canonical internal space because it is perceptually
  uniform — equal numeric distances correspond to equal perceived color
  differences — which color-harmony scoring (Section 8) depends on. Conversion
  between spaces is lossless within gamut and clamps out-of-gamut values at the
  sRGB boundary.
- **Body measurement types**: Circumference measurements (bust, waist, hips),
  length measurements (inseam, torso length), and the derived shoulder width are
  stored in centimeters. Proportional relationships (torso-to-leg,
  shoulder-to-hip, waist-to-hip ratios) are computed from the raw measurements
  rather than stored, so they cannot drift out of sync.
- **Skin analysis types**: `SkinAnalysisResult` carries a Fitzpatrick phototype
  (`TypeI`–`TypeVI`), a five-way `SkinType` classification
  (`Normal`/`Dry`/`Oily`/`Combination`/`Sensitive`), a list of `SkinConcern`
  values, and eleven named 0–100 dimension scores (hydration, oiliness,
  elasticity, pigmentation, texture, wrinkle depth, pore size, redness,
  firmness, clarity, radiance). Ingredient reactions are tracked separately as
  `IngredientSensitivity` records with a `Mild`/`Moderate`/`Severe` level.
- **Fashion taxonomy types**: Garments are classified hierarchically — category
  (tops, bottoms, dresses), subcategory, silhouette, construction details, and
  aesthetic style tag — so a query can match at any level of specificity.
- **Validation**: Every core type has a Zod schema. Inputs crossing a module
  boundary are validated at the boundary; a validation failure rejects the input
  with a field-level error rather than propagating malformed data into analysis
  or recommendation logic.

### 1.2 AI Orchestration (`@aglaea/ai-orchestrator`)

The orchestrator sits between every analysis and recommendation library and the
underlying ML inference infrastructure. Rather than each library managing model
connections directly, every inference request flows through this single layer.
Libraries declare a `ModelCapability` — one of ten values: skin analysis, hair
analysis, body analysis, color analysis, outfit recommendation, trend
forecasting, fragrance matching, virtual try-on, fabric detection, and style
classification — and the orchestrator selects the appropriate model.

- **Model registry**: Each model is registered with a `ModelConfig` — id, name,
  provider (`OpenAI`/`Anthropic`/`HuggingFace`/`Custom`/`RunPod`/
  `Replicate`/`Local`), inference endpoint, capability list, version, max batch
  size, timeout, per-inference cost, and `warmupRequired` flag. Multiple model
  versions can be registered for the same capability.
- **A/B testing**: An `ABTestConfig` routes a configurable `trafficSplitPercent`
  of inference requests for a capability to a treatment (challenger) model; the
  orchestrator records `ModelMetrics` per arm so a challenger can be promoted on
  a measured win rate rather than intuition.
- **Fallback strategies**: When a model returns an error or exceeds its
  configured timeout, the orchestrator retries with the registered fallback
  model; if no model succeeds, it surfaces a typed `InferenceError` to the
  caller.
- **Priority queuing**: Each `InferenceRequest` declares an `InferencePriority`
  (`low`/`normal`/`high`/`critical`). Latency-sensitive requests (real-time
  virtual try-on) are dispatched ahead of batch analysis so an interactive
  try-on is never blocked behind a bulk job.
- **Cost tracking**: Inference cost is attributed per model and per capability,
  making the cost of each feature visible.
- **Warm-up and edge deployment**: Models can be pre-warmed ahead of an expected
  demand spike, and an `EdgeDeploymentConfig` describes quantized
  (`int8`/`int4`/`fp16`) edge deployments to a `cpu`/`gpu`/`tpu`/`npu` target.

### 1.3 Data, Events, and Tooling

These four packages handle persistence, inter-module communication, external
access, and test infrastructure. Together they form the plumbing that lets the
93 libraries coordinate without coupling to each other directly.

- **Database layer** (`@aglaea/database`): PostgreSQL with Knex migrations and
  Zod row schemas. Persists personal profiles, skin/body analysis records,
  wardrobe items, outfits, product catalog, recommendation records, preferences,
  feedback, trends, ingredients, fabrics, brands/retailers, social records, and
  an audit log across sixteen schema modules. Skin analysis and body measurement
  records are dated history rows so a profile's evolution over time remains
  reconstructable.
- **Event bus** (`@aglaea/events`): Domain events decouple modules — when skin
  analysis completes, the skincare-routine module updates recommendations from
  the event rather than being called directly. The full event catalog is
  Section 17.
- **SDK** (`@aglaea/sdk`): Typed TypeScript SDK and browser client for the
  platform API, with the same types as `@aglaea/core` so consumers share one
  type definition end to end.
- **Testing** (`@aglaea/testing`): Mock factories, fixtures, mock images,
  benchmarking, chaos, snapshot, and integration-test utilities — so
  recommendation and analysis logic can be tested across synthetic profiles
  spanning the full `BodyShape`, `SeasonalSubtype`, and `FitzpatrickScale`
  range, not just one body.

---

## 2. Personal Analysis Engines

Computer-vision analysis of the user's body, face, skin, hair, nails, and
coloring forms the foundation of every personalized recommendation. Every
analysis writes its result to the unified profile (Section 11), and the result
of each analysis advances the profile's `profileCompleteness` score — a 0–100
measure of how many of the analyses are present. The platform uses
`profileCompleteness` to drive onboarding: it knows exactly which analyses are
missing and prompts for them, and recommendation modules degrade gracefully when
a profile is incomplete rather than producing low-confidence output from absent
data.

### Skin Analysis (`@aglaea/skin-analysis`, `@aglaea/enhanced-skin-analysis`)

Skin analysis takes a high-resolution photograph and runs it through computer
vision models, producing a `SkinAnalysisResult`. The `skin-analysis` library
implements dedicated per-condition detectors — acne, rosacea, redness and
inflammation, pores, oiliness, pigmentation and melasma, sun spots and UV
damage, hydration and barrier, wrinkles, crow's feet, forehead/glabellar/
marionette/nasolabial/neck lines, texture, scars, freckles, hypopigmentation,
and more — each as its own source module.

- **Quantitative scoring**: The result carries eleven named 0–100 dimension
  scores (hydration, oiliness, elasticity, pigmentation, texture, wrinkle depth,
  pore size, redness, firmness, clarity, radiance). The score, not a raw pixel
  measurement, is what routine and treatment logic consumes, so improvements are
  directly comparable across analyses.
- **Concern detection**: Detected `SkinConcern` values (from a twelve-value set:
  acne, wrinkles, dark spots, large pores, dullness, redness, dehydration,
  hyperpigmentation, sun damage, texture, undereye circles, sagging) are
  attached to the result and drive routine and treatment logic.
- **Skin tone and type**: Skin tone is placed on the Fitzpatrick phototype scale
  (`TypeI`–`TypeVI`), the dermatological standard for classifying skin by UV
  response, and the core `FITZPATRICK_UV_DATA` table maps each phototype to a
  recommended SPF and burn-time range. `SkinType` is one of `Normal`, `Dry`,
  `Oily`, `Combination`, or `Sensitive` — each implies a fundamentally different
  routine, so this classification is a hard input to the skincare-routine
  builder rather than advisory.
- **Longitudinal tracking**: Because each analysis is stored as a dated record,
  scores can be charted over time, and a regression in a tracked condition can
  be surfaced proactively — the `skin-analysis` library includes
  temporal-analysis, progress-comparison, and significance-testing modules for
  this.
- **Before/after comparison** (`@aglaea/before-after`): Pixel-level comparison
  of two analyses (across time, or before/after a treatment) yields a
  per-biomarker delta and an aggregate improvement score, so the effect of a
  routine or treatment is quantified rather than judged by eye.

### Aging Trajectory (`@aglaea/aging-trajectory`)

While skin analysis measures current condition, aging trajectory projects how
that condition will change over time — helping users understand not just where
their skin is today but where it is headed, and what interventions can alter
that path.

- **Skin age estimation**: Computer vision model estimates the biological age of
  the skin — which may differ from chronological age — based on measurable
  biomarker states.
- **Aging trajectory prediction**: Evidence-based projection of how the skin is
  likely to age given current condition and lifestyle factors, with prevention
  pathway modeling.
- **Intervention impact modeling**: Quantify the expected improvement from
  consistent use of specific active ingredients or treatments, helping users
  prioritize interventions.

### Color Analysis (`@aglaea/color-analysis`)

Color analysis determines which colors of clothing, makeup, and accessories most
flatter an individual given their natural coloring (skin, hair, eyes). Its
output is a `SeasonalColorPalette` that influences every downstream styling and
recommendation decision — from outfit color-harmony scoring to jewelry
metal-tone selection.

- **Seasonal classification**: The user is classified into one of the twelve
  `SeasonalSubtype` values — `LightSpring`, `WarmSpring`, `ClearSpring`,
  `LightSummer`, `SoftSummer`, `CoolSummer`, `SoftAutumn`, `WarmAutumn`,
  `DeepAutumn`, `DeepWinter`, `CoolWinter`, `ClearWinter` — grouped under four
  parent `Season` values (Spring, Summer, Autumn, Winter). The 12-season system
  refines the four seasons along warmth, value, and chroma axes; the
  `seasonal-classification` module computes those three perceptual axes from LAB
  skin and hair signals, and each subtype maps to a distinct palette.
- **Undertone**: Undertone is resolved to `Cool`, `Warm`, `Neutral`, or `Olive`
  from the combined skin, hair, and eye signals. Undertone is a primary
  determinant of flattering color.
- **Palette generation**: The output `SeasonalColorPalette` splits colors (in
  LAB space) into `bestColors` (most flattering), `goodColors` (acceptable but
  not optimal), and `avoidColors` (clash with the user's coloring), plus a
  `neutrals` palette for staples and recommended `metalTones` for jewelry. The
  core `SEASONAL_PALETTE_ANCHORS` table provides anchor colors per subtype.
- **Outfit color harmony**: Color-wheel relationships are modeled by the
  `ColorHarmony` type (`Complementary`, `Analogous`, `Triadic`,
  `SplitComplementary`, `Tetradic`, `Monochromatic`), and an outfit
  recommendation's `confidence.colorHarmony` score (0–1) reflects how well its
  palette agrees with the personal palette and with itself (Section 8).

### Body Analysis (`@aglaea/body-analysis`, `@aglaea/enhanced-body-measurement`)

Body analysis produces a body-shape classification, raw `BodyMeasurements`, and
a derived `BodyProportions` profile. These three outputs — shape label, absolute
measurements, and proportional ratios — each serve different downstream
purposes. Shape drives silhouette guidance, measurements feed fit prediction,
and proportional ratios determine the visual-balance corrections that make
styling advice specific rather than generic.

- **Body shape classification**: One of eight `BodyShape` values — `Hourglass`,
  `Pear`, `Apple`, `Rectangle`, `InvertedTriangle`, `Oval`, `Diamond`,
  `Athletic` — classified from photographs (94%+ accuracy target). The core
  `BODY_SHAPE_THRESHOLDS` table defines the ratio thresholds for each shape.
  Each shape has documented styling strategies for visual balance, so it is a
  selector for the silhouette-recommendation rule set.
- **Precision measurement pipeline**: `BodyMeasurements` captures ten
  circumference and length values in centimeters — bust, waist, hip, inseam,
  shoulder, arm length, torso length, thigh, neck, and wrist — estimated from
  photographs, removing the need for a tape measure when shopping online; these
  feed fit prediction (Section 3).
- **Proportional analysis**: `BodyProportions` computes waist-to-hip,
  shoulder-to-hip, bust-to-waist, torso-to-leg, and shoulder-to-waist ratios.
  These ratios — not the body-shape label alone — determine which proportions
  are most flattering, so two users with the same body shape but different
  ratios receive different silhouette guidance.
- **Silhouette recommendations**: For each body type and proportional profile,
  the engine recommends garment silhouettes that create visual balance, grounded
  in established fashion styling principles rather than generic advice.

### Face Shape Analysis (`@aglaea/face-shape-analysis`)

Face shape analysis determines which hairstyles, eyewear frames, earring shapes,
necklines, and hat styles are most flattering for a given facial structure. Its
output feeds multiple downstream libraries — hairstyle recommendations, eyewear
selection, and hat styling — so an accurate face shape classification has a wide
effect on recommendation quality.

- **Face shape detection**: Classify face shape (oval, round, square, heart,
  diamond, oblong/rectangle) from facial landmark analysis — each shape has
  specific recommendations for what to emphasize or de-emphasize.
- **Hairstyle recommendations**: Suggest flattering hairstyles for the detected
  face shape (e.g., volume at the sides for a narrow face, minimal width for a
  round face).
- **Eyewear recommendations**: Recommend eyewear frame shapes that complement
  the face shape — round frames soften angular faces, rectangular frames add
  structure to round faces (`@aglaea/eyewear-recommendation`).
- **Accessory geometry recommendations**: Suggest necklace lengths (shorter
  necklaces for longer faces, longer for rounder), earring shapes, and hat
  styles based on face shape proportions.

### Hair Analysis (`@aglaea/hair-analysis`, `@aglaea/enhanced-hair-analysis`)

Hair analysis classifies the physical properties of hair that determine which
products and routines are appropriate. The same product that adds moisture for
one hair type will weigh down another, so accurate classification here directly
determines routine quality.

- **Hair type and texture analysis**: Classify curl pattern using the Andre
  Walker system (1A straight through 4C tightly coiled), porosity (how well hair
  absorbs moisture), thickness (fine/medium/coarse), and density (how many hairs
  per square inch).
- **Scalp health analysis**: Assess scalp condition (dry, oily, sensitive,
  healthy, flaky) — scalp health directly determines which shampoo and treatment
  formulations are appropriate.
- **Advanced hair profiling**: Comprehensive hair diagnostics including damage
  assessment (split ends, breakage pattern, heat damage), protein/moisture
  balance, and chemical processing history analysis.

---

## 3. Fashion Intelligence

Deep knowledge of garments, fabrics, style, and fit — the domain-specific
expertise that makes the difference between a recommendation engine that knows
facts about clothes and one that understands how clothes actually work on real
people.

### Fabric Intelligence (`@aglaea/fabric-identification`, `@aglaea/fabric-properties`)

Fabric knowledge underpins care instructions, sustainability scoring, comfort
prediction, and longevity guidance. Being able to identify fabric from a
photograph means none of this intelligence requires the user to read a label.

- **Fabric identification from photos**: Identify fabric type (the `FabricType`
  enum covers twenty types — cotton, silk, wool, linen, polyester, cashmere,
  denim, leather, and more) from product photographs (99.99%+ accuracy target) —
  enabling automatic care instructions and sustainability scores without the
  user reading a label.
- **Fabric property database**: Comprehensive fabric database covering care
  requirements (machine wash vs. dry clean), durability ratings, breathability,
  drape characteristics, and how each fabric ages.
- **Material trend analysis**: Track which fabrics and materials are trending in
  the market, correlating material choices with trend cycles
  (`@aglaea/material-trends`).
- **Care intelligence**: Garment care and maintenance instructions automatically
  tailored to the specific fabric composition of each wardrobe item, including
  washing temperature, drying method, ironing settings, and storage advice
  (`@aglaea/care-intelligence`).

### Style Taxonomy and Classification (`@aglaea/style-taxonomy`)

Style taxonomy is a structured vocabulary for classifying aesthetic identities,
occasions, and style personas — necessary for a machine to understand abstract
concepts like "minimalist chic" or "Parisian casual." Without a shared taxonomy,
every recommendation module would use its own ad-hoc classification scheme,
making cross-module consistency impossible.

- **Style vocabulary**: Comprehensive classification system for fashion
  aesthetics (minimalist, maximalist, bohemian, classic, streetwear, preppy,
  romantic, edgy, vintage), occasions (casual, business casual, formal,
  athletic, resort), and style personas.
- **Garment classification**: Classify garment type (category, subcategory),
  silhouette (A-line, bodycon, relaxed, structured), construction details
  (collar type, sleeve style, closure type), and aesthetic style tag.
- **Style evolution tracking**: Track how a user's personal style evolves over
  time — important for long-term recommendation quality and for users undergoing
  style transformations (`@aglaea/style-evolution`).
- **Fashion history library**: Historical context for fashion periods (1920s Art
  Deco, 1960s mod, 1990s minimalism), movements, and iconic looks — useful for
  both education and understanding cultural fashion references
  (`@aglaea/style-history`).
- **Celebrity style matching**: Match user to celebrity style references and
  assist in recreating specific celebrity-inspired looks at accessible price
  points (`@aglaea/celebrity-style`).

### Fit and Comfort (`@aglaea/fit-prediction`, `@aglaea/comfort-prediction`)

Return rates from online fashion retail are driven largely by fit failures — the
user's size in one brand is a different size in another, and they have no way of
knowing without trying it on. These two libraries address that problem directly.

- **Size and fit prediction**: Predict the best size for any specific garment
  given the user's body measurements — accounting for brand-specific sizing,
  garment stretch, intended fit (slim, regular, relaxed), and cut style. Targets
  0.74+ satisfaction accuracy and 17–28% reduction in return rates.
- **Comfort prediction**: Predict comfort scores for garments based on fabric
  composition, garment construction, and the user's body type — identifying
  potential fit issues before purchase.

### Inclusive Fashion (`@aglaea/inclusive-fashion`, `@aglaea/cultural-adaptation`)

These two libraries ensure Aglaea's recommendations are genuinely useful to the
full diversity of its users — not a default range with token additions.

- **Size-inclusive recommendations**: Styling recommendations across all size
  ranges, with specific knowledge of which silhouettes and cuts work across
  diverse bodies — not just a scaled-down version of standard recommendations.
- **Adaptive fashion**: Recommendations for users with adaptive clothing needs —
  magnetic closures, open-back designs, seated silhouettes, and other functional
  fashion features.
- **Cultural adaptation**: Adjust recommendations for cultural dress
  requirements and preferences — modesty guidelines, traditional dress
  integration, cultural occasion wear, and regional aesthetic traditions.

---

## 4. Beauty and Skincare

Comprehensive skincare intelligence from product ingredients to personalized
routines. The quality of skincare advice depends entirely on understanding what
is in the products and how those ingredients interact with a specific skin type
— which is why ingredient intelligence is the foundation of this section.

### Ingredient Intelligence (`@aglaea/ingredient-intelligence`, `@aglaea/ingredient-scanner`)

Understanding skincare ingredients is essential for building effective routines
— most people cannot interpret the INCI (International Nomenclature of Cosmetic
Ingredients) names on product labels. These two libraries translate that
technical language into actionable guidance.

- **Cosmetic ingredient analysis**: Analyze the function (humectant, emollient,
  occlusant, exfoliant, antioxidant), evidence level (proven, promising,
  anecdotal), and efficacy of skincare ingredients — explaining what each
  ingredient actually does.
- **Ingredient conflict detection**: Identify conflicting ingredient
  combinations that can reduce efficacy or cause irritation — e.g., Vitamin C
  (ascorbic acid) with retinol (both at low pH, but different pH optima), or
  direct acids with AHAs that disrupt barrier.
- **Product label scanning**: Scan and parse product labels to automatically
  extract and analyze the full ingredient list — no manual input required.
- **Skin concern targeting**: Map active ingredients to the specific skin
  concerns they address — hyaluronic acid for hydration, niacinamide for pores
  and pigmentation, retinol for aging, salicylic acid for acne.

### Skincare Routines (`@aglaea/skincare-routine`, `@aglaea/beauty-calendar`)

A good skincare routine is specific to the person, the season, and the
ingredients they are using — and it needs to be updated as any of those change.
These two libraries manage both the routine itself and its lifecycle over time.

- **Personalized skincare regimen builder**: Build AM and PM routines tailored
  to skin type, skin concerns, climate (humidity and UV index affect optimal
  formulations), and product availability — generating step-by-step routines
  with specific product recommendations.
- **Step sequencing**: Correct application order for layering multiple products
  — generally thinnest to thickest, actives before moisturizers, SPF always last
  in AM. Incorrect layering reduces product efficacy.
- **Seasonal routine adjustments**: Modify routines for seasonal climate changes
  — switching to richer moisturizers in winter, lighter formulations in summer,
  adding antioxidants in summer for UV protection support.
- **Beauty calendar**: Schedule seasonal routine transitions, treatment
  appointments, product introduction phases (new actives should be introduced
  slowly to assess skin response), and product replacement reminders.

### Aesthetic Treatments (`@aglaea/aesthetic-treatments`)

For users seeking professional treatment alongside a home routine, this library
provides evidence-based guidance on the available options and how they compare.

- **Non-invasive treatment recommendations**: Recommend chemical peels
  (superficial, medium, deep), facials (hydrafacial, microneedling, LED),
  microdermabrasion, and other aesthetic treatments for specific skin concerns.
- **Treatment plan builder**: Build a complete treatment plan with treatment
  sequencing (some treatments require recovery time before the next), downtime
  expectations, and maintenance intervals.
- **Treatment comparison**: Compare treatment options by expected efficacy,
  downtime requirements, cost range, and discomfort level for informed
  decision-making.

### Wellness-Beauty Connection (`@aglaea/wellness-beauty`, `@aglaea/biometric-integration`)

Skin condition does not exist in isolation from the rest of the body — sleep
quality, stress, hydration, and diet all have measurable effects on skin
appearance. These two libraries surface those connections so recommendations can
account for the full context.

- **Wellness-beauty correlation analysis**: Analyze the connection between
  wellness behaviors (sleep quality, hydration, diet patterns, stress levels)
  and visible skin condition — explaining how lifestyle factors manifest in skin
  appearance.
- **Biometric integration**: Use health biometrics from wearables (HRV as a
  stress proxy, sleep score, activity data) to contextualize skin analysis —
  explaining why skin looks different on high-stress or poor-sleep days.

### Makeup Recommendations (`@aglaea/makeup-recommendation`, `@aglaea/makeup-looks`)

Makeup recommendations are grounded in the same color analysis and facial
analysis data as all other Aglaea recommendations — the goal is always to
enhance the specific person, not to apply a generic look.

- **AI-powered makeup product matching**: Match foundation shades, concealers,
  and complexion products to specific skin tone and undertone — eliminating the
  difficulty of finding the right shade when shopping online.
- **Makeup looks library**: Curated library of makeup looks organized by
  occasion, style, and trend, with product-to-look mapping and tutorials.
- **Technique recommendations**: Recommend makeup application techniques
  appropriate for the user's features — eye shape, lip shape, and face shape all
  affect which techniques are most flattering.

---

## 5. Haircare Intelligence

AI-powered haircare advice from routine building to virtual try-on. Hair type
and texture determine which products, routines, and styles are appropriate;
advice that ignores these properties — recommending the same products for 2A
fine hair and 4C coarse hair — is not merely unhelpful but counterproductive.

- **Hair routine optimization**: Build personalized haircare routines for
  specific hair type (curl pattern, porosity, thickness) and goals (growth,
  moisture, protein balance, color maintenance) — the correct routine is
  entirely different for 2A fine hair vs. 4C coarse hair
  (`@aglaea/hair-routine`).
- **Hairstyle recommendations**: Recommend hairstyles (length, texture, cut
  style) based on the combination of face shape, hair type, lifestyle, and
  maintenance willingness — a recommendation that is flattering but requires 90
  minutes of styling daily is not practical for most users
  (`@aglaea/hairstyle-recommendation`).
- **Virtual hair try-on**: Visualize different hair colors and cut styles on the
  user's photo before making a commitment — reducing the anxiety of major hair
  changes (`@aglaea/virtual-tryon-hair`).
- **Product matching**: Match haircare products (shampoo, conditioner,
  treatments, styling products) to the specific hair type, porosity level, and
  concern — porosity in particular determines whether protein-rich or
  moisture-rich formulations are needed.

---

## 6. Nail Intelligence

Nail health analysis, care guidance, and creative styling.

- **Nail health analysis**: Assess nail condition including strength
  (brittleness, breakage patterns), hydration, nail bed health, and signs of
  nutritional deficiency visible in the nail — such as white spots (trauma or
  zinc deficiency), vertical ridging (aging or malnutrition), and nail color
  changes (`@aglaea/nail-analysis`).
- **Nail care routines**: Personalized nail care routines for nail type and
  growth goals — strengthening protocols, cuticle care, hydration strategies,
  and the optimal filing technique for each nail shape (`@aglaea/nail-care`).
- **Virtual nail try-on**: Visualize nail art designs, color swatches, nail
  shapes (square, round, almond, stiletto, coffin/ballerina), and gel vs.
  natural finishes on the user's actual hand photo before booking a nail
  appointment (`@aglaea/virtual-tryon-nails`).

---

## 7. Fragrance Intelligence

AI-powered scent profiling and fragrance recommendations, implemented in
`@aglaea/fragrance-intelligence` (scent-profile, fragrance-matching, and
application-guide modules) over the core `FragranceProfile` type. The challenge
of fragrance discovery is that you cannot smell a product online — the library
addresses this by building a detailed olfactory preference model from stated
preferences, known dislikes, and occasion requirements, then matching that model
to a fragrance database.

- **Scent profile creation**: Build a detailed olfactory preference profile —
  preferred `FragranceFamily` values (twelve: floral, oriental, woody, fresh,
  citrus, aromatic, chypre, fougère, gourmand, aquatic, green, musk), individual
  preferred and avoided notes (each note positioned `Top`, `Middle`, or `Base`
  in the scent pyramid), per-occasion and per-season preferences, and a
  preferred concentration tier.
- **Fragrance recommendations**: Recommend perfumes and colognes from the user's
  scent profile (90%+ first-pick match target) — reducing the difficulty of
  fragrance discovery when smelling online is impossible.
- **Fragrance layering**: Suggest complementary fragrances for layering to
  create unique scent combinations — the practice of applying multiple
  fragrances simultaneously to create a personalized bespoke scent.
- **Occasion matching**: Recommend fragrances appropriate for specific occasions
  — some fragrances project more powerfully (suitable for evenings but
  overwhelming in offices), others are lighter (appropriate for sport or daytime
  professional settings).
- **Seasonal scent guidance**: Adjust fragrance recommendations seasonally —
  heavier, warmer oriental and woody fragrances perform better in cold weather;
  lighter citrus and aquatic fragrances suit summer heat and humidity.

---

## 8. Outfit and Wardrobe Management

Complete digital wardrobe management and AI-powered outfit generation. The
wardrobe is the inventory that the outfit engine draws from — building the
digital wardrobe once enables every subsequent outfit recommendation to work
from the user's actual clothes rather than generic catalog items.

### Outfit Recommendation (`@aglaea/outfit-recommendation`, `@aglaea/occasion-engine`)

The outfit engine produces an `OutfitRecommendation`: a list of wardrobe item
IDs, a multi-dimensional `RecommendationConfidence`, styling notes, a rationale,
alternative-swap suggestions, and an optional achieved `ColorHarmony` type.

- **AI outfit generation**: Combinations are assembled from the user's digital
  wardrobe and scored by `RecommendationConfidence` — an object of seven 0–1
  scores: `overall`, `styleMatch`, `colorHarmony`, `occasionFit`,
  `trendAlignment`, `bodyFlattery`, and `weatherAppropriateness`. The scores are
  surfaced separately so a user can see, for example, that an outfit is
  color-perfect (`colorHarmony` high) but a style mismatch (`styleMatch` low).
- **Occasion engine**: An outfit is generated for a specific `OccasionType` —
  one of fifteen values: `Casual`, `Business`, `BusinessCasual`, `Formal`,
  `BlackTie`, `Cocktail`, `DateNight`, `Wedding`, `Interview`, `Outdoor`,
  `Beach`, `Festival`, `Travel`, `Gym`, `Lounge`. The related `DressCode` enum
  (`WhiteTie` through `Resort`) refines the formality band. Each occasion
  defines a formality band and acceptable silhouettes; the `occasion-engine`
  library also covers event styling and travel packing.
- **Weather-aware styling** (`@aglaea/weather-service`): The recommendation
  takes a `WeatherContext` — min/max temperature, humidity, precipitation type,
  UV index, wind speed — and filters or layers garments accordingly, so a
  cocktail outfit for a cold, wet evening differs from the same occasion in
  summer heat.
- **Calendar-aware styling** (`@aglaea/calendar-integration`): Reading the
  user's calendar, the engine prepares an outfit for an upcoming event and
  surfaces it the evening before, mapping the event type to an `OccasionType`.
- **Event preparation** (`@aglaea/event-prep`): For a specific event, builds a
  complete plan — garments plus shoes, bag, and jewelry — as a coordinated set
  rather than independent recommendations.
- **Feedback loop**: Recommendation feedback is captured via the
  `recommendation.accepted` / `recommendation.rejected` events (with a rating or
  reason) and consumed by preference learning (Section 11).

### Digital Wardrobe (`@aglaea/wardrobe-management`)

Each garment is a `WardrobeItem` record carrying category, subcategory, brand,
name, colors, pattern, fabric (and optional blend), size and size region,
formality, style, applicable seasons and occasions, condition, purchase price
and date, care instructions, image URLs, tags, and a `wearHistory`.

- **Photograph and catalog**: The `digitization` module analyzes a photograph of
  a garment to extract its category, color, brand, and style attributes
  automatically, so building the digital inventory does not require manual data
  entry per item.
- **Cost-per-wear analytics**: Each item carries a `wearCount` counter and a
  dated `wearHistory`. The analytics module derives a `CostPerWear` value
  (purchase price ÷ wear count) and an `ItemROI` per item — making the true
  value of an item visible, since a frequently worn item trends toward zero
  while an unworn item's cost-per-wear stays at its full purchase price.
- **Item state**: An item carries `isFavorite`, `isArchived`, `storageLocation`,
  `needsRepair`, and `repairNotes` flags. Archived items are excluded from the
  active wardrobe; a donation queue tracks items being retired.
- **Wardrobe gap analysis**: The `optimization` module compares the inventory
  against the user's lifestyle profile and usage patterns to produce a
  `WardrobeGap` report, a `RedundancyReport`, and `VersatilityScore`s,
  distinguishing genuine gaps from items already owned but rarely worn, and can
  generate a `CapsuleWardrobe` from existing items.
- **Laundry and care integration** (`@aglaea/laundry-integration`): Wear-count
  thresholds trigger laundry reminders, and each garment's care instructions are
  derived from its fabric composition.
- **Digital product passport** (`@aglaea/digital-product-passport`): Surfaces
  provenance, material composition, authenticity verification, and
  sustainability certifications for items that carry a digital product passport,
  the per-item record now required under EU regulation.

### Accessories

Each accessory library scores candidate pieces against the relevant slice of the
unified profile — face shape, body proportions, color palette, outfit formality
— and the colors of the outfit it is being matched to, returning ranked
recommendations rather than a generic catalog. Each accessory type has its own
matching logic reflecting the specific geometry of the item.

- **Jewelry** (`@aglaea/jewelry-recommendation`): Recommends a jewelry style
  (delicate, statement, vintage, modern) and metal (gold, silver, mixed) by
  matching metal warmth to the user's color undertone and scaling piece
  prominence to the outfit's formality and neckline — delicate pieces for high
  necklines, statement pieces for open ones.
- **Fine jewelry** (`@aglaea/advanced-jewelry`): Adds investment-grade expertise
  — gemstone identification, the 4Cs diamond grading (cut, color, clarity,
  carat), metal alloy assessment, and authentication guidance — so a significant
  purchase is evaluated on quality grade and provenance, not styling alone.
- **Watches** (`@aglaea/watch-recommendation`): Matches a watch class — dress,
  sport, or casual — to outfit formality (a dress watch for `black_tie`, a sport
  watch for `sport_active`) and to the user's personal style.
- **Bags** (`@aglaea/bag-recommendation`): Selects a handbag by occasion and
  outfit formality, scales the bag's size to the user's body proportions so it
  neither overwhelms a petite frame nor looks undersized on a tall one, and
  accounts for stated carrying needs (laptop, travel).
- **Hats** (`@aglaea/hat-recommendation`): Recommends a hat shape (fedora,
  wide-brim, baseball cap, beanie, beret) chosen for the user's face shape —
  brim width balances face proportions — and the occasion.
- **Scarves** (`@aglaea/scarf-styling`): Recommends scarves whose color sits in
  the personal palette and suggests a styling technique (Parisian knot, loop,
  drape) flattering for the user's face shape and the outfit's neckline.
- **Belts** (`@aglaea/belt-styling`): Selects belt width, material, and buckle
  for the outfit, and recommends placement (waist vs. hip) to create the visual
  effect of a defined waist appropriate to the user's body type.
- **Shoes** (`@aglaea/shoe-recommendation`): Recommends footwear by heel height,
  toe silhouette (pointed, round, square, platform), and material, balancing the
  occasion and outfit against the user's stated comfort tolerance — a high heel
  is suppressed for a user who has flagged comfort as a priority.

Eyewear recommendation is documented under Face Shape Analysis (Section 2),
where it scores frame shapes against the detected face shape.

---

## 9. Virtual Try-On

Visualize garments, beauty products, and accessories before purchasing. The
primary goal of this section is reducing return rates — pre-purchase
visualization aimed at closing the gap between how a product looks in a catalog
photo and how it will look on the specific user.

- **Fashion virtual try-on**: Virtually try on clothing items on the user's body
  model generated from their measurements and photos — seeing how a specific
  garment's silhouette, fit, and drape would look without trying it on in person
  (`@aglaea/virtual-tryon-fashion`).
- **Makeup virtual try-on**: Try on makeup looks (foundation shades, lipstick
  colors, eyeshadow palettes, blush placement) in real time using augmented
  reality on the live camera feed or on a photo
  (`@aglaea/virtual-tryon-makeup`).
- **Hair virtual try-on**: Visualize hair color changes (highlights, all-over
  color, balayage), cut length changes, and different curl/texture treatments on
  the user's actual photo (`@aglaea/virtual-tryon-hair`).
- **Nail virtual try-on**: Preview nail art designs, colors, shapes, and
  finishes on the user's actual hands in a photo
  (`@aglaea/virtual-tryon-nails`).
- **Accessories virtual try-on**: Preview jewelry (earrings, necklaces, rings),
  sunglasses, hats, and bags on the user's photo
  (`@aglaea/virtual-tryon-accessories`).
- **Avatar creation**: Generate a photorealistic digital avatar from user photos
  for try-on experiences — the avatar captures the user's body proportions, skin
  tone, hair, and facial features (`@aglaea/avatar-creation`).
- **Smart mirror integration**: Drive smart mirror devices with outfit
  suggestions, virtual try-on overlays, and analysis displays — the smart mirror
  becomes an interactive styling assistant in the user's home
  (`@aglaea/smart-mirror`).
- **Before/after visualization**: Side-by-side before/after comparison for
  skincare progress, makeup looks, hairstyle changes, and wardrobe
  transformations (`@aglaea/before-after`).

---

## 10. Shopping Intelligence

AI-powered product discovery, matching, and concierge shopping. These libraries
connect the personal profile to the external retail world — helping users find
products that will actually work for them, at the right price point, across
multiple retailers.

- **Personal shopper AI**: Conversational AI shopping assistant that finds items
  matching the user's style profile, size, budget, and aesthetic — essentially a
  virtual personal shopper available 24/7 (`@aglaea/personal-shopper-ai`).
- **Shopping assistant**: Structured product discovery, comparison tools,
  filtering by style attributes, and shortlisting — for users who prefer
  browsing to conversation (`@aglaea/shopping-assistant`).
- **Shopping concierge**: Premium high-touch shopping service for luxury and
  special occasion purchases — involving research, quality assessment, and
  provenance verification for significant fashion investments
  (`@aglaea/shopping-concierge`).
- **Agentic shopping**: Autonomous shopping agent that proactively researches
  items matching the user's wishlist criteria, monitors prices, tracks restocks,
  and surfaces opportunities without requiring the user to initiate a search
  (`@aglaea/agentic-shopping`).
- **Product matching**: Find visually and functionally similar products across
  multiple retailers at different price points — enabling the user to find the
  look they want at their budget.
- **Retailer API integration**: Connect product catalogues from multiple retail
  partners with standardized data normalization, availability checking, and
  real-time pricing (`@aglaea/retailer-api`).
- **Skincare product matching**: Match skincare products to the user's skin
  analysis profile and concerns — filtering out products with irritating
  ingredients for sensitive skin, ensuring actives target the detected concerns.

---

## 11. Personalization Engine

Deep learning systems that understand and evolve with each user. The
personalization engine is what separates Aglaea from a generic product
recommender — it builds a model of each individual that improves with every
interaction and persists that model across sessions.

- **Preference learning**: ML pipeline that learns individual style and product
  preferences from explicit feedback (likes, saves, purchases) and implicit
  signals (dwell time, click-through, outfit assembly choices) — improving
  recommendations with every interaction (`@aglaea/preference-learning`).
- **Lifestyle profiling**: Analyze lifestyle, activities (professional, casual,
  athletic, evening, travel), social context, and aspirational identities to
  inform recommendations that fit actual life rather than an idealized version
  (`@aglaea/lifestyle-profiler`).
- **Unified user profile**: Aggregate signals from all modules — skin analysis,
  body analysis, color analysis, hair analysis, style preferences, purchase
  history — into a coherent cross-module user profile
  (`@aglaea/unified-profile`).
- **Long-term memory system**: Interaction memory that retains long-term context
  about preferences, past feedback, style evolution, and stated goals —
  preventing the system from forgetting the user's preferences between sessions
  (`@aglaea/memory-system`).
- **Family features**: Extend styling to family members — shared preferences
  across household members, group shopping, and managing multiple profiles
  within one household account (`@aglaea/family-features`).

---

## 12. Conversational AI and Coaching

Natural language interaction for style guidance and education. These libraries
give users a way to express what they need in ordinary language — including the
vague, subjective descriptions that are natural when talking about personal
style — and receive concrete, actionable guidance in return.

### Conversation Engine (`@aglaea/conversation-engine`)

The conversation engine handles multi-turn dialogues where context from earlier
turns affects the meaning of later ones. Without context retention, a follow-up
like "show me that in a warmer color" is unresolvable.

- **Style vocabulary understanding**: Interpret vague or subjective style
  descriptions ("I want to look more put-together but still approachable") and
  translate them into concrete product and outfit recommendations.
- **Context retention**: Multi-turn dialogue management that remembers earlier
  conversation context — "show me something similar but in a warmer color"
  requires remembering what was shown before.
- **Intent classification**: Classify user intent (browsing, seeking advice,
  planning an outfit for a specific occasion, comparing options) to provide
  contextually appropriate responses.
- **Entity extraction**: Extract fashion-relevant entities from natural language
  — colors, garment types, occasions, budget ranges, brands, and style
  descriptors.
- **Preference extraction from conversation**: Learn style preferences from
  conversational exchanges without requiring explicit rating input.
- **Clarifying question generation**: When requests are ambiguous, generate
  targeted clarifying questions that narrow down the intent efficiently.

### Style Coaching (`@aglaea/style-coaching`)

Style coaching teaches the principles behind recommendations rather than just
delivering them — building the user's long-term styling capability alongside
their immediate outfit choices.

- **Style rule education**: Explain why specific combinations work or don't
  work, teaching the underlying principles (color theory, proportion, visual
  balance) rather than just issuing prescriptive recommendations.
- **Body-specific advice**: Provide styling advice specific to the user's body
  proportions, explaining the visual reasoning behind each recommendation.
- **Confidence-building messaging**: Frame style guidance positively — building
  the user's confidence in their aesthetic identity rather than implying their
  current style is wrong.
- **Transition guidance**: Help users navigate life style transitions (career
  change, post-pregnancy, weight change, moving to a different climate) with
  specific wardrobe strategy advice.

### Multi-Modal Input (`@aglaea/multi-modal-input`)

Users naturally want to describe what they mean using images as well as words.
This library enables queries that combine photos, voice, and text into a single
request.

- **Voice, image, and text together**: Process voice queries, uploaded photos,
  and text simultaneously — e.g., "What should I wear with this?" (with a photo)
  processed as a unified query.
- **Photo inspiration parsing**: Extract style attributes from inspiration
  images — Pinterest boards, runway screenshots, celebrity photos — and
  translate them into actionable product recommendations.

---

## 13. Trend Forecasting

AI-powered trend detection and lifecycle prediction
(`@aglaea/trend-forecasting`). Trend intelligence matters because the shelf-life
of a fashion purchase depends on whether the item is a trend or a classic — a
micro-trend may be unwearable in two seasons, while a macro-trend can be worn
for years. The forecasting engine helps users invest in the right items.

- **Trend detection from multiple signals**: Identify emerging trends by
  aggregating signals from runway collections, fashion week coverage, social
  media (Instagram, TikTok, Pinterest), street style, and retail sell-through
  data.
- **Trend prediction**: Forecast trend adoption curves (which trends will go
  mainstream and when) and peak timing with 91%+ accuracy — distinguishing
  between micro-trends (short cycle, specific demographic) and macro-trends
  (broad, multi-season).
- **Trend lifecycle mapping**: Track trends from emergence (visible on runways
  and early adopters) through mainstream adoption (available at mid-market
  retailers) to saturation (widely available) and decline (no longer
  aspirational).
- **Material and fabric trends**: Forecast which fabrics and material properties
  (texture, transparency, structure) will trend alongside silhouette and color
  trends (`@aglaea/material-trends`).
- **Personalized trend relevance**: Filter global trend signals to those
  relevant to the individual user's style profile and lifestyle — a trend in
  office wear is irrelevant to someone who works from home.
- **Generative design**: AI-generated fashion design concepts (mood boards,
  colorways, silhouette sketches) based on synthesized trend intelligence —
  useful for designers and stylists using Aglaea as a creative tool
  (`@aglaea/generative-design`).

---

## 14. Sustainability Intelligence

Environmental and ethical intelligence for conscious fashion choices. The
fashion industry is one of the world's largest polluters, and purchasing
decisions are one of the primary levers consumers have. These libraries make the
environmental cost of each decision visible and findable.

- **Sustainability scoring**: Score garments and brands on environmental impact
  — carbon footprint per garment (considering fiber, dyeing, manufacturing, and
  transport), water consumption, chemical use, and end-of-life recyclability
  (`@aglaea/sustainability-scoring`).
- **Sustainable fashion intelligence**: Identify sustainable alternatives,
  eco-friendly brands (B Corp, GOTS certified, Fair Trade), secondhand options,
  and conscious shopping strategies (`@aglaea/sustainable-fashion`).
- **Digital product passport**: Verify product provenance, material composition
  traceability, authenticity (anti-counterfeit), and certification status —
  using the digital product passport infrastructure now required under EU
  Digital Product Passport regulations (`@aglaea/digital-product-passport`).
- **Care and longevity guidance**: Extend garment lifespan through proper care —
  reducing the environmental impact of fashion by keeping items out of landfill
  longer. The most sustainable garment is the one already in the wardrobe
  (`@aglaea/care-intelligence`).

---

## 15. Social, Community, and Gamification

Social features connecting style-minded users, plus engagement mechanics to make
the styling journey motivating. Building personal style is a long-term process,
and community and gamification provide the ongoing engagement that sustains it.

- **Style communities**: Join interest-based communities organized around style
  aesthetics (minimalism, vintage, cottagecore, streetwear, business
  professional) and engage with others who share those aesthetic interests
  (`@aglaea/style-communities`).
- **Outfit sharing**: Share outfit compositions with the community — a daily
  look post, an event outfit request, or a before/after style transformation
  (`@aglaea/outfit-sharing`).
- **Inspiration feed**: Curated style inspiration feed personalized to the
  user's aesthetic profile and seasonal trends — more personalized than a
  generic fashion feed (`@aglaea/inspiration-feed`).
- **Expert network**: Access to vetted human stylists and image consultants for
  paid consultations, wardrobe audits, and personal shopping services
  (`@aglaea/expert-network`).
- **Style coaching integration**: AI style coaching supplemented by human expert
  escalation for complex or nuanced style situations (`@aglaea/style-coaching`).
- **Gamification — achievements and challenges**: Style-oriented achievement
  system with badges earned for milestones (first virtual try-on, completing a
  full wardrobe catalog, 30-day skincare streak), multi-tier challenges (e.g.,
  "build 7 complete outfits from existing wardrobe items"), leaderboards
  comparing style consistency scores, point rewards, and a GamificationProfile
  that tracks the user's progress across all engagement mechanics — making the
  ongoing process of building personal style intrinsically motivating
  (`@aglaea/gamification`).

---

## 16. Smart Devices and IoT

Connect Aglaea to smart devices in the home and on the body. These integrations
extend the platform beyond the phone screen — into the mirror the user looks at
each morning, the closet where their clothes live, and the wearable that
monitors their health.

- **Smart mirror integration**: Drive smart mirror devices (MIRROR, Capstone
  Connected Mirror, etc.) with real-time outfit suggestions, virtual try-on
  overlays, skin analysis, and daily styling briefs displayed in the mirror as
  the user gets ready (`@aglaea/smart-mirror`).
- **Smart device ecosystem**: Connect to IoT devices — smart closets with
  automated inventory tracking via RFID, connected hangers that track which
  items are worn, NFC tag readers for garment identification
  (`@aglaea/smart-device`).
- **Biometric integration**: Use wearable health data (skin hydration sensors,
  stress indicators from HRV, sleep quality) to contextualize beauty and styling
  recommendations — e.g., recommending extra hydration-focused skincare after a
  poor sleep score (`@aglaea/biometric-integration`).

---

## 17. Platform, API, and Ethical AI

Programmatic access to the full Aglaea platform, the event catalog that
decouples its modules, and the bias controls wired into the recommendation
pipeline.

### 17.1 API and SDK

`@aglaea/api-services` defines every endpoint as a typed `RouteDefinition`,
aggregated by an endpoint registry under base path `/api/v1` (API version `v1`).
The registry holds 64 endpoints across seven modules; `@aglaea/sdk` exposes
high-level client methods over a subset of them. All endpoints require
authentication except the Trends/Discovery group, where eight endpoints are
`optional` or `required`.

| Module           | Count | Representative endpoints                                                                      |
| ---------------- | ----- | --------------------------------------------------------------------------------------------- |
| Profile          | 10    | `GET`/`POST`/`PUT`/`DELETE /profiles/:profileId`, `/profiles/:profileId/preferences`          |
| Analysis         | 10    | `POST /analysis/{skin,color,face-shape,body,hair,nails}`, `POST /analysis/compare`            |
| Recommendation   | 10    | `POST /recommendations/{outfit,shopping,color-palette,skincare-routine,makeup-look}`          |
| Wardrobe         | 10    | `GET`/`POST /wardrobe/:profileId/items`, `/wardrobe/:profileId/{analytics,gaps,capsule}`      |
| Virtual try-on   | 8     | `POST /tryon/{fashion,makeup,hair,nails,accessories,avatar}`                                  |
| Conversation     | 8     | `POST /conversations`, `POST /conversations/:sessionId/message`                               |
| Trends/Discovery | 8     | `GET /trends`, `GET /trends/forecast`, `GET /discovery/inspiration`, `POST /discovery/search` |

The full endpoint list is in `specifications.md` §5.

### 17.2 Domain Events

Two event surfaces exist. `@aglaea/events` is the runtime typed event system —
modules communicate through it rather than direct calls, so a consumer reacts to
an event without the producer knowing it exists (when skin analysis completes,
the skincare-routine module updates from the event). It defines an
`AGLAEA_EVENT_TYPES` const of 23 event type strings across five groups, each
with a typed payload interface:

| Group              | Event type strings                                                                                      |
| ------------------ | ------------------------------------------------------------------------------------------------------- |
| Analysis (5)       | `aglaea.analysis.{skin,body,hair,color}-completed`, `aglaea.analysis.failed`                            |
| Recommendation (5) | `aglaea.recommendation.{outfit-recommended,shopping-recommended,style-tip-generated,accepted,rejected}` |
| Wardrobe (6)       | `aglaea.wardrobe.{item-added,item-removed,item-worn,item-updated,outfit-created,outfit-rated}`          |
| Purchase (4)       | `aglaea.purchase.{completed,wishlist-added,cart-abandoned,return-initiated}`                            |
| Social (4)         | `aglaea.social.{profile-followed,outfit-shared,style-board-created,style-board-liked}`                  |

Every event is wrapped in a `DomainEvent<T>` envelope carrying `id`, `type`,
`timestamp`, `version`, `source`, optional correlation/causation IDs, and the
typed `payload`. For example, `SkinAnalysisCompletedPayload` carries
`profileId`, `analysisId`, `skinType`, `fitzpatrickType`, `overallScore`,
`concerns`, and `timestamp`. Separately, `@aglaea/api-services` declares 39
`EventDefinition` contract records (with `type`, `description`, `payload` schema
name, `topic`, and `version`) for documentation and contract generation; the
full catalog is in `specifications.md` §6–7.

### 17.3 Ethical AI as a Pipeline Constraint (`@aglaea/ethical-ai`)

Ethical AI is a bias-testing and representation-scoring layer over model outputs
rather than a post-hoc audit. The `bias-engine` runs paired bias tests across
the six `BiasType` dimensions — skin tone, body type, age, ethnicity, gender,
and disability — and the library also covers intersectional bias, fairness
metrics, inclusive language, adaptive-fashion database gaps, remediation
planning, and model-card transparency.

- **Bias metrics**: For each pair of demographic groups, a `BiasMetric` computes
  a disparate-impact ratio (ideal 1.0) and statistical parity (ideal 0) from the
  two groups' accuracy figures, and flags whether the pair passes.
- **Skin-tone bias** (`testSkinToneBias`): Tests model accuracy across all
  Fitzpatrick skin-tone pairs (`FitzpatrickSkinTone` I–VI), catching models that
  perform more confidently for some skin tones.
- **Body-type bias** (`testBodyTypeBias`): Tests accuracy across
  `BodyTypeCategory` groups (petite, slim, average, athletic, curvy, plus-size),
  so the engine does not serve some bodies better than others.
- **Representation scoring**: A `RepresentationScore` measures the diversity
  index (entropy-based, 0–1) of demographic representation, rolling up to an
  overall diversity score, so AI-generated content does not narrow onto a single
  demographic.

### 17.4 Knowledge and Data

- **Sophia integration** (`@aglaea/sophia-integration`): Draws on the Sophia
  research domain for peer-reviewed dermatology evidence, ingredient safety
  research, and fashion-history knowledge, so Aglaea does not maintain its own
  research corpus.
- **Database access layer** (`@aglaea/database`): Query builders, optimized
  access patterns, and caching strategies over the shared PostgreSQL schema.

## Grounding

This feature document is scoped to the implemented `libs/aglaea/*` package
surface — 93 libraries, all present in the monorepo. It captures recommendation,
analysis, virtual try-on, product matching, trend, wardrobe, shopping,
wellness-beauty, sustainability, ethical AI, and Sophia integration features.
Type names, enum values, event constants, and the API surface trace to
`@aglaea/core`, `@aglaea/ai-orchestrator`, `@aglaea/events`,
`@aglaea/api-services`, `@aglaea/ethical-ai`, and `@aglaea/wardrobe-management`
source; see `specifications.md` for the full contract detail. The
industry-leading accuracy figures are SOTA targets from `libs/aglaea/README.md`,
not measured production numbers.

Aglaea consumes Freya product, brand, inventory, and provenance data where
available, but Freya's supply-side luxury-goods operations remain documented in
`DOMAINS/freya/features.md`.
