# Aglaea Domain — Architecture

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

Aglaea is the personal style intelligence domain in Oshun. It answers the
question every person faces when getting dressed, shopping, or choosing a
skincare routine: _what will actually work for me, specifically?_ The domain
combines computer vision analysis of a user's physical characteristics — skin,
body proportions, face shape, hair, nails, and coloring — with AI-powered
recommendation engines to deliver advice that is genuinely personalized rather
than generic.

Named after the Greek goddess of beauty, splendor, and adornment, Aglaea covers
fashion, beauty, skincare, haircare, fragrance, and accessories end to end.
Because styling advice depends on the full picture of a person — their coloring
affects which fabrics flatter them, their body proportions determine which
silhouettes create visual balance, and their skin type determines which active
ingredients their routine should include — Aglaea is designed as a deeply
integrated platform rather than a collection of independent tools.

The domain is a **pure library domain** — it has 93 libraries under
`libs/aglaea/`, with no standalone application or service (`apps/aglaea/` and
`services/aglaea/` do not exist). These libraries are consumed by host
applications in other domains and by the shared Oshun platform.

---

## Library Organization

The 93 libraries are organized into functional groups. Each group represents a
logical layer or capability cluster; the groups build on each other from the
bottom up (Foundation → Analysis → Personalization → Recommendations →
Consumer-facing surface).

