# Demeter Domain

> **Demeter** - Agriculture, Home Gardening, and Environmental Intelligence

Library-only domain providing a comprehensive home gardening and urban
agriculture platform covering plant encyclopedias, companion planting, pest and
disease databases, climate zone intelligence, IoT sensor integration, garden
automation, hydroponic and aquaponic systems, food preservation (USDA/NCHFP
compliant), community gardening, task management, and AI-driven agricultural
intelligence. Named after the Greek goddess of the harvest.

---

## Overview

The Demeter domain implements a full-stack agricultural technology platform
spanning from plant science databases and soil analysis through to IoT sensor
networks, automation systems, and community gardening features. The platform
covers the entire lifecycle of home gardening: planning garden layouts with
sun/shadow analysis, selecting and sourcing plants, monitoring growing
conditions through sensor networks, managing tasks and schedules, harvesting,
and post-harvest preservation. Integration with real-world data systems is a
core design principle: USDA hardiness zones, Koppen climate classifications, AHS
heat zones, NCHFP food safety guidelines, and growing degree day calculations
all drive the platform's intelligence. Advanced growing methods (hydroponics,
aquaponics, indoor growing, microgreens, mushroom cultivation) extend the
platform beyond traditional soil gardening. The community layer provides seed
exchanges, expert networks, local resource directories, and social content
sharing.

---

## Architecture

```
                    @demeter/intelligence
                    (ML: plant ID, disease, pest, prediction)
                         |
         +---------------+---------------+
         |               |               |
    @demeter/analytics  @demeter/community  @demeter/tasks
    (yield, cost,       (profiles, exchange, (scheduling,
     resource, env)      groups, experts)    calendar, notif)
         |               |               |
         +-------+-------+-------+-------+
                 |               |
    @demeter/preservation   @demeter/journal
    (canning, freezing,     (observations,
     drying, ferment)       photos, harvest)
                 |               |
         +-------+-------+-------+
         |       |       |       |
    planner  automation  hydroponics  inventory
    (layout,  (rules,    (NFT/DWC,   (seeds,
     sun,     irrigation, aquaponics,  suppliers,
     rotation) climate)   mushrooms)   tools)
         |       |       |       |
         +-------+-------+-------+
                 |
         +-------+-------+
         |       |       |
      plants   weather  sensors
      (species, (forecast,(MQTT,Zigbee,
       companion,GDD,     BLE,LoRa,
       pests)   alerts)   timeseries)
                 |
            @demeter/core
        (Zod schemas, Drizzle ORM,
         domain types, seed data)
```

### Layer Summary

1. **Core** - 30 Zod validation schemas covering the full domain model (plants,
   gardens, soil, weather, pests, sensors), Drizzle ORM database schema, type
   inference, and seed data
2. **Data** - Plant encyclopedias with companion planting intelligence, weather
   integration with GDD tracking, and IoT sensor protocol adapters
3. **Planning** - Garden layout design with sun analysis, crop rotation, and
   succession planting; automation rules engine; hydroponic/aquaponic system
   management; seed and supply inventory
4. **Recording** - Garden journaling with photo management and growth tracking;
   post-harvest preservation with USDA/NCHFP compliance
5. **Social** - Community profiles, seed/plant exchanges, expert networks, local
   resource directories, analytics dashboards, and AI intelligence

---

## Libraries (14)

### `@demeter/core` - Core Foundation

Core domain types, Zod validation schemas, Drizzle ORM database schema, and seed
data for the entire Demeter platform.

**Key exports:** `schemas` (30 Zod schemas with full validation rules),
`db-schema` (Drizzle ORM tables), `db-seed` (initial data seeding)

The schema layer defines 30 comprehensive schemas including `PlantTypeSchema`
(vegetable, fruit, herb, flower, tree, shrub, vine, grass, succulent, fern),
`PlantLifecycleSchema` (annual, biennial, perennial), plus schemas for gardens,
beds, plantings, soil tests, weather readings, pest observations, sensor
devices, and more. All schemas use Zod with full validation rules and export
inferred TypeScript types.

**Dependencies:** `drizzle-orm`, `zod`

### `@demeter/plants` - Comprehensive Plant Encyclopedia

A complete plant knowledge base with seven sub-modules.

**Species and data models** define `PlantSpecies`, `PlantVariety`,
`PlantTaxonomy`, `GrowingRequirements`, `PlantingInstructions`, `CareGuide`,
`HarvestInfo`, `NutritionalInfo`, `CulinaryUses`, and `MedicinalUses` types with
CRUD operations and search.

