# Hestia Domain - Developer Guide

> Comprehensive development guide for the Hestia culinary intelligence and smart
> home domain.

---

## Prerequisites

### Required Software

| Tool       | Version | Purpose                                  |
| ---------- | ------- | ---------------------------------------- |
| Node.js    | >= 20.0 | Runtime for all Hestia libraries         |
| pnpm       | >= 10.0 | Package manager (workspace protocol)     |
| Git        | >= 2.40 | Version control                          |
| TypeScript | ^6.0.3  | Compile-time type checking (via catalog) |

### Domain Knowledge

Developers working on Hestia libraries should be familiar with:

- **Food science** - Maillard reaction, emulsification, gelation, fermentation
  chemistry, flavor compound families (for `@hestia/ingredients` and
  `@hestia/education`)
- **Nutrition science** - Macronutrient/micronutrient profiles, bioavailability
  factors, dietary frameworks (keto, DASH, low-FODMAP), allergen groups (for
  `@hestia/nutrition`)
- **Food safety** - USDA internal temperature guidelines, HACCP critical control
  points, allergen cross-contamination (for `@hestia/cooking` and
  `@hestia/professional`)
- **IoT protocols** - Smart kitchen device communication protocols for oven,
  sous vide, thermometer, and scale integration (for `@hestia/smart-kitchen`)
- **Measurement systems** - US customary units (tsp, tbsp, cup, fl oz, pint,
  quart, gallon, oz, lb) and metric units (ml, liter, gram, kg), plus informal
  units (pinch, dash, piece, clove, sprig, bunch)

### Optional Tooling

| Tool   | Purpose                                           |
| ------ | ------------------------------------------------- |
| Docker | Running PostgreSQL for database integration tests |

### Environment Variables

No environment variables are required for building or unit-testing Hestia
libraries. `@hestia/core` has zero runtime dependencies.

For integration tests involving the database:

```bash
# Database (required for @hestia/core db-schema features)
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
```

---

## Project Structure

The Hestia domain contains 14 libraries under `libs/hestia/`:

```
libs/hestia/
  ai-ml/                   # Recipe generation, flavor AI, image recognition, NLP
  cooking/                 # Guided cooking, timers, voice, doneness, techniques
  core/                    # Foundation: schemas, db-schema, types, events, auth
  education/               # Techniques, skill progression, food science, certifications
  heritage/                # Family recipes, oral history, regional archives
  ingredients/             # Master database, flavor compounds, pairing, substitution
  meal-planning/           # Calendar, household, suggestions, budget, batch cooking
  nutrition/               # Analysis, bioavailability, dietary, allergen, medical
  pantry/                  # Inventory, barcode scanning, expiration, shopping lists
  professional/            # Menu costing, HACCP, kitchen workflow, catering
  recipes/                 # Recipe model, parsing, scaling, versioning, search
  smart-kitchen/           # IoT devices, sensors, appliances, automation
  social/                  # Recipe sharing, profiles, ratings, cook-alongs
  sustainability/          # Carbon footprint, food waste, ethical sourcing, composting
```

### Individual Library Layout

```
libs/hestia/<library>/
  package.json             # Name, version, ESM exports, peer deps
  project.json             # Nx configuration (build, lint, test targets)
  tsconfig.json            # Extends tsconfig.base.json
  tsconfig.lib.json        # Library compilation config
  tsconfig.spec.json       # Test compilation config
  vitest.config.ts         # Vitest test runner configuration
  src/
    index.ts               # Barrel export file
    <module>.ts             # Implementation files
    <module>.spec.ts        # Co-located tests
```

### Dependency Graph

Hestia has a flat dependency graph with `@hestia/core` as the sole foundation:

```
@hestia/core (standalone, zero runtime dependencies)
  |
  +-- @hestia/smart-kitchen (peer: core)
  +-- @hestia/recipes (peer: core)
  +-- @hestia/cooking (peer: core)
  +-- @hestia/ingredients (peer: core)
  +-- @hestia/nutrition (peer: core)
  +-- @hestia/meal-planning (peer: core)
  +-- @hestia/pantry (peer: core)
  +-- @hestia/heritage (peer: core)
  +-- @hestia/sustainability (peer: core)
  +-- @hestia/education (peer: core)
  +-- @hestia/professional (peer: core)
  +-- @hestia/social (peer: core)
  +-- @hestia/ai-ml (peer: core)
```

All libraries depend only on `@hestia/core` as a peer dependency. There are no
inter-library dependencies among the non-core libraries, which simplifies the
build graph.

---

## Local Development Setup

### Initial Setup

```bash
# Clone the repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# Install all dependencies
pnpm install
```

### No Infrastructure Required

`@hestia/core` has zero runtime dependencies. All domain logic is pure
TypeScript. No database, cache, or message broker is needed for unit testing.

For database integration work:

```bash
docker compose -f docker/docker-compose.dev.yml up -d postgres
```

---

## Building Libraries

### Build a Single Library

```bash
pnpm nx build @hestia/core
```

### Build All Hestia Libraries

