# Demeter — Systems Deep Dive

> The `libs/demeter/` area: twenty-seven Nx libraries that make up the domain
> logic of **Demeter, the home-gardening platform** — from the Drizzle/Zod data
> core and a typed REST client up through plant knowledge, garden planning,
> growing-system math, post-harvest preservation, social features, and a
> local-first garden-intelligence layer.

## What this area is

Every library here is a `scope:demeter`, `layer:domain`, `type:lib` Nx project
(see any `libs/demeter/*/project.json`) published under the `@demeter/*` npm
scope — 27 of them, all real implementations, none empty scaffolds. Together
they are the reusable brains of a consumer gardening product: the apps that ship
them live outside this directory (`apps/demeter/api`, `apps/demeter/web`,
`apps/demeter/mobile`, plus a `clients/demeter-python` SDK). The libraries hold
the domain algorithms and data; the apps hold the wiring, persistence, UI, and
native device access.

The area has a deliberate dependency floor. `@demeter/core` owns the data
contracts — Zod validation schemas (`src/schemas.ts`), a Drizzle ORM PostgreSQL
schema of ~29 `demeter_*` tables (`src/db-schema.ts`), and seed data
(`src/db-seed.ts`) — and is the one library that pulls runtime dependencies
(`drizzle-orm`, `zod`). Almost everything else is intentionally **pure and
dependency-free**: the docstrings on `@demeter/biodynamic`,
`@demeter/soil-test`, `@demeter/light-meter`, `@demeter/water-analytics`,
`@demeter/pollinators`, `@demeter/i18n`, `@demeter/monetization`,
`@demeter/household`, `@demeter/data-portability`, `@demeter/accessibility`,
`@demeter/gamification`, and `@demeter/webhooks` all describe themselves that
way, and their `package.json` files declare no runtime deps. The few that touch
`@demeter/core` (e.g. `@demeter/sensors` imports `SensorType`) do so only for
its types.

A consistent architectural seam runs through the area: **domain math and
decision logic live in the library; I/O lives in the app.** The libraries that
talk to the outside world expose typed interfaces and pure builders/parsers
rather than performing the network or hardware calls themselves.
`@demeter/sensors` defines a `ProtocolAdapter` interface for
MQTT/Zigbee/BLE/LoRa but leaves the transport to the host; `@demeter/weather`
and `@demeter/intelligence` model providers (weather APIs, PlantNet, Google
Vision, TFLite, LLMs) as URL builders + response parsers + config types so the
actual `fetch` is injected by the caller. The one library that does own the wire
is `@demeter/api-client`, which uses an injectable `fetch` to implement the two
real Demeter auth modes. This is the same "validate/compute here, fetch there"
boundary the rest of Oshun favours, applied per gardening concern.

The libraries cluster by gardening workflow: a knowledge tier (`plants`,
`biodynamic`, `pollinators`); planning and scheduling (`planner`, `tasks`);
growing systems and their telemetry (`hydroponics`, `sensors`, `automation`,
`light-meter`); agronomy and environment (`soil-test`, `water-analytics`,
`weather`); the harvest-and-after tier (`inventory`, `preservation`, `journal`,
`analytics`); a local-first AI tier (`intelligence`); social and engagement
(`community`, `household`, `gamification`); and cross-cutting platform concerns
(`accessibility`, `i18n`, `monetization`, `data-portability`, `webhooks`,
`api-client`, `core`).

## How it fits the wider system

The consumers are the Demeter applications. `apps/demeter/api` composes the
domain logic over `@demeter/core`'s Drizzle schema and exposes the REST surface;
`apps/demeter/web` and `apps/demeter/mobile` consume the same libraries plus
`@demeter/api-client` to talk to that API; `clients/demeter-python` is a
separate SDK over the same wire. Because the heavy logic is pure and lives in
libraries, it runs identically on the server (Node) and, where useful, on the
client/offline — which is why `@demeter/intelligence` is built around a local
knowledge base and feature-matching, and `@demeter/biodynamic` /
`@demeter/light-meter` derive everything from a date or a raw sensor read.

The boundaries are crisp. These are **product-domain** libraries, not platform
contracts: they depend downward on `@demeter/core` (and on nothing else in the
Oshun graph beyond it), and the app layer depends on them. Anything that needs
credentials, hardware, binary decoding, or live third-party data — store
receipts, EXIF bytes, MQTT sockets, weather/vision/LLM HTTP — is explicitly left
to the app or native layer, with the library providing the typed seam and the
math on either side of it. Walk the "used by" edges on any node below to see
exactly which apps and siblings consume it.

