# Demeter — Architecture

> Agriculture, home gardening, and environmental intelligence domain. Named
> after the Greek goddess of the harvest, agriculture, and the seasons.

---

Demeter is the Oshun platform's home gardening and small-scale urban agriculture
domain. It solves the problem of fragmented gardening knowledge: a gardener
today must juggle plant encyclopedias, weather apps, IoT sensor dashboards, food
safety references, and paper journals, none of which talk to each other. Demeter
unifies all of these into a single, coherent platform that connects botanical
science, real-world climate standards, sensor data, and preservation safety
guidelines through a common data model.

The domain is used by home gardeners, urban agriculture enthusiasts, hobbyist
hydroponic and aquaponic growers, and community garden organizers. The web and
mobile applications surface the full feature set; the Fastify REST API exposes
the domain's capabilities over HTTP.

---

## 1. Domain Summary

Demeter is a home gardening and urban agriculture platform built from **14
libraries plus 3 applications** (`@demeter/api` — a Fastify REST API,
`@demeter/web` — a React/Vite SPA, and `@demeter/mobile` — a React Native/Expo
app). The libraries are the domain logic layer; the applications consume
`@demeter/core` for shared schema and types. The platform spans from plant
science databases and soil analysis through to IoT sensor networks, automation
systems, and community gardening features.

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 rather than being optional extensions.

---

## 2. Component Topology

The diagram below shows how the 14 libraries depend on each other. All roads
lead to `@demeter/core` at the foundation. The intelligence and analytics layers
sit at the top, consuming outputs from every layer beneath them. Notice that
`@demeter/planner` is the only non-core library that peers on another feature
library (`@demeter/plants`) — it needs companion planting data during layout
design.

```
                @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)
```

---

## 3. Layer Architecture

The 14 libraries are organized into five conceptual layers, progressing from
foundational data types up through operational features and intelligence.

### Layer 1 — Foundation: `@demeter/core`

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

**30 schemas** comprise 10 enumerations (`PlantTypeSchema`,
`PlantLifecycleSchema`, `GrowthStageSchema`, `SoilTypeSchema`, `TaskTypeSchema`,
`SensorTypeSchema`, `IrrigationTypeSchema`, `GardenTypeSchema`,
`PestTypeSchema`, `TreatmentTypeSchema`), 10 value objects (`ClimateZoneSchema`,
`GeoLocationSchema`, `SoilCompositionSchema`, `SunExposureSchema`,
`WaterRequirementSchema`, `TemperatureRangeSchema`, `GrowingConditionsSchema`,
`PlantSpacingSchema`, `HarvestWindowSchema`, `NutrientProfileSchema`), and 10
entities (`GardenSchema`, `GardenBedSchema`, `PlantSchema`, `PlantingSchema`,
`HarvestSchema`, `TaskSchema`, `ObservationSchema`, `SensorSchema`,
`AlertSchema`, `UserSchema`).

All schemas use Zod with full validation rules. TypeScript types are inferred
from schemas providing compile-time safety from the same source as runtime
validation.

**Database schema** (`db-schema`) defines 20 PostgreSQL enums, 17 tables (all
`demeter_`-prefixed), and Drizzle `relations()` for every table.

**Seed data** (`db-seed`) pre-populates sample users, gardens, beds, 32 plants
with full botanical data, plantings, tasks, observations, and harvests.

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

### Layer 2 — Data Sources

These three libraries bring external knowledge and real-world data into the
platform. They have no dependencies on each other — each peers only on
`@demeter/core`.

**`@demeter/plants`** (7 sub-modules)

The plant encyclopedia is the most data-rich library. It ships with four
pre-built databases (`VEGETABLE_DATABASE`, `HERB_DATABASE`, `FRUIT_DATABASE`,
`FLOWER_DATABASE`). Companion planting implements relationship scoring using
documented mechanisms. The climate zone system implements three classification
systems (USDA, Koppen, AHS) and computes growing degree days, chill hours, and
growing season length.

**`@demeter/weather`** (7 sub-modules)

Weather integration with multi-source adapter abstraction. Growing degree day
tracking ties weather data to plant development prediction. Garden-specific
alerts fire based on forecast thresholds relevant to gardening activities.

**`@demeter/sensors`** (6 sub-modules)

IoT sensor platform supporting MQTT, Zigbee, BLE, and LoRa. Time-series
analytics provide aggregation and anomaly detection on sensor data streams.
Calibration management tracks sensor drift over time.

### Layer 3 — Operations

These four libraries act on the data sources layer: they use plant knowledge,
weather readings, and sensor data to drive decision-making, layout planning, and
growing management.