**Companion planting** provides a full companion database with relationship
scoring, guild planting suggestions, Three Sisters layout generation, bed
compatibility checking, and companion chart generation. Companion types include
beneficial and detrimental relationships with documented mechanisms.

**Pest and disease database** includes `PEST_DATABASE`, `DISEASE_DATABASE`, and
`BENEFICIAL_INSECTS` collections with pest identification, treatment
recommendations, and IPM (Integrated Pest Management) plan generation.

**Climate zone system** implements USDA hardiness zones, Koppen climate
classifications, AHS heat zones, and frost date lookups. Calculations include
growing season length, growing degree days (GDD), chill hours, hardiness
checking, zone-based plant filtering, and microclimate estimation.

**Seasonal calendar** provides planting calendars, seed start schedules,
transplant schedules, succession schedules, fall planting calendars, moon phase
calculation, and moon planting advice. Printable calendar generation is
included.

**Search and discovery** offers fuzzy name search, faceted search with counts,
similar plant recommendations, beginner suggestions, pollinator plant
suggestions, edible landscaping recommendations, and nutrition-based search.

**Plant databases** ship with `VEGETABLE_DATABASE`, `HERB_DATABASE`,
`FRUIT_DATABASE`, and `FLOWER_DATABASE` pre-built collections.

**Peer dependencies:** `@demeter/core`

### `@demeter/weather` - Weather Integration

Comprehensive weather data management providing seven sub-modules: data source
adapters, current conditions analysis, forecasting, weather alerts, historical
data, growing degree day tracking, and garden-specific weather integration that
ties weather events to gardening actions.

**Peer dependencies:** `@demeter/core`

### `@demeter/sensors` - IoT Sensor Integration

IoT sensor platform supporting multiple protocols and device lifecycle
management.

**Devices** provides device registration, discovery, and lifecycle management.

**Protocols** implements adapters for MQTT, Zigbee, BLE (Bluetooth Low Energy),
and LoRa, enabling integration with a wide range of garden sensors (soil
moisture, temperature, humidity, light, pH).

**Readings** handles sensor data collection with validation and normalization.

**Timeseries** provides time-series analytics for sensor data including
aggregation, trend detection, and anomaly identification.

**Calibration** manages sensor calibration workflows and drift correction.

**Integrations** connects to commercial sensor platforms and garden monitoring
products.

**Peer dependencies:** `@demeter/core`

### `@demeter/automation` - Garden Automation and Rules Engine

Rule-based automation system for garden operations.

**Rules** implements a condition/action rules engine supporting complex triggers
(sensor thresholds, time schedules, weather conditions).

**Irrigation** provides smart irrigation scheduling with weather-adjusted
watering, zone control, and moisture-based activation.

**Climate control** manages greenhouse climate including ventilation, heating,
cooling, and humidity regulation.

**Alerts** generates notifications for critical conditions (frost warnings, high
temperatures, dry soil, pest detections).

**Scenes** supports predefined automation scenarios (nighttime frost protection,
morning watering, greenhouse ventilation).

**History** logs all automation actions for auditing and optimization.

**Peer dependencies:** `@demeter/core`

### `@demeter/hydroponics` - Advanced Growing Systems

Comprehensive library spanning six growing methodologies.

**Systems** manages hydroponic system configurations including NFT (Nutrient
Film Technique), DWC (Deep Water Culture), ebb and flow, drip, aeroponic, Kratky
(passive), and wick systems. Includes system templates, setup guides, component
management, cost estimation, power consumption calculation, and system
comparison.

**Nutrients** provides EC/TDS range management per growth stage, pH adjustment
calculations, nutrient lockout detection, deficiency symptom diagnosis, brand
profiles (General Hydroponics, Advanced Nutrients, etc.), mixing recipe
calculation, and purchase list generation.

**Reservoir** handles water level monitoring, temperature control, pH
auto-dosing commands, evaporation rate calculation, cleaning schedules,
maintenance reminders, anomaly detection, and trend analysis.

**Aquaponics** implements a fish species database with compatibility checking,
feeding calculations, nitrogen cycle monitoring, water quality assessment,
fish-to-plant ratio balancing, stocking density management, disease diagnosis,
and balance reporting.

**Indoor growing** covers grow light selection (LED, HPS, CMH), VPD (Vapor
Pressure Deficit) calculation, DLI (Daily Light Integral) calculation,
photoperiod scheduling, CO2 supplementation planning, grow tent sizing, and
electricity cost estimation.

**Microgreens** manages tray lifecycle, variety database with difficulty
ratings, seed density calculation, production scheduling, cost analysis, and
profitability ranking.