## Entity reference

### @demeter/core

The data foundation of the platform (`libs/demeter/core/src`). It exports three
things from `src/index.ts`: Zod domain/validation **schemas** (`schemas.ts`), a
**Drizzle ORM** PostgreSQL schema (`db-schema.ts`) defining ~29 `demeter_*`
tables — gardens, plants, plantings, harvests, tasks, observations, sensors and
readings, alerts, users, auth (refresh tokens, magic links, API keys, sessions),
membership, and the community/social tables — with `pgEnum` types and Drizzle
`relations`, plus **seed data** (`db-seed.ts`). It is the only library in the
area with runtime dependencies (`drizzle-orm`, `zod`) and the type/source-of-
truth that the API service and several sibling libraries build on.

### @demeter/api-client

A small, dependency-free, typed client for the Demeter REST API
(`libs/demeter/api-client/src/client.ts`). `DemeterClient` uses an injectable
`fetch` (`fetchImpl`) and implements the two real auth modes — Bearer JWT with
transparent one-shot **refresh-token rotation** (on a 401 it calls
`POST /<v>/auth/refresh` once, stores the rotated pair, fires
`onTokensRefreshed`, retries, and throws on a second 401) and machine API keys —
surfacing non-2xx responses as a typed `DemeterApiError`. It exposes typed
resource namespaces (gardens, readings) over the `types.ts` models and is what
the web/mobile apps use to reach `apps/demeter/api`.

### @demeter/plants

The plant encyclopedia and knowledge base (`libs/demeter/plants/src`). Real
curated databases (`VEGETABLE_DATABASE`, `HERB_DATABASE`, `FRUIT_DATABASE`,
`FLOWER_DATABASE` in `database.ts`) plus domain logic across `species.ts`,
`companion.ts` (companion-planting scoring, three-sisters layout, guild
suggestions over a `COMPANION_DATABASE`), `pests.ts` (pest/disease databases and
an IPM planner), `climate.ts` (USDA/Köppen/AHS zone systems, growing-degree-day
and chill-hour math, hardiness checks), `calendar.ts` (seasonal planting/seed-
start/transplant/succession schedules and moon-phase advice), and `search.ts`
(faceted/fuzzy search and recommender helpers). It is the shared reference data
many planning and intelligence libraries reason over.

### @demeter/biodynamic

A pure, dependency-free **biodynamic & lunar gardening calendar**
(`libs/demeter/biodynamic/src`). It implements faithful Meeus solar/lunar
astronomy (`astronomy.ts`: `julianDay`, `sunEclipticLongitude`,
`moonEclipticLongitude`, `lunarPhase`), the Maria Thun Root/Leaf/Flower/Fruit
day-type scheme from the Moon's sidereal constellation including an `ayanamsa`
correction and ascending/descending-Moon logic (`biodynamic.ts`), the
Steiner/Thun `PREPARATIONS` (`preparations.ts`), and activity scheduling with an
explicit scientific⇄biodynamic mode toggle (`scheduling.ts`). Everything derives
from a date, so results are reproducible.

### @demeter/pollinators

Native-plants and pollinator-habitat logic (`libs/demeter/pollinators/src`).
Curated datasets (`data.ts`: `POLLINATOR_SPECIES`, `NATIVE_PLANTS`,
`INVASIVE_BY_REGION`, `NATIVE_SEED_SOURCES`, `MONARCH_WAYSTATION_CRITERIA`)
drive an ecoregion/region native-plant finder (`finder.ts`), a bloom-continuity
calendar and scoring (`bloom.ts`), a pollinator-friendliness score (`score.ts`),
and habitat-certification evaluation — Monarch Waystation and NWF wildlife-
habitat checks, bird-friendly scoring, and region invasive alerts
(`habitat.ts`). It is pure; precise lat/lon→ecoregion GIS and live invasive
feeds are explicitly left to external layers.

### @demeter/planner

The garden planning and design engine (`libs/demeter/planner/src`), the largest
planning library. Modules cover a layout engine with an `UndoRedoHistory` and
grid snapping (`layout.ts`), plant placement including square-foot grids,
companion checks, and mature-size overlap (`placement.ts`), sun/shadow analysis
with sun-position/sunrise/sunset math, structure/tree shadow casting, DLI, and
light-zone heatmaps (`sun-analysis.ts`), crop-rotation planning with 4-year
validation and nitrogen-balance tracking over `ROTATION_GROUPS` (`rotation.ts`),
succession planting (`succession.ts`), a `TEMPLATE_LIBRARY` of garden templates
(`templates.ts`), and export/list generation — shopping lists, calendars, bed
labels, JSON import/export (`export.ts`).