```
libs/aglaea/
│
├── FOUNDATION
│   ├── core/                        # Zod-schema type system, color science, constants, config, validation
│   ├── database/                    # Knex migrations + Zod row schemas, seeding (PostgreSQL)
│   ├── sdk/                         # Unified TypeScript client SDK
│   ├── events/                      # Domain event types and pub/sub
│   ├── ai-orchestrator/             # Model routing, A/B testing, fallbacks, monitoring
│   └── testing/                     # Mock factories, fixtures, test utilities
│
├── PHYSICAL ANALYSIS
│   ├── skin-analysis/               # Skin biomarker / condition detection (per-condition detectors)
│   ├── enhanced-skin-analysis/      # Advanced condition tracking, multi-angle fusion, privacy
│   ├── color-analysis/              # Seasonal color analysis (12 sub-types)
│   ├── body-analysis/               # Body type classification and proportions
│   ├── enhanced-body-measurement/   # Precision body measurement from photos
│   ├── face-shape-analysis/         # Face shape detection
│   ├── hair-analysis/               # Hair type, texture, porosity, scalp health
│   ├── enhanced-hair-analysis/      # Advanced hair profiling, trichoscopy, shaft analysis
│   └── nail-analysis/               # Nail health and style analysis
│
├── FASHION INTELLIGENCE
│   ├── fashion-taxonomy/            # Garment classification and style vocabulary
│   ├── fabric-identification/       # Fabric type detection from photos
│   ├── fabric-properties/           # Fabric care, durability, sustainability
│   ├── fit-prediction/              # Size and fit prediction engine
│   ├── comfort-prediction/          # Comfort scoring and prediction
│   ├── style-taxonomy/              # Style classification system
│   ├── style-evolution/             # Personal style change tracking
│   ├── style-history/               # Fashion history and period analysis
│   ├── inclusive-fashion/           # Size-inclusive and adaptive fashion
│   └── cultural-adaptation/         # Culture-aware styling adjustments
│
├── OUTFIT AND WARDROBE
│   ├── outfit-recommendation/       # AI outfit generation and scoring
│   ├── wardrobe-management/         # Digital wardrobe CRUD and analytics
│   ├── occasion-engine/             # Context-aware occasion styling
│   ├── trend-forecasting/           # Trend detection, prediction, lifecycle
│   ├── generative-design/           # AI-driven generative fashion design and trend synthesis
│   ├── material-trends/             # Fabric and material trend analysis
│   ├── celebrity-style/             # Celebrity look matching and recreation
│   ├── care-intelligence/           # Garment care and maintenance
│   └── laundry-integration/         # Smart laundry and care scheduling
│
├── ACCESSORIES
│   ├── advanced-jewelry/            # Fine jewelry intelligence
│   ├── jewelry-recommendation/      # Jewelry styling recommendations
│   ├── watch-recommendation/        # Watch recommendations
│   ├── bag-recommendation/          # Handbag recommendations
│   ├── hat-recommendation/          # Hat recommendations
│   ├── scarf-styling/               # Scarf and wrap styling
│   ├── belt-styling/                # Belt selection guidance
│   ├── eyewear-recommendation/      # Eyewear frame recommendations
│   └── shoe-recommendation/         # Footwear recommendations
│
├── BEAUTY AND WELLNESS
│   ├── skincare-routine/            # Personalized skincare regimen builder
│   ├── hair-routine/                # Hair care routine optimization
│   ├── hairstyle-recommendation/    # AI hairstyle recommendations based on face shape and hair profile
│   ├── nail-care/                   # Nail care routine and product matching
│   ├── ingredient-intelligence/     # Cosmetic ingredient analysis
│   ├── ingredient-scanner/          # Product label scanning
│   ├── beauty-calendar/             # Seasonal beauty routine scheduling
│   ├── wellness-beauty/             # Wellness-beauty connection
│   ├── aging-trajectory/            # Skin aging prediction and prevention
│   └── aesthetic-treatments/        # Non-invasive treatment recommendations
│
├── FRAGRANCE
│   └── fragrance-intelligence/      # Scent profiling and recommendation
│
├── MAKEUP
│   ├── makeup-recommendation/       # Makeup shade and product matching
│   └── makeup-looks/                # Curated makeup looks and product mapping
│
├── VIRTUAL TRY-ON
│   ├── virtual-tryon-fashion/       # Clothing virtual try-on
│   ├── virtual-tryon-hair/          # Hair color/style visualization
│   ├── virtual-tryon-makeup/        # Makeup try-on
│   ├── virtual-tryon-nails/         # Nail art visualization
│   ├── virtual-tryon-accessories/   # Accessories visualization
│   ├── avatar-creation/             # Digital avatar generation from photos
│   └── before-after/                # Before/after comparison engine
│
├── SHOPPING AND COMMERCE
│   ├── personal-shopper-ai/         # Conversational AI shopping assistant
│   ├── shopping-assistant/          # Product discovery and comparison
│   ├── shopping-concierge/          # Premium concierge service
│   ├── agentic-shopping/            # Autonomous shopping agent
│   ├── product-matching/            # Product similarity and matching
│   ├── retailer-api/                # Retailer catalogue integration
│   └── digital-product-passport/    # Product provenance and authenticity
│
├── PERSONALIZATION ENGINE
│   ├── preference-learning/         # User preference ML pipeline
│   ├── lifestyle-profiler/          # Lifestyle analysis and profiling
│   ├── unified-profile/             # Cross-module user profile aggregation
│   ├── memory-system/               # Interaction memory and context
│   ├── conversation-engine/         # Natural language style consultation
│   └── multi-modal-input/           # Voice, image, text input processing
│
├── SUSTAINABILITY
│   ├── sustainability-scoring/      # Environmental impact scoring
│   └── sustainable-fashion/         # Eco-friendly fashion intelligence
│
├── SOCIAL AND COMMUNITY
│   ├── style-coaching/              # AI and human stylist coaching
│   ├── style-communities/           # Social style communities
│   ├── outfit-sharing/              # Outfit sharing and social
│   ├── inspiration-feed/            # Personalized style inspiration
│   ├── expert-network/              # Human stylist marketplace
│   ├── family-features/             # Family and group styling
│   ├── event-prep/                  # Event-specific styling preparation
│   ├── calendar-integration/        # Calendar-aware styling
│   └── gamification/                # Style gamification and rewards
│
├── CONTEXT SERVICES
│   ├── weather-service/             # Weather-aware styling
│   └── biometric-integration/       # Health data for personalization
│
└── PLATFORM
    ├── smart-mirror/                # Smart mirror integration
    ├── smart-device/                # IoT and wearable integration
    ├── sophia-integration/          # Cross-domain knowledge integration
    ├── ethical-ai/                  # Bias detection and fairness monitoring
    └── api-services/                # REST/GraphQL API layer
```