**`@demeter/automation`** (6 sub-modules)

Rule-based automation engine with multi-condition triggers. Smart irrigation
scheduling is weather-adjusted: if significant rain is forecast, scheduled
irrigation is suppressed. Greenhouse climate control responds to sensor readings
within configured setpoint ranges.

**`@demeter/hydroponics`** (7 sub-modules)

The most technically complex library, covering seven hydroponic system types
plus aquaponics, indoor growing, microgreens, and mushroom cultivation. Each
growing methodology has its own calculation engine (EC/TDS management, VPD
calculation, nitrogen cycle modeling, biological efficiency tracking).

**`@demeter/inventory`** (5 sub-modules)

Comprehensive inventory management for seeds, plants, and supplies. Seed
viability tables model germination rate decline over time. Seed saving guides
calculate isolation distances and minimum viable populations.

**`@demeter/planner`** (7 sub-modules)

The garden planning library is notable for having a second peer dependency: it
peers on both `@demeter/core` and `@demeter/plants` for companion planting data
during layout design. This is the only cross-library dependency in the feature
layer. The sun and shadow analysis module computes solar position and structure
shadows to generate DLI heatmaps for bed placement optimization.

### Layer 4 — Recording

These two libraries capture what actually happens in the garden over time,
creating the historical record that Layer 5 analytics and intelligence consume.

**`@demeter/journal`** (6 sub-modules)

Observation logging with photo management and growth stage tracking. Harvest
logging with yield data. AI-powered insights surface patterns across journal
history.

**`@demeter/preservation`** (8 sub-modules)

Food preservation library following USDA and NCHFP guidelines. The canning
module enforces altitude-adjusted processing times and includes botulism risk
assessment. Fermentation tracks pH for safety assessment.

### Layer 5 — Intelligence and Community

The top layer consumes data and records from all layers below it to provide
scheduling, social features, aggregated analytics, and ML-powered intelligence.

**`@demeter/tasks`** (6 sub-modules)

Task scheduling with automated task generation from garden plans. iCal export
enables integration with external calendar applications. Weather-aware
prioritization suggests rescheduling outdoor tasks when weather is unfavorable.

**`@demeter/community`** (6 sub-modules)

Social platform with location-based features (haversine distance search for
nearby gardeners, local market directories). Expert network includes
consultation booking and workshop management. Seed exchange marketplace includes
wishlist-to-match detection.

**`@demeter/analytics`** (7 sub-modules)

Aggregated analytics covering yield, cost, resource consumption, environmental
impact, and time efficiency. Dashboard reporting provides a unified view across
growing seasons.

**`@demeter/intelligence`** (8 sub-modules)

ML layer for plant identification, disease detection, pest identification, and
growth prediction. Personalized recommendations synthesize historical garden
data. Natural language interface answers garden queries in plain English.

---

## 3a. Application Layer

Three applications sit on top of the library layer and each serves a different
interaction context.

**`@demeter/api`** — a Fastify REST API. `buildServer()` registers plugins in a
fixed order (request-context, CORS, error-handler, Swagger, auth, database,
Redis, rate-limit, routes). It uses Drizzle on a `pg.Pool` for PostgreSQL and
ioredis for caching, rate-limiting, and sessions. Authentication supports
email/password (bcrypt), refresh-token rotation with family-based theft
detection, OAuth2 (Google/Apple/Facebook), magic links, and IoT API keys. A
five-role RBAC model (`owner > admin > member > viewer`, plus `iot_device`) with
12 fine-grained permissions, plus resource-ownership middleware, gates the
routes. REST routes are versioned under `/v1` and cover gardens, plants,
plantings, tasks, harvests, sensors, weather, observations, AI, and community.

**`@demeter/web`** — a React single-page app built with Vite, React Router v6,
TanStack Query, Zustand, Tailwind CSS, and Recharts. It ships ~62 page
components and includes a 2D and a 3D garden planner. End-to-end tests use
Playwright.

**`@demeter/mobile`** — a React Native app on Expo SDK 52 with React Navigation,
TanStack Query, and Zustand. It ships ~50 screens and adds an offline subsystem
(action queue, conflict resolution, sync engine, caches) and a widgets layer
(Siri Shortcuts, Google Assistant, Watch, quick actions).

---

## 4. Dependency Graph

All 13 feature libraries peer on `@demeter/core`. The one exception to this flat
structure is `@demeter/planner`, which also peers on `@demeter/plants` because
garden layout design requires companion planting compatibility data at planning
time.

```
@demeter/core (standalone: drizzle-orm, zod)
  |
  +-- @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)
```

