# Demeter Automation Rule Syntax

Demeter's automation engine
([`@demeter/automation`](../../../../libs/demeter/automation/src/rules.ts))
evaluates **rules** — "when these conditions hold, run these actions" — against
a live context of sensor readings, time, and weather. This document specifies
the rule grammar so you can author rules correctly.

## Rule anatomy

A `Rule` has:

| Field                              | Meaning                                                |
| ---------------------------------- | ------------------------------------------------------ |
| `name` / `description`             | Human-readable identity                                |
| `enabled`                          | Active flag                                            |
| `conditions`                       | A **root condition group** (see below)                 |
| `actions`                          | Ordered actions to run when conditions are met         |
| `cooldownSeconds`                  | Minimum seconds between triggers (debounce; default 0) |
| `priority`                         | 1 (lowest) – 10 (highest); orders concurrent rules     |
| `tags`                             | Organisation labels                                    |
| `triggerCount` / `lastTriggeredAt` | Engine-maintained stats                                |

## Conditions

A **condition** tests one fact:

```ts
{
  type: 'sensor_threshold',     // what kind of fact
  sensorType: 'soil_moisture',  // which sensor (for sensor_threshold / rate_of_change)
  deviceId: 'bed-3-moisture',   // which device's reading
  operator: 'lt',               // comparison
  value: 30,                    // threshold
  negate: false                 // optionally invert the result
}
```

### Condition types

| `type`             | Tests                         | Uses                                         |
| ------------------ | ----------------------------- | -------------------------------------------- |
| `sensor_threshold` | A sensor reading vs a value   | `sensorType`/`deviceId`, `operator`, `value` |
| `rate_of_change`   | How fast a sensor is changing | `sensorType`/`deviceId`, `operator`, `value` |
| `time_of_day`      | Current clock time            | `operator`, `value`                          |
| `day_of_week`      | Day (0=Sun … 6=Sat)           | `operator`, `value`                          |
| `weather`          | A weather-context field       | `operator`, `value`                          |
| `custom`           | A user-defined variable       | `value`                                      |

### Operators

`gt`, `gte`, `lt`, `lte`, `eq`, `neq`, and the ranged `between` / `not_between`
(which use both `value` and `secondValue`). Any condition may set `negate: true`
to invert its result.

## Condition groups (AND / OR, nestable)

Conditions combine in a **`ConditionGroup`** with a logical `operator` (`'and'`
| `'or'`). Groups nest arbitrarily, so you can express `A AND (B OR C)`:

```ts
{
  operator: 'and',
  conditions: [
    { /* A: soil_moisture lt 30 */ },
    {
      operator: 'or',
      conditions: [
        { /* B: weather rainMm eq 0 */ },
        { /* C: time_of_day between 06:00–08:00 */ },
      ],
    },
  ],
}
```

`evaluateConditionGroup(group, context)` short-circuits per the operator;
`evaluateCondition(condition, context)` evaluates a leaf against the
`RuleContext`.

## Actions

When the root group evaluates true (and cooldown has elapsed), `actions` run in
order:

| `type`              | Effect                       | Key fields                          |
| ------------------- | ---------------------------- | ----------------------------------- |
| `set_device`        | Send a command to a device   | `deviceId`, `command`, `parameters` |
| `send_notification` | Notify the user              | `parameters` (message/channel)      |
| `log_event`         | Record to the automation log | `parameters`                        |
| `trigger_scene`     | Run a saved scene            | `parameters.sceneId`                |
| `delay`             | Pause before the next action | `delaySeconds`                      |
| `set_variable`      | Set a context variable       | `parameters`                        |

Each action returns an `ActionResult` (`success`, `error?`, `result?`); the rule
returns a `RuleResult` (`conditionsMet`, `actionsExecuted`, and the reason if it
was skipped — e.g. cooldown).

## Evaluation context

`RuleContext` is what conditions see each tick:

```ts
{
  sensorReadings: Record<deviceId, { type, value, unit, timestamp }>,
  currentTime: Date,
  dayOfWeek: number,           // 0=Sunday … 6=Saturday
  weather?: { tempC, humidity, windKmh, conditions, rainMm },
  variables: Record<string, unknown>,
}
```

## Worked example — moisture-triggered irrigation

> _"When soil moisture in bed 3 drops below 30% **and** no rain has fallen, run
> the drip line — but no more than once every 6 hours."_

```ts
createRule({
  name: 'Bed 3 low-moisture watering',
  enabled: true,
  cooldownSeconds: 6 * 60 * 60,
  priority: 5,
  conditions: {
    operator: 'and',
    conditions: [
      {
        type: 'sensor_threshold',
        sensorType: 'soil_moisture',
        deviceId: 'bed-3-moisture',
        operator: 'lt',
        value: 30,
        negate: false,
      },
      { type: 'weather', operator: 'eq', value: 0, negate: false }, // rainMm == 0
    ],
  },
  actions: [
    {
      type: 'set_device',
      deviceId: 'bed-3-valve',
      command: 'open',
      parameters: { durationSeconds: 600 },
    },
    {
      type: 'send_notification',
      parameters: { message: 'Watered bed 3 (low moisture)' },
    },
  ],
});
```

## Related building blocks

- **Alerts** (`alerts.ts`) — a specialised rule form with `PRESET_ALERT_RULES`,
  `evaluateAlerts`, acknowledge/resolve/escalate.
- **Irrigation** (`irrigation.ts`) — `schedule | moisture | manual | et_based`
  watering triggers + usage tracking.
- **Climate control** (`climate-control.ts`) — vent/fan actions from temperature
  deltas and wind.
- **Scenes** (`scenes.ts`) — named action bundles invoked by `trigger_scene`.
- **History** (`history.ts`) — rule performance, water-savings, and
  underperforming-rule analysis.