### @demeter/tasks

Garden task and schedule management (`libs/demeter/tasks/src`). It composes
scheduling, automated **task generation** from garden state, smart
**prioritization**, **iCal** calendar integration (`calendar-integration.ts`),
notifications, and task performance **analytics** — each its own module
re-exported from `index.ts`. It turns the plans and conditions other libraries
produce into a concrete, prioritized, calendar-exportable to-do stream.

### @demeter/hydroponics

A comprehensive advanced-growing-systems library
(`libs/demeter/hydroponics/src`, ~11k LOC) for hydroponic, aquaponic, indoor,
microgreen, and mushroom growing. Each module is a real domain calculator plus
curated data: `systems.ts` (`SYSTEM_TEMPLATES`, power/cost estimates,
NFT/DWC/EbbFlow/Drip/Aeroponic/Kratky configs), `nutrients.ts` (EC/TDS
conversion, pH adjustment, nutrient-lockout and deficiency diagnosis, mixing
recipes), `reservoir.ts` (dosing commands, evaporation and water-usage math,
anomaly detection), `aquaponics.ts` (fish/ plant ratios, feed-conversion,
nitrogen-cycle assessment), `indoor-growing.ts` (VPD/DLI/PPFD math, CO₂
supplementation, electricity cost), `microgreens.ts`, and `mushrooms.ts`
(biological-efficiency, substrate recipes, contamination ID).

### @demeter/sensors

The IoT sensor-integration library (`libs/demeter/sensors/src`). It provides
device-lifecycle management (`devices.ts`), a protocol-agnostic adapter layer
(`protocols.ts`) defining a `ProtocolAdapter` interface and typed configs for
MQTT/Zigbee/BLE/LoRa, reading collection and validation (`readings.ts`), time-
series analytics (`timeseries.ts`), calibration (`calibration.ts`), and
commercial-platform integrations (`integrations.ts`). It depends only on
`@demeter/core` types (e.g. `SensorType`); the actual radio/socket transport is
an app-layer implementation of the adapter interface, not bundled here.

### @demeter/automation

A rule-based garden automation engine (`libs/demeter/automation/src`, ~7k LOC).
Modules implement the rules engine (`rules.ts`), smart **irrigation** control
(`irrigation.ts`), greenhouse **climate-control** (`climate-control.ts`), an
**alerts** system (`alerts.ts`), **scenes** for grouped device states
(`scenes.ts`), and execution **history** (`history.ts`). It is the decision
layer that turns sensor readings and conditions into automation actions, paired
with `@demeter/sensors` for input and the app layer for actuation.

### @demeter/light-meter

Phone-based light measurement and horticultural-lighting math
(`libs/demeter/light-meter/src`), pure and dependency-free. `photometry.ts`
converts camera exposure → lux and lux ⇄ PPFD (per light source) and computes
DLI; `logging.ts` integrates PPFD time-series into daily/seasonal DLI rollups;
`placement.ts` recommends plant placement and compares spots against
`REQUIREMENT_MIN_DLI`/`REQUIREMENT_MAX_DLI`; `sunpath.ts` provides clear-sky
solar-declination/day-length/DLI references to validate measurements. The native
layer supplies raw sensor reads; every conversion lives here.

### @demeter/soil-test

Soil-test interpretation and amendment guidance (`libs/demeter/soil-test/src`),
pure agronomy. It classifies USDA soil **texture** and drainage (`texture.ts`),
interprets pH and NPK against `NUTRIENT_RANGES` with deficiency alerts
(`nutrients.ts`), recommends lime/sulfur and other **amendments** toward a
target pH (`amendments.ts`), suggests **cover crops** (`cover-crops.ts`), and
tracks improvement across multiple tests (`history.ts`). External soil-kit/lab
APIs and PDF parsing feed the `SoilTestResult` this library reasons over.

### @demeter/water-analytics

Water usage, harvesting, cost, and conservation math
(`libs/demeter/water-analytics/src`), pure and dependency-free. `usage.ts`
aggregates litres per plant/bed/garden and by source and tracks budget;
`rainwater.ts` computes rainwater-harvest potential (metric and imperial) and
tiered/flat water cost; `conservation.ts` scores drought tolerance and produces
greywater guidance and water-saving recommendations; `restrictions.ts` is a
municipal watering-restriction rule engine (`canWaterAt`). Dashboards and live
municipal data are app/integration layers over these numbers.