```bash
pnpm nx run-many --target=build --projects=tag:scope:hestia
```

### Build Configuration

The standard build configuration:

```json
{
  "build": {
    "executor": "@nx/js:tsc",
    "outputs": ["{options.outputPath}"],
    "options": {
      "outputPath": "dist/libs/hestia/core",
      "main": "libs/hestia/core/src/index.ts",
      "tsConfig": "libs/hestia/core/tsconfig.lib.json",
      "assets": []
    }
  }
}
```

Build output goes to `dist/libs/hestia/<library>/`.

---

## Testing

### Run Tests for a Single Library

```bash
pnpm nx test @hestia/core
```

### Run All Domain Tests

```bash
pnpm nx run-many --target=test --projects=tag:scope:hestia
```

### Watch Mode

```bash
npx vitest --config libs/hestia/recipes/vitest.config.ts --watch
```

### Test Configuration

Hestia libraries use a vitest configuration with `root` set to `__dirname`:

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    root: __dirname,
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

### Coverage

```bash
npx vitest --config libs/hestia/recipes/vitest.config.ts --coverage
```

### Testing Patterns

**Recipe scaling tests** should verify that ingredient quantities scale
correctly for different serving sizes, including edge cases for non-linear items
(eggs, seasoning):

```typescript
describe('scaleRecipe', () => {
  it('doubles ingredient quantities for double servings', () => {
    const original = { flour: { amount: 2, unit: 'cup' } };
    const scaled = scaleIngredients(original, 2);
    expect(scaled.flour.amount).toBe(4);
  });

  it('handles egg scaling with rounding', () => {
    const original = { eggs: { amount: 3, unit: 'piece' } };
    const scaled = scaleIngredients(original, 1.5);
    expect(scaled.eggs.amount).toBe(5); // rounds 4.5 up
  });
});
```

**Flavor compound pairing tests** should verify that complementary ingredient
recommendations are based on actual compound overlap analysis:

```typescript
describe('flavorPairing', () => {
  it('pairs tomato and basil based on shared compounds', () => {
    const score = scoreFlavorPairing('tomato', 'basil');
    expect(score).toBeGreaterThan(0.7);
  });
});
```

**Nutrition analysis tests** should verify calorie and macronutrient
calculations against known USDA FoodData Central reference values.

**Bioavailability tests** should verify that nutrient absorption modifiers are
correctly applied (e.g., vitamin C enhancing iron absorption, phytates
inhibiting zinc uptake).

**Allergen detection tests** should verify detection of all major allergen
groups including hidden allergens in processed ingredients.

**Timer management tests** should verify concurrent timer handling, including
conflict detection when multiple timers overlap.

**HACCP compliance tests** in `@hestia/professional` should verify that critical
control points are correctly identified and that temperature logs meet audit
requirements.

**Smart kitchen device tests** should mock the device communication layer and
verify that cooking programs, temperature profiles, and automation rules execute
correctly.

---

## Linting

### Lint a Single Library

```bash
pnpm nx lint @hestia/recipes
```

### Lint All Hestia Libraries

```bash
pnpm nx run-many --target=lint --projects=tag:scope:hestia
```

---

## Common Development Tasks

### Adding a New Library

1. Create the directory:

```bash
mkdir -p libs/hestia/new-library/src
```

2. Create `project.json`:

```json
{
  "name": "@hestia/new-library",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/hestia/new-library/src",
  "projectType": "library",
  "tags": ["scope:hestia", "layer:domain", "type:lib"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/hestia/new-library",
        "main": "libs/hestia/new-library/src/index.ts",
        "tsConfig": "libs/hestia/new-library/tsconfig.lib.json",
        "assets": []
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "options": {
        "lintFilePatterns": ["libs/hestia/new-library/**/*.ts"]
      }
    },
    "test": {
      "executor": "@nx/vite:test",
      "options": {
        "config": "libs/hestia/new-library/vitest.config.ts"
      }
    }
  }
}
```

3. Create `package.json`:

```json
{
  "name": "@hestia/new-library",
  "version": "0.0.1",
  "type": "module",
  "main": "./src/index.ts",
  "types": "./src/index.ts",
  "peerDependencies": {
    "@hestia/core": "workspace:*"
  },
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

4. Create `vitest.config.ts`:

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    root: __dirname,
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

5. Create `src/index.ts` as a barrel export.

6. The `tsconfig.base.json` maps `"@hestia/*": ["libs/hestia/*/src/index.ts"]`
   so no additional path mapping is needed.

7. Run `pnpm install`.

### Working with the Core Foundation

`@hestia/core` uses pure TypeScript interfaces with validation functions rather
than Zod runtime schemas. This is a deliberate design choice for zero runtime
dependencies:

```typescript
// Measurement units defined as const objects
export const MeasurementUnit = {
  // US customary
  tsp: 'tsp',
  tbsp: 'tbsp',
  cup: 'cup',
  fl_oz: 'fl_oz',
  // ... metric, informal
} as const;

export type MeasurementUnit =
  (typeof MeasurementUnit)[keyof typeof MeasurementUnit];
