Eve library

Demeter Domain - Developer Guide

Guide

Revision 1

On this page

Comprehensive development guide for the Demeter agriculture, home gardening, and environmental intelligence domain.


Prerequisites#

Required Software#

Tool Version Purpose
Node.js >= 20.0 Runtime for all Demeter 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 Demeter libraries should be familiar with:

  • Plant science - Plant taxonomy, growing requirements, companion planting mechanics, pest/disease identification
  • Climate systems - USDA hardiness zones, Koppen climate classifications, AHS heat zones, growing degree day (GDD) calculations, frost dates
  • Food safety - USDA and NCHFP (National Center for Home Food Preservation) guidelines for canning, blanching, and fermentation safety
  • IoT protocols - MQTT, Zigbee, BLE, LoRa for sensor integration (@demeter/sensors)
  • Hydroponic systems - NFT, DWC, ebb and flow, drip, aeroponic, Kratky methods; nutrient EC/TDS/pH management (@demeter/hydroponics)

Optional Tooling#

Tool Purpose
MQTT broker Local testing for @demeter/sensors MQTT adapter
Docker Running PostgreSQL for database integration tests

Environment Variables#

No environment variables are required for building or unit-testing Demeter libraries. For integration tests involving the database:

bash
# Database (required for @demeter/core Drizzle ORM features)
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev

For sensor integration testing:

bash
# MQTT broker (for @demeter/sensors)
MQTT_BROKER_URL=mqtt://localhost:1883

Project Structure#

The Demeter domain contains 14 libraries under libs/demeter/:

text
libs/demeter/
  analytics/               # Yield, cost, resource, environmental, time analytics
  automation/              # Rules engine, irrigation, climate control, alerts
  community/               # Profiles, seed exchange, groups, experts, content
  core/                    # Foundation: Zod schemas (30), Drizzle ORM, seed data
  hydroponics/             # NFT/DWC, nutrients, aquaponics, indoor, microgreens
  intelligence/            # ML: plant ID, disease detection, pest ID, predictions
  inventory/               # Seed lots, suppliers, seed saving, plant inventory
  journal/                 # Observations, growth tracking, photos, harvest logs
  planner/                 # Layout engine, sun analysis, crop rotation, succession
  plants/                  # Species encyclopedia, companion planting, climate zones
  preservation/            # Canning, freezing, dehydrating, fermentation, recipes
  sensors/                 # IoT devices, MQTT/Zigbee/BLE/LoRa, timeseries
  tasks/                   # Task scheduling, auto-generation, prioritization
  weather/                 # Weather data, forecasting, alerts, GDD tracking

Individual Library Layout#

text
libs/demeter/<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#

The Demeter dependency graph is straightforward with @demeter/core as the single foundation:

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

Note that @demeter/planner is the only library with two peer dependencies (@demeter/core and @demeter/plants), because the planner needs companion planting data from the plants library.


Local Development Setup#

Initial Setup#

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

# Install all dependencies
pnpm install

Database Setup (Optional)#

The @demeter/core library uses Drizzle ORM for database schema definition. To work with the database layer:

bash
# Start PostgreSQL
docker compose -f docker/docker-compose.dev.yml up -d postgres

IoT Testing Setup (Optional)#

For @demeter/sensors integration testing, start an MQTT broker:

bash
# Start a local MQTT broker (e.g., Mosquitto)
docker run -d --name mosquitto -p 1883:1883 eclipse-mosquitto

Building Libraries#

Build a Single Library#

bash
pnpm nx build @demeter/core

Build All Demeter Libraries#

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

Build Configuration#

The standard build configuration for Demeter libraries:

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

Build output goes to dist/libs/demeter/<library>/.


Testing#

Run Tests for a Single Library#

bash
pnpm nx test @demeter/core

Run All Domain Tests#

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

Watch Mode#

bash
npx vitest --config libs/demeter/plants/vitest.config.ts --watch

Test Configuration#

The standard vitest configuration for Demeter libraries:

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

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

Coverage#

bash
npx vitest --config libs/demeter/plants/vitest.config.ts --coverage

Testing Patterns#

Plant database tests should verify data completeness and consistency. Every plant species should have required fields, growing requirements, and valid zone ranges:

typescript
describe('VEGETABLE_DATABASE', () => {
  it('every vegetable has growing requirements', () => {
    for (const plant of VEGETABLE_DATABASE) {
      expect(plant.growingRequirements).toBeDefined();
      expect(plant.growingRequirements.sunlight).toBeDefined();
    }
  });
});

Companion planting tests should verify that relationship scoring is symmetric (if A benefits B, the relationship should be documented from both perspectives) and that the Three Sisters layout generates valid configurations.

Climate zone tests should verify GDD calculations against known agricultural reference data and that USDA zone lookups return correct temperature ranges.

Sensor protocol tests should mock the protocol layer (MQTT, Zigbee, BLE) and verify that readings are correctly parsed, validated, and normalized to standard units.

Preservation safety tests should verify that USDA/NCHFP processing times are correctly calculated at different altitudes (pressure canning times increase with altitude):

typescript
describe('pressureCanning', () => {
  it('increases processing time at altitude > 1000ft', () => {
    const seaLevel = getProcessingTime('green-beans', 0);
    const highAltitude = getProcessingTime('green-beans', 5000);
    expect(highAltitude).toBeGreaterThan(seaLevel);
  });
});