### @demeter/weather

The weather-integration library (`libs/demeter/weather/src`, ~16k LOC). It
defines a unified weather data model with multi-provider abstractions, fallback
chains, caching, and normalization (`data-sources.ts`), then layers analysis on
top: current-conditions interpretation, forecasting, alerts, historical data,
**growing-degree-day** tracking (`growing-degree-days.ts`), and garden-specific
weather integration (`garden-weather.ts`). It has no runtime dependencies — the
provider modules are typed seams and normalizers, and the actual weather-API
`fetch` is the app layer's responsibility.

### @demeter/preservation

Post-harvest preservation (`libs/demeter/preservation/src`, ~11k LOC), with
food- safety data following USDA/NCHFP guidance. Modules cover harvest planning
and forecasting over a `CROP_YIELD_DATABASE` (`harvest-planning.ts`);
**canning** with altitude-adjusted processing times/pressures, acid-addition and
botulism- risk logic (`canning.ts`); **freezing** guides, FIFO and energy cost
(`freezing.ts`); **dehydrating** (`dehydrating.ts`); **fermentation** with
brine- salt math and pH-safety assessment (`fermentation.ts`); root-cellar
**storage** (`storage.ts`); and **recipe** integration (`recipes.ts`).
`index.ts` aliases the several modules' colliding `getRecipe`/`scaleRecipe`
exports.

### @demeter/inventory

Seed and supply management (`libs/demeter/inventory/src`). It tracks seed lots
with viability/germination estimation over a `SEED_VIABILITY_TABLE`
(`seeds.ts`), supplier catalogs, ratings, price comparison and order generation
(`suppliers.ts`), seed-saving batches with isolation-distance and minimum-
population math (`seed-saving.ts`), a live plant inventory with hardening-off
schedules and propagation tracking (`plant-inventory.ts`), and garden supplies/
tools with reorder, usage-rate, and maintenance logic (`supplies.ts`).

### @demeter/journal

Garden journaling and observations (`libs/demeter/journal/src`). It records
observations (`observations.ts`), manages photos (`photos.ts`), tracks growth
(`growth-tracking.ts`), logs harvests (`harvest-log.ts`), provides entry search
(`search.ts`), and generates insights (`insights.ts`). It is the longitudinal-
record layer; its data feeds analytics and the intelligence library.

### @demeter/analytics

Cross-cutting gardening analytics (`libs/demeter/analytics/src`, ~9k LOC).
Modules compute yield analytics (`yield-analytics.ts`), cost analysis
(`cost-analysis.ts`), resource optimization (`resource-analytics.ts`),
environmental impact (`environmental-impact.ts`), time management
(`time-analytics.ts`), success metrics (`success-metrics.ts`), and a composed
dashboard (`dashboard.ts`). It turns the records other libraries accumulate
(harvests, water, tasks, costs) into reportable metrics.

### @demeter/intelligence

The local-first garden AI/ML layer (`libs/demeter/intelligence/src`, ~22k LOC,
the largest in the area). It pairs **real local algorithms** with **typed seams
for remote models**: plant identification implements a local text-feature
matcher (`identifyFromDescription` over `PLANT_PROFILES`) alongside PlantNet/
Google Vision/TFLite endpoint builders and response parsers
(`plant-identification.ts`); the NLP interface answers from a 50+-entry local
`KNOWLEDGE_BASE` via intent detection and token similarity, with an `LLMConfig`
seam (`provider: openai | anthropic | local`) and `buildLLMPrompt`/
`buildLLMRequest`/`parseLLMResponse` for an optional hosted model
(`nlp-interface.ts`). It also covers disease/pest detection, growth prediction,
recommendations, anomaly detection, and a model-registry/A-B-test/versioning
layer (`model-management.ts`). The library performs no network calls itself —
remote inference is wired by the app via these seams.

### @demeter/community

A social gardening platform (`libs/demeter/community/src`, ~12k LOC). It is a
broad in-process reference implementation backed by module-level `Map` stores
(e.g. `profileStore`/`badgeStore` in `profiles.ts`, with `resetProfileStores`
and siblings for test isolation), spanning gardener profiles with badges/
milestones and haversine-based nearby search (`profiles.ts`), a seed/plant
exchange marketplace with reputation and wishlists (`exchange.ts`), groups and
community gardens with plots/events/polls (`groups.ts`), an expert network with
Q&A, bookings, workshops, and articles (`experts.ts`), content sharing and
moderation (`content.ts`), and a local-resources business directory
(`local-resources.ts`). The persistent store is the app's concern; this owns the
domain rules.