```

The `@hestia/core` barrel export provides five modules:

```typescript
export * from './schemas.js'; // Pure TS interfaces + validation functions
export * from './db-schema.js'; // Drizzle ORM table definitions
export * from './types.js'; // Domain type definitions
export * from './events.js'; // Domain event definitions
export * from './auth.js'; // Authentication utilities
```

### Adding a New Cuisine Module

To add a new cuisine to `@hestia/education`:

1. Create a sub-module under `libs/hestia/education/src/cuisine/`
2. Define the cuisine's essential techniques, pantry staples, and signature
   dishes
3. Link techniques to the technique progression system
4. Add integration with `@hestia/ingredients` for cuisine-specific ingredient
   profiles

### Adding a New Smart Kitchen Device

To add a new device type to `@hestia/smart-kitchen`:

1. Add the device type definition to the appropriate sub-module (cooking
   devices, sensors, or smart appliances)
2. Implement the device protocol adapter
3. Define cooking programs or sensor profiles for the device
4. Add automation triggers for the device to the orchestration layer
5. Add tests with mock device communication

---

## Key Patterns and Conventions

### Zero Runtime Dependencies in Core

`@hestia/core` is distinctive in the Oshun monorepo because it has zero runtime
dependencies. All schemas use pure TypeScript interfaces with manual validation
functions instead of Zod:

```json
{
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

This keeps the core foundation lightweight and eliminates any runtime overhead
from validation libraries.

### Pure TypeScript Validation

Instead of Zod schemas, Hestia uses const objects with derived type unions:

```typescript
export const CookingMethod = {
  bake: 'bake',
  roast: 'roast',
  broil: 'broil',
  grill: 'grill',
  saute: 'saute',
  fry: 'fry',
  deep_fry: 'deep_fry',
  stir_fry: 'stir_fry',
  steam: 'steam',
  boil: 'boil',
  simmer: 'simmer',
  // ...more methods
} as const;

export type CookingMethod = (typeof CookingMethod)[keyof typeof CookingMethod];
```

This pattern provides both runtime values (for iteration and lookup) and
compile-time types (for type checking).

### Flat Dependency Graph

Unlike domains with layered dependencies, Hestia uses a flat graph where every
library depends solely on `@hestia/core`. This design simplifies the build order
and allows libraries to be developed independently.

### ESM Module System

All libraries use ESM (`"type": "module"`). Import paths use `.js` extensions:

```typescript
export * from './schemas.js';
export * from './db-schema.js';
export * from './types.js';
```

### Peer Dependency Pattern

All non-core libraries use `@hestia/core` as a peer dependency:

```json
{
  "peerDependencies": {
    "@hestia/core": "workspace:*"
  }
}
```

### Project Tags

```json
["scope:hestia", "layer:domain", "type:lib"]
```

### Package Versioning

`@hestia/core` uses version `0.1.0` while some newer libraries like
`@hestia/smart-kitchen` use `0.0.1`. Both are marked private.

---

## Debugging Tips

### TypeScript Path Resolution

The `tsconfig.base.json` maps `"@hestia/*": ["libs/hestia/*/src/index.ts"]`. If
imports fail:

1. Verify the library has a valid `src/index.ts`
2. Run `pnpm install` to refresh workspace links
3. Check that `tsconfig.json` extends `../../../tsconfig.base.json`

### Unit Conversion Precision

Recipe scaling involves unit conversions that can introduce floating-point
errors. Use `toBeCloseTo` for numeric comparisons in scaling tests:

```typescript
expect(converted.amount).toBeCloseTo(expectedAmount, 2);
```

### Measurement System Edge Cases

When testing unit conversions, pay attention to:

- Informal units (`pinch`, `dash`) that do not have exact metric equivalents
- Non-linear scaling items (eggs, seasoning)
- Volume-to-weight conversions that depend on ingredient density

### Smart Kitchen Device Communication

When testing device integration, mock all network communication. Real device
tests should be in dedicated integration test suites that run separately from
unit tests.

### Nx Cache Issues

```bash
pnpm nx reset
```

### Viewing the Dependency Graph

```bash
pnpm nx graph --focus=@hestia/core
```

---

## Quick Reference

| Action                     | Command                                                       |
| -------------------------- | ------------------------------------------------------------- |
| Install dependencies       | `pnpm install`                                                |
| Build one library          | `pnpm nx build @hestia/<lib>`                                 |
| Build all Hestia libraries | `pnpm nx run-many --target=build --projects=tag:scope:hestia` |
| Test one library           | `pnpm nx test @hestia/<lib>`                                  |
| Test all Hestia libraries  | `pnpm nx run-many --target=test --projects=tag:scope:hestia`  |
| Lint one library           | `pnpm nx lint @hestia/<lib>`                                  |
| Lint all Hestia libraries  | `pnpm nx run-many --target=lint --projects=tag:scope:hestia`  |
| Reset Nx cache             | `pnpm nx reset`                                               |
| View dependency graph      | `pnpm nx graph --focus=@hestia/core`                          |