---

## Architectural Layers

Requests flow through a strict layered stack. Higher layers depend on lower
ones; lower layers never call upward. This means the Analysis layer produces
structured outputs that the Personalization layer normalizes into a profile, and
the Recommendation layer reads only from the normalized profile — never directly
from raw analysis results.

```
┌──────────────────────────────────────────────────────────────────────┐
│  CONSUMER LAYER                                                      │
│  @aglaea/sdk · @aglaea/api-services                                 │
├──────────────────────────────────────────────────────────────────────┤
│  RECOMMENDATION LAYER                                                │
│  @aglaea/outfit-recommendation · @aglaea/occasion-engine            │
│  @aglaea/personal-shopper-ai · @aglaea/shopping-concierge           │
│  @aglaea/fragrance-intelligence · @aglaea/makeup-recommendation     │
│  @aglaea/skincare-routine · @aglaea/trend-forecasting               │
├──────────────────────────────────────────────────────────────────────┤
│  PERSONALIZATION LAYER                                               │
│  @aglaea/unified-profile · @aglaea/preference-learning             │
│  @aglaea/memory-system · @aglaea/conversation-engine               │
│  @aglaea/lifestyle-profiler                                         │
├──────────────────────────────────────────────────────────────────────┤
│  ANALYSIS LAYER                                                      │
│  @aglaea/skin-analysis · @aglaea/color-analysis                    │
│  @aglaea/body-analysis · @aglaea/hair-analysis                     │
│  @aglaea/face-shape-analysis · @aglaea/fabric-identification       │
├──────────────────────────────────────────────────────────────────────┤
│  AI ORCHESTRATION LAYER                                              │
│  @aglaea/ai-orchestrator                                            │
├──────────────────────────────────────────────────────────────────────┤
│  FOUNDATION                                                          │
│  @aglaea/core · @aglaea/database · @aglaea/events                  │
└──────────────────────────────────────────────────────────────────────┘
```

---

## Core Design Patterns

Five architectural decisions shape the entire domain. Understanding these five
patterns is the fastest way to understand how the 93 libraries fit together.

### 1. AI Orchestration Layer

`@aglaea/ai-orchestrator` sits between all recommendation and analysis libraries
and the underlying ML model infrastructure. Rather than each library managing
its own model connections, every inference request flows through the
orchestrator, which provides:

- **Model registry**: Register and version all ML models with capability
  metadata
- **A/B testing**: Route a percentage of requests to challenger models and
  measure outcomes
- **Fallback strategies**: Graceful degradation when a model fails (try next
  model, use rule-based fallback)
- **Priority queuing**: Ensure latency-sensitive requests (real-time try-on)
  take precedence over batch analysis
- **Cost tracking**: Track and attribute inference cost per model and feature
- **Warm-up management**: Pre-warm models before expected demand spikes

### 2. Unified Profile as the Source of Truth

`@aglaea/unified-profile` is the central aggregation point for all user data.
Every analysis module (skin, color, body, hair) writes its output to the unified
profile. Every recommendation module reads from it. This means recommendation
modules never query analysis modules directly — they read normalized data from
the unified profile, ensuring consistency and avoiding circular dependencies.

The unified profile tracks a `profileCompleteness` score (0–100) that drives
onboarding guidance — the platform knows exactly which analyses are missing and
can prompt users to complete their profile.

### 3. Preference Learning as a Continuous Loop

`@aglaea/preference-learning` consumes events from every user interaction:
outfit feedback, product clicks, purchases, wardrobe adds, and virtual try-on
sessions. It maintains an ML model of each user's preferences across multiple
style dimensions (color, silhouette, formality, brand tier, sustainability
tier). This model is used by every recommendation module. The loop closes when
new recommendations are generated using the updated preference model and user
feedback is captured on those recommendations.