**Mushrooms** provides a species database covering oyster, shiitake, lion's
mane, reishi, and more. Includes substrate recipe management, spawn
calculations, colonization timeline estimation, biological efficiency tracking,
contamination identification, and growing guide generation. Separates culinary
and medicinal species.

**Peer dependencies:** `@demeter/core`

### `@demeter/inventory` - Seed and Supply Management

Five-module inventory system for gardening supplies.

**Seed inventory** tracks seed lots with viability tables, germination rate
estimation, expiration monitoring, needs calculation from garden plans, shopping
list generation, and cost tracking.

**Supplier tracking** maintains a supplier database with ratings, germination
tracking by supplier, price comparison, order history, and wishlist-to-order
conversion.

**Seed saving** provides saving guides with difficulty ratings, isolation
distance calculation, minimum population requirements, saving calendars, lineage
tracking, success rate calculation, and yield estimation.

**Plant inventory** manages live plant items with status tracking, hardening-off
schedules with day-by-day progression, propagation recording with success rates,
planting readiness checks, and nursery spending calculation.

**Supply and tool inventory** handles consumable supplies (soil, fertilizer,
mulch) with reorder alerts and usage rate analysis, plus durable tools with
maintenance scheduling, lending/return tracking, and cost analysis.

**Peer dependencies:** `@demeter/core`

### `@demeter/planner` - Garden Planning and Design

Comprehensive garden layout and planning system with seven sub-modules.

**Layout engine** provides a canvas-based garden designer with element
manipulation (add, remove, move, rotate, resize, copy), grid snapping, layer
management, undo/redo history, and area calculations. Supports bed shapes,
paths, structures, and water features.

**Plant placement** implements square-foot gardening grids, row planting
calculations, spacing validation, companion compatibility checking, mature size
overlap detection, and vertical space planning.

**Sun and shadow analysis** calculates solar position, sunrise/sunset times,
daylength, structure and tree shadows, daily light integral, sun exposure
classification into light zones, sun heatmap generation, and optimal bed
placement recommendations.

**Crop rotation** manages plant family groups with soil impact tracking,
four-year rotation plan generation and validation, next crop suggestions,
nitrogen balance tracking, cover crop planning, perennial accounting, and
rotation schedule generation.

**Succession planting** calculates sowing intervals, creates succession plans,
determines seed quantities, plans fall successions, generates harvest timelines,
tracks actual vs. planned performance, and suggests succession crops with yield
estimates.

**Garden templates** provides a template library with filtering by difficulty,
zone, and garden type, plus custom template creation and template instantiation.

**Export** generates plant shopping lists, seed order lists, materials lists,
planting calendars, bed labels, plan summaries, cost estimates, and task lists
from garden plans. Supports JSON import/export.

**Peer dependencies:** `@demeter/core`, `@demeter/plants`

### `@demeter/journal` - Garden Journaling and Observations

Garden journaling library for recording observations, tracking growth, managing
photos, logging harvests, searching entries, and generating AI-powered insights.
Six sub-modules cover the complete journaling workflow from daily observations
through seasonal analysis.

**Peer dependencies:** `@demeter/core`

### `@demeter/preservation` - Post-Harvest Preservation

Comprehensive food preservation library following USDA/NCHFP safety guidelines.
Eight sub-modules cover the entire preservation workflow.

**Harvest planning** forecasts yields using a crop yield database, predicts peak
harvest windows, assesses preservation needs, schedules preservation sessions,
calculates container requirements, and generates prep checklists.

**Canning** implements water bath and pressure canning with altitude-adjusted
processing times and pressures. Includes recipe scaling, acid addition
calculation, batch management with seal checking, jar inventory tracking (sizes,
mouths), lid reorder monitoring, safety checks, label generation, and botulism
risk assessment.

**Freezing** provides blanching guides by produce type, packing method
selection, freezer item management with FIFO (First In, First Out)
prioritization, expiration alerting, freezer unit management with zone mapping,
and energy cost estimation.

**Dehydrating** covers produce and herb drying with temperature guides,
reconstitution ratios, dried weight calculation, tray rotation management,
drying logs, shelf life estimation, fruit leather recipes, and jerky recipes.

**Fermentation** implements lacto-fermentation, kombucha, and other fermentation
types with recipe databases, batch tracking, tasting notes, temperature
monitoring with alerts, pH reading and safety assessment, milestone tracking,
salt-for-brine calculation, and taste reminders.

**Root cellar storage** manages storage locations with condition monitoring,
compliance checking, spoilage inspection, rotation scheduling, storage loss
tracking, compatibility checking, and location recommendation.