### @demeter/household

Multi-user / family logic for a shared garden (`libs/demeter/household/src`),
pure and dependency-free. It implements role-based permissions over
`ROLE_PERMISSIONS` (owner/caretaker/viewer/kid) with `can`/`assertCan`
(`roles.ts`), shared task assignment with role validation (`assignments.ts`),
vacation-mode caretaker handoff (`vacation.ts`), a merged activity feed
(`feed.ts`), per-member contribution stats (`contributions.ts`), and preference-
aware notification routing (`notifications.ts`). It mirrors the roles on
`demeter_garden_members` from `@demeter/core`.

### @demeter/gamification

Gardening progression, achievements, and rewards
(`libs/demeter/gamification/src`), pure and dependency-free. It implements
XP/leveling with rank titles (`leveling.ts`), daily-care streaks (`streaks.ts`),
a `BADGES` achievement system (`badges.ts`), skill trees (`skill-trees.ts`),
seasonal challenges and quests (`challenges.ts`), a virtual-currency ledger with
`InsufficientFundsError` (`currency.ts`), tiered leaderboards
(`leaderboard.ts`), share payloads (`sharing.ts`), and a composed progress
dashboard (`stats.ts`). Every function derives from a player's real
stats/activity, so results are reproducible.

### @demeter/accessibility

Color-accessibility utilities (`libs/demeter/accessibility/src`), pure and
dependency-free. `color.ts` provides WCAG contrast math (sRGB↔linear, relative
luminance, `contrastRatio`, `meetsContrast`) for high-contrast modes; `cvd.ts`
implements Machado-2009 color-vision-deficiency simulation matrices
(`CVD_MATRICES`, `simulateCvd`) and perceptual distance/distinguishability;
`palette.ts` ships the Okabe–Ito colorblind-safe palette and CVD-safety
verification. The UI modes themselves (themes, large text, haptics) are app/CSS
layers that consume this color logic.

### @demeter/i18n

Internationalization and localization (`libs/demeter/i18n/src`), pure and
dependency-free. It provides a message-catalog translator with `{var}`
interpolation, Intl plural selection, and locale fallback (`core.ts`,
`catalogs.ts`) with real en/es/fr/de/pt/ja/zh translations; Intl-based number/
date formatting and metric⇄imperial unit conversion/formatting (`format.ts`);
RTL detection and locale negotiation (`locale.ts`); and region→climate-zone/
units/locale profiles (`regions.ts`), which tie localization to gardening
context.

### @demeter/data-portability

Import, export, and an open garden-profile format
(`libs/demeter/data-portability/src`), pure and dependency-free. `format.ts`
defines a versioned `PORTABLE_FORMAT` with serialize/parse; `import.ts` provides
a CSV parser and field-mapped importers for Gardenize/Planta/Garden Planner and
nursery lists (`FIELD_MAPS`); `photos.ts` does EXIF-based photo dating;
`lifecycle.ts` assembles GDPR full-exports, handles account transfer, and runs a
confirmation-gated deletion flow. The import-wizard UI and binary EXIF
extraction are app/native layers over this logic.

### @demeter/monetization

Freemium entitlement, trials, promo codes, and family sharing
(`libs/demeter/monetization/src`), pure and dependency-free. `tiers.ts` holds
the free/Premium/Pro entitlement matrix (`FEATURE_MIN_TIER`, `TIER_PRICING`,
`hasFeature`, `yearlySavings`); `trial.ts` is a deterministic free-trial clock
with reminder timing; `promo.ts` validates promo codes and computes discounts;
`subscription.ts` resolves cross-device entitlement and manages family seats
with a `SeatLimitError`. Store/IAP receipt plumbing is the native layer; the
entitlement and pricing decisions live here.

### @demeter/webhooks

Signed event delivery for third-party integrations
(`libs/demeter/webhooks/src`). `signing.ts` implements HMAC-SHA256 payload
signing and replay-protected verification (`signPayload`, `verifySignature`,
`DEFAULT_TOLERANCE_SECONDS`); `events.ts` defines the `WEBHOOK_EVENT_TYPES`
catalog and endpoint-subscription matching with wildcards
(`subscriptionsForEvent`); `delivery.ts` is a deterministic retry/backoff policy
(`nextRetryDelaySeconds`, `shouldRetry`, `isRetryableStatus`). The HTTP
dispatcher that actually POSTs to endpoints is the app layer; this owns the
security and routing logic.