### 4. Ethical AI as an Architectural Constraint

`@aglaea/ethical-ai` intercepts recommendation outputs rather than auditing them
after the fact. It is wired directly into the recommendation pipeline output
path, where it:

- Detects and flags body-type bias (are all body types being served equally
  relevant recommendations?)
- Monitors skin tone representation in virtual try-on outputs
- Detects price-range bias (is the engine skewing toward luxury even for budget
  users?)
- Ensures diversity of style recommendations (preventing aesthetic filter
  bubbles)

### 5. Sophia Integration for Knowledge Depth

`@aglaea/sophia-integration` connects to the Sophia domain (Research and
Knowledge Management) to draw on:

- Peer-reviewed dermatology research for skin recommendations
- Fashion history and cultural knowledge for style guidance
- Ingredient safety research for cosmetic ingredient analysis
- Trend analysis from research corpora

The boundary exists because Sophia owns the research corpus and knowledge graph
infrastructure — Aglaea is a consumer of that knowledge, not a maintainer of it.
This prevents Aglaea from having to maintain its own research infrastructure and
ensures that dermatology evidence and ingredient safety data stay current
through Sophia's knowledge pipelines rather than becoming stale in Aglaea's own
storage.

---

## Library Dependency Graph (Key Paths)

The most important dependency chains to understand when tracing a feature are
shown below. The key insight is that `@aglaea/unified-profile` is the hub: every
analysis library writes into it, and every recommendation library reads from it.

```
@aglaea/outfit-recommendation
  ├── @aglaea/unified-profile
  ├── @aglaea/occasion-engine
  ├── @aglaea/wardrobe-management
  ├── @aglaea/fit-prediction
  └── @aglaea/ai-orchestrator

@aglaea/unified-profile
  ├── @aglaea/skin-analysis
  ├── @aglaea/color-analysis
  ├── @aglaea/body-analysis
  ├── @aglaea/hair-analysis
  └── @aglaea/preference-learning

@aglaea/skin-analysis
  └── @aglaea/ai-orchestrator (→ inference endpoint)

@aglaea/preference-learning
  ├── @aglaea/core
  └── @aglaea/events (subscribes to all user interaction events)

@aglaea/ai-orchestrator
  └── @aglaea/core

@aglaea/core   (no internal dependencies)
```

---

## Dependencies on Other Oshun Domains

Aglaea consumes two other Oshun domains. The boundary between Aglaea and each
domain is intentional: Aglaea is a style intelligence layer, not a research
corpus or an infrastructure platform.

| Domain            | Integration Reason                                                                     |
| ----------------- | -------------------------------------------------------------------------------------- |
| `@sophia/*`       | Research and knowledge integration for evidence-based beauty and style recommendations |
| Shared `@oshun/*` | Authentication, S3 image storage, observability, event bus                             |

---

## Build and Test Configuration

All 93 libraries use a consistent build and test setup. When Nx is unavailable
(e.g., due to worktree conflicts), use the direct invocations below.

- **Build executor**: `@nx/js:tsc`
- **Test executor**: `@nx/vite:test` (Vitest)
- **Tags**: `scope:aglaea`, `type:lib`, `layer:domain`

Direct invocations when Nx is unavailable:

```bash
# Type check
cd libs/aglaea/<library> && npx tsc --noEmit

# Run tests
cd libs/aglaea/<library> && npx vitest run

# Run core tests
cd libs/aglaea/core && npx vitest run
```

## Grounding

This architecture document was checked against the 93 libraries under
`libs/aglaea/` (there is no `apps/aglaea/` or `services/aglaea/`). It captures
the fashion/beauty/style library organization, layered intelligence
architecture, core design patterns, dependency graph, cross-domain consumers,
and build/test configuration. The library tree above matches the directory
listing and `libs/aglaea/README.md`; the foundation, design-pattern, and
dependency-graph claims trace to `core/`, `database/`, `ai-orchestrator/`,
`unified-profile/`, `preference-learning/`, `ethical-ai/`, and
`sophia-integration/` source.