The only non-core dependency in the feature layer is `@demeter/planner` peering
on `@demeter/plants`.

---

## 5. Design Patterns

### Real-World Data Integration

Demeter is distinguished by the depth of real-world standards integration. These
are not reference data displayed for informational purposes — they drive
algorithmic decisions (is this plant suitable for this zone? what processing
time is required at this altitude?):

- USDA Hardiness Zones (zones 1a–13b with exact temperature ranges)
- Koppen climate classifications (A, B, C, D, E groups with sub-types)
- AHS Heat Zone Map (number of heat days above 30°C)
- NCHFP food safety guidelines (mandatory altitude adjustment in canning)
- Growing degree day (GDD) base temperature formulas per crop type

### IoT Protocol Abstraction

The sensor library provides protocol-agnostic device registration and reading
storage. Protocol-specific adapters (MQTT, Zigbee, BLE, LoRa) implement a common
interface, allowing garden owners to mix sensor technologies without the rest of
the platform needing to know which protocol each device uses. A sensor reading
from a LoRa field sensor and a reading from a Bluetooth pot sensor are handled
identically by the analytics layer.

### Safety-First Preservation

The preservation library treats food safety as a first-class constraint, not an
advisory. This distinction matters: a system that merely displays USDA
guidelines leaves safety decisions to the user, whereas Demeter actively
enforces them. Canning recipes that do not meet NCHFP pH or pressure standards
are flagged with risk assessments. Botulism risk assessment is built into the
water bath canning workflow. Fermentation pH is tracked against documented
safety thresholds.

---

## 6. Technology Stack

The table below summarizes the technology choices across the domain. The
consistent use of Zod schemas as the single source of truth for both runtime
validation and TypeScript types is a key architectural decision: it ensures that
the 30 `@demeter/core` schemas govern both what the database accepts and what
TypeScript enforces at compile time.

| Component     | Technology                                                                    |
| ------------- | ----------------------------------------------------------------------------- |
| Language      | TypeScript (ESM)                                                              |
| Validation    | Zod (30 schemas in `@demeter/core`)                                           |
| ORM           | Drizzle ORM                                                                   |
| Database      | PostgreSQL                                                                    |
| Cache         | Redis (ioredis)                                                               |
| API framework | Fastify (`@demeter/api`)                                                      |
| Web client    | React + Vite + React Router + TanStack Query + Zustand                        |
| Mobile client | React Native (Expo SDK 52) + React Navigation                                 |
| Library build | `@nx/js:tsc`                                                                  |
| Testing       | Vitest (libraries, API, web); Jest/`jest-expo` (mobile); Playwright (web e2e) |
| Food safety   | USDA and NCHFP guidelines                                                     |
| Climate data  | USDA zones, Koppen classification, AHS heat zones                             |

---

## 7. Project Configuration

- **Project tags**: `["scope:demeter", "layer:domain", "type:lib"]`
- **Module format**: ESM (`"type": "module"`)
- **Build executor**: `@nx/js:tsc`

### Common Build Commands

The following commands assume the monorepo root as the working directory and
rely on Nx project tags to target all Demeter packages at once.

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

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

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

# Lint a library
pnpm nx lint @demeter/plants
```

---

## 8. Related Domains

Demeter is deliberately scoped to home and small-scale gardening. Four other
domains handle adjacent concerns; understanding these boundaries prevents
feature duplication.

| Domain | Relationship                                                                         |
| ------ | ------------------------------------------------------------------------------------ |
| Hestia | Seasonal ingredient sourcing alignment; post-harvest preservation techniques overlap |
| Asase  | Commercial agricultural operations intelligence — Demeter scopes home/small-scale    |
| Airmid | Botanical / phytotherapy intelligence — Demeter scopes growing, not therapeutic use  |
| Gaia   | Sovereign weather and climate ML source consumed for advanced forecasts              |

The Hestia boundary is additive: Demeter produces a harvest and tracks
preservation; Hestia picks up from there to handle cooking, meal planning, and
ingredient sourcing. Data crosses the boundary in the form of yield records and
preserved produce inventory. Asase handles the same agricultural domain at
commercial scale — Demeter intentionally does not model commodity pricing, farm
operations management, or supply chain logistics. Airmid overlaps on botanical
knowledge but diverges on purpose: Demeter knows how to grow a plant, Airmid
knows its therapeutic properties and clinical applications. Gaia owns weather
model generation and forecast skill verification; Demeter consumes Gaia's
products for garden-specific alerts (frost warnings, GDD enrichment, irrigation
timing) without duplicating forecast infrastructure.