**Recipe integration** connects preserved foods to recipes with category/tag/
ingredient search, harvest-to-recipe matching, batch calculation, shopping list
generation, meal planning, success rate tracking, and recipe import from text.

**Peer dependencies:** `@demeter/core`

### `@demeter/tasks` - Task and Schedule Management

Garden task scheduling library with six sub-modules: task scheduling with
recurrence, automated task generation from garden plans, smart prioritization
based on weather and conditions, iCal calendar integration, notification
management, and task performance analytics.

**Peer dependencies:** `@demeter/core`

### `@demeter/community` - Community Gardening Platform

Comprehensive social gardening platform with six sub-modules.

**Profiles** provides gardener profiles with experience levels, privacy
controls, badge and achievement systems (tiered badges with criteria), garden
statistics, follow/block/mute relationships, activity feeds, milestone tracking,
location- based gardener search with haversine distance, and connection
suggestions.

**Seed and plant exchange** implements a marketplace for seed swaps, plant
divisions, and produce sharing with listing management, location-based search,
messaging threads, exchange history, reputation scoring, wishlists with
automatic match detection, and seasonal trend analytics.

**Groups** supports community garden management with group creation, membership
workflows (join, approve, roles, banning), discussion posts with threaded
replies, events with RSVP tracking, shared resource checkout, garden plot
assignment with waitlists, polls, photo albums, and announcements.

**Expert network** connects gardeners with verified experts through Q&A with
voting and acceptance, consultation booking with time slots, workshop
management, article publishing, expert ratings, response metrics, and automatic
question-to- expert matching.

**Content sharing** enables before/after posts, growth timelines, harvest
celebrations, garden plan sharing with forking, garden tours, tips with ratings,
challenges with entries and voting, content moderation with reporting and
appeals, and trending content feeds.

**Local resources** provides a directory of nurseries, farmers markets, and
extension offices with reviews, inventory listings, promotions, business
claiming, and event listings.

**Peer dependencies:** `@demeter/core`

### `@demeter/analytics` - Agricultural Analytics

Seven-module analytics system covering yield analytics, cost analysis, resource
optimization, environmental impact assessment, time management analytics,
success metrics, and dashboard reporting with aggregated views.

**Peer dependencies:** `@demeter/core`

### `@demeter/intelligence` - ML-Driven Agricultural Intelligence

AI/ML intelligence library with eight sub-modules: plant identification from
images, disease detection and diagnosis, pest identification, growth prediction
modeling, personalized recommendations, anomaly detection in sensor data,
natural language interface for garden queries, and ML model management with
versioning.

**Peer dependencies:** `@demeter/core`

---

## Technology Stack

| Component    | Technology                         |
| ------------ | ---------------------------------- |
| Language     | TypeScript (ESM)                   |
| Runtime      | Node.js                            |
| Build        | Nx with `@nx/js:tsc`               |
| Testing      | Vitest                             |
| Database     | Drizzle ORM (via `@demeter/core`)  |
| Validation   | Zod schemas (30 schemas in core)   |
| IoT          | MQTT, Zigbee, BLE, LoRa            |
| Food Safety  | USDA/NCHFP guidelines              |
| Climate Data | USDA zones, Koppen, AHS heat zones |

---

## Development

```bash
# Test a specific library
pnpm nx test @demeter/core

# Build all Demeter libraries
pnpm nx run-many --target=build --projects=tag:scope:demeter

# Lint a library
pnpm nx lint @demeter/plants

# Run all domain tests
pnpm nx run-many --target=test --projects=tag:scope:demeter
```

### Configuration

- **Project tags:** `["scope:demeter", "layer:domain", "type:lib"]`
- **Build executor:** `@nx/js:tsc`
- All libraries use ESM (`"type": "module"`)
- Core uses `drizzle-orm` and `zod` as direct dependencies
- All other libraries use `@demeter/core` as a peer dependency
- `@demeter/planner` also peers on `@demeter/plants` for companion planting data

### Dependency Graph

```
@demeter/core (standalone)
  |
  +-- @demeter/plants (peer: core)
  |     |
  |     +-- @demeter/planner (peer: core, plants)
  |
  +-- @demeter/weather (peer: core)
  +-- @demeter/sensors (peer: core)
  +-- @demeter/automation (peer: core)
  +-- @demeter/hydroponics (peer: core)
  +-- @demeter/inventory (peer: core)
  +-- @demeter/journal (peer: core)
  +-- @demeter/preservation (peer: core)
  +-- @demeter/tasks (peer: core)
  +-- @demeter/community (peer: core)
  +-- @demeter/analytics (peer: core)
  +-- @demeter/intelligence (peer: core)
```