Zod schema tests should validate that all 30 schemas in @demeter/core correctly accept valid data and reject invalid data with appropriate error messages.


Linting#

Lint a Single Library#

bash
pnpm nx lint @demeter/plants

Lint All Demeter Libraries#

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

Common Development Tasks#

Adding a New Library#

  1. Create the directory:
bash
mkdir -p libs/demeter/new-library/src
  1. Create project.json:
json
{
  "name": "@demeter/new-library",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/demeter/new-library/src",
  "projectType": "library",
  "tags": ["scope:demeter", "layer:domain", "type:lib"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/demeter/new-library",
        "main": "libs/demeter/new-library/src/index.ts",
        "tsConfig": "libs/demeter/new-library/tsconfig.lib.json",
        "assets": []
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint"
    },
    "test": {
      "executor": "@nx/vite:test",
      "options": {
        "config": "libs/demeter/new-library/vitest.config.ts"
      }
    }
  }
}
  1. Create package.json:
json
{
  "name": "@demeter/new-library",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "exports": {
    ".": {
      "import": "./src/index.js",
      "types": "./src/index.d.ts"
    }
  },
  "peerDependencies": {
    "@demeter/core": "workspace:*"
  },
  "devDependencies": {
    "vitest": "catalog:"
  }
}
  1. Create vitest.config.ts, tsconfig.json, tsconfig.lib.json, tsconfig.spec.json following the standard pattern.

  2. Create src/index.ts as a barrel export.

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

  4. Run pnpm install.

Adding a New IoT Protocol Adapter#

To add support for a new sensor protocol in @demeter/sensors:

  1. Create a new sub-module under libs/demeter/sensors/src/protocols/
  2. Implement the protocol adapter conforming to the base adapter interface
  3. Handle device discovery, connection, reading, and disconnection
  4. Normalize readings to the standard sensor reading types in @demeter/core
  5. Add tests with mock protocol data

Working with the Core Schemas#

@demeter/core exports 30 Zod validation schemas covering the entire domain model. These schemas provide both validation and TypeScript type inference:

typescript
import { PlantTypeSchema, type PlantType } from '@demeter/core';

// Runtime validation
const result = PlantTypeSchema.safeParse(input);
if (result.success) {
  const plantType: PlantType = result.data;
}

When adding new domain entities, define the Zod schema in @demeter/core first, then use the inferred types in dependent libraries.

Working with the Plant Encyclopedia#

The @demeter/plants library ships with pre-built plant databases:

typescript
import {
  VEGETABLE_DATABASE,
  HERB_DATABASE,
  FRUIT_DATABASE,
  FLOWER_DATABASE,
  searchPlants,
  getCompanions,
} from '@demeter/plants';

// Search across all plants
const results = fuzzyNameSearch('tomat');

// Get companion planting recommendations
const companions = getCompanions('tomato');

Adding New Plant Entries#

Plant entries should follow the PlantSpecies type defined in libs/demeter/plants/src/species.ts. Each entry requires taxonomic classification, growing requirements, planting instructions, care guides, and harvest information.


Key Patterns and Conventions#

Core as the Single Foundation#

@demeter/core is the only library with direct dependencies (drizzle-orm, zod). All other libraries use @demeter/core as a peer dependency and have zero direct runtime dependencies:

json
{
  "peerDependencies": {
    "@demeter/core": "workspace:*"
  }
}

30 Zod Schemas#

The core module defines 30 comprehensive Zod schemas covering plants, gardens, beds, plantings, soil tests, weather readings, pest observations, sensor devices, and more. These schemas serve as the single source of truth for data validation and type inference across the entire domain.

Drizzle ORM Database Schema#

The database schema is defined using Drizzle ORM in @demeter/core:

typescript
import { db-schema } from '@demeter/core';

Seed data is also provided through @demeter/core for initial database population.

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 './db-seed.js';

Project Tags#

json
["scope:demeter", "layer:domain", "type:lib"]

Peer Dependency Pattern#

All non-core libraries declare @demeter/core as a peer dependency. Only @demeter/planner has an additional peer dependency on @demeter/plants:

json
{
  "peerDependencies": {
    "@demeter/core": "workspace:*",
    "@demeter/plants": "workspace:*"
  }
}

Debugging Tips#

TypeScript Path Resolution#

The tsconfig.base.json maps "@demeter/*": ["libs/demeter/*/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

Zod Schema Validation Errors#

When Zod validation fails, the error object contains detailed path information:

typescript
const result = schema.safeParse(data);
if (!result.success) {
  console.log(result.error.issues);
  // Shows exactly which field failed and why
}

Sensor Protocol Testing#

When testing IoT protocol adapters, mock the transport layer completely. Do not rely on a running MQTT broker or Zigbee coordinator for unit tests. Reserve real protocol testing for integration tests.

Growing Degree Day Calculations#

GDD calculations accumulate over time and are sensitive to base temperature selection. If GDD tests fail:

  • Verify the base temperature for the crop (varies by species)
  • Check that the calculation uses the correct min/max temperature clamping
  • Verify date range boundaries

Database Integration Issues#

If Drizzle ORM operations fail:

bash
# Verify PostgreSQL is running
docker compose -f docker/docker-compose.dev.yml ps

# Check the connection URL
echo $DATABASE_URL

Nx Cache Issues#

bash
pnpm nx reset

Viewing the Dependency Graph#

bash
pnpm nx graph --focus=@demeter/core

Quick Reference#

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