# Rules

Use Rule to choose which steps to run based on values in context.

## Overview

**Type:** `rule`

Rules are evaluated in order, and only the first matching rule runs. Combine a rule's conditions with `AND` or `OR`. Add a final rule without `conditions` for a fallback.

## Configuration

### Rules

* **Type:** Array of Objects
* **Required:** Yes
* **Description:** List of conditional rules to evaluate in order

Each rule contains:

**Conditions**

* **Type:** Array of Objects
* **Required:** No
* **Description:** List of conditions to evaluate for this rule

Each condition object contains:

**source**

* **Type:** String
* **Required:** Yes
* **Templatable:** Yes
* **Description:** Path to value in context (supports dot notation)

```
user.age
order.status
api_response.data.count
```

**filter**

* **Type:** Enum
* **Required:** Yes
* **Description:** Comparison operation to apply

| Category | Filters |
| --- | --- |
| Existence | `EXISTS`, `NOT_EXISTS` |
| Comparison | `EQUALS`, `NOT_EQUALS`, `GREATER_THAN`, `LESS_THAN`, `GREATER_THAN_OR_EQUALS`, `LESS_THAN_OR_EQUALS` |
| String | `CONTAINS`, `NOT_CONTAINS`, `STARTS_WITH`, `ENDS_WITH`, `MATCHES` |
| Array | `IN`, `NOT_IN`, `ARRAY_CONTAINS`, `ARRAY_LENGTH` |
| Date | `DATE_BEFORE`, `DATE_AFTER`, `DATE_BETWEEN` |
| Boolean | `IS_TRUE`, `IS_FALSE` |
| Object | `HAS_PROPERTY`, `PROPERTY_EQUALS` |

`EXISTS` treats both `null` and missing values as absent. `EQUALS`, `NOT_EQUALS`, `ARRAY_CONTAINS`, and `ARRAY_LENGTH` use strict comparisons. String filters are case-sensitive, and `MATCHES` treats the target as a regular expression.

For `IN` and `NOT_IN`, supply the allowed values as an array. `DATE_BETWEEN` takes `[start, end]` and includes both endpoints. `PROPERTY_EQUALS` takes `[propertyName, expectedValue]`.

**value**

* **Type:** The configuration schema declares a String. At runtime, literal values can also be numbers, booleans, or arrays, as required by the filter.
* **Required:** No (depends on filter)
* **Templatable:** Yes
* **Description:** Value to compare against

**Operator**

* **Type:** Enum
* **Required:** No
* **Default:** `AND`
* **Options:** `AND`, `OR`
* **Description:** Logical operator to combine multiple conditions

**Then**

* **Type:** Array of Objects
* **Required:** Yes
* **Description:** Steps to execute when conditions match

**Else**

* **Type:** Array of Objects
* **Required:** No
* **Description:** Used only on a rule with no `conditions` property. Conditional rules fall through to the next rule when they do not match; their `else` is ignored. Prefer a final conditionless rule with `then` for a fallback.

## Output

The first matching rule returns the complete context after its nested steps, including parent values and named nested outputs. A rule without `conditions` runs unconditionally (`else` if supplied, otherwise `then`). If no rule matches, the input context is returned. When the Rule step has an `output`, this returned context is stored under that name; nested outputs are not merged into the parent.

## Examples

These examples are steps to include in an [execution request](/docs/execute-workflows). Supply their referenced variables in context, including `currentDate` for the date comparison example.

### Simple equality check

```json
{
  "type": "rule",
  "output": "result",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "user.role",
            "filter": "EQUALS",
            "value": "admin"
          }
        ],
        "then": [
          {
            "type": "request",
            "output": "admin_data",
            "config": {
              "url": "https://api.example.com/admin/dashboard",
              "method": "GET"
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "request",
            "output": "user_data",
            "config": {
              "url": "https://api.example.com/user/dashboard",
              "method": "GET"
            }
          }
        ]
      }
    ]
  }
}
```

### Multiple conditions with AND

```json
{
  "type": "rule",
  "output": "notification",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "order.total",
            "filter": "GREATER_THAN",
            "value": "100"
          },
          {
            "source": "user.isPremium",
            "filter": "IS_TRUE"
          }
        ],
        "operator": "AND",
        "then": [
          {
            "type": "email",
            "output": "email_sent",
            "config": {
              "to": "{{ user.email }}",
              "from": "rewards@company.com",
              "subject": "Premium Rewards Points!",
              "htmlPart": "<p>You earned bonus points on order {{ order.id }}!</p>"
            }
          }
        ]
      }
    ]
  }
}
```

### Multiple conditions with OR

```json
{
  "type": "rule",
  "output": "alert",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "payment.status",
            "filter": "EQUALS",
            "value": "failed"
          },
          {
            "source": "payment.attempts",
            "filter": "GREATER_THAN",
            "value": "3"
          }
        ],
        "operator": "OR",
        "then": [
          {
            "type": "sms",
            "output": "alert_sent",
            "config": {
              "to": "{{ user.phone }}",
              "from": "{{ company.smsNumber }}",
              "body": "Payment issue detected for order {{ order.id }}. Please update your payment method."
            }
          }
        ]
      }
    ]
  }
}
```

### String operations

```json
{
  "type": "rule",
  "output": "categorized",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "email.subject",
            "filter": "CONTAINS",
            "value": "urgent"
          }
        ],
        "then": [
          {
            "type": "request",
            "output": "priority_queue",
            "config": {
              "url": "https://api.example.com/tickets/priority",
              "method": "POST",
              "data": {
                "email": "{{ email }}"
              }
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "request",
            "output": "normal_queue",
            "config": {
              "url": "https://api.example.com/tickets/normal",
              "method": "POST",
              "data": {
                "email": "{{ email }}"
              }
            }
          }
        ]
      }
    ]
  }
}
```

### Array operations

```json
{
  "type": "rule",
  "output": "access_granted",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "user.permissions",
            "filter": "ARRAY_CONTAINS",
            "value": "reports:view"
          }
        ],
        "then": [
          {
            "type": "request",
            "output": "reports",
            "config": {
              "url": "https://api.example.com/reports",
              "method": "GET"
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "request",
            "output": "error",
            "config": {
              "url": "https://api.example.com/errors/403",
              "method": "POST",
              "data": {
                "message": "Access denied"
              }
            }
          }
        ]
      }
    ]
  }
}
```

### Date comparisons

```json
{
  "type": "rule",
  "output": "subscription_check",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "subscription.expiresAt",
            "filter": "DATE_AFTER",
            "value": "{{ currentDate }}"
          }
        ],
        "then": [
          {
            "type": "email",
            "output": "active_email",
            "config": {
              "to": "{{ user.email }}",
              "from": "noreply@company.com",
              "subject": "Your subscription is active",
              "htmlPart": "<p>Your subscription is valid until {{ subscription.expiresAt }}</p>"
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "email",
            "output": "expired_email",
            "config": {
              "to": "{{ user.email }}",
              "from": "noreply@company.com",
              "subject": "Renew your subscription",
              "htmlPart": "<p>Your subscription expired. Click here to renew.</p>"
            }
          }
        ]
      }
    ]
  }
}
```

### Checking existence

```json
{
  "type": "rule",
  "output": "profile_complete",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "user.phoneNumber",
            "filter": "EXISTS"
          },
          {
            "source": "user.address",
            "filter": "EXISTS"
          }
        ],
        "operator": "AND",
        "then": [
          {
            "type": "request",
            "output": "send_verification",
            "config": {
              "url": "https://api.example.com/verify",
              "method": "POST"
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "email",
            "output": "reminder",
            "config": {
              "to": "{{ user.email }}",
              "from": "noreply@company.com",
              "subject": "Complete your profile",
              "htmlPart": "<p>Please complete your profile information.</p>"
            }
          }
        ]
      }
    ]
  }
}
```

### Multiple rules (fallthrough)

```json
{
  "type": "rule",
  "output": "tier_benefits",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "user.tier",
            "filter": "EQUALS",
            "value": "platinum"
          }
        ],
        "then": [
          {
            "type": "request",
            "output": "platinum_benefits",
            "config": {
              "url": "https://api.example.com/benefits/platinum",
              "method": "GET"
            }
          }
        ]
      },
      {
        "conditions": [
          {
            "source": "user.tier",
            "filter": "EQUALS",
            "value": "gold"
          }
        ],
        "then": [
          {
            "type": "request",
            "output": "gold_benefits",
            "config": {
              "url": "https://api.example.com/benefits/gold",
              "method": "GET"
            }
          }
        ]
      },
      {
        "conditions": [],
        "then": [
          {
            "type": "request",
            "output": "standard_benefits",
            "config": {
              "url": "https://api.example.com/benefits/standard",
              "method": "GET"
            }
          }
        ]
      }
    ]
  }
}
```

### Regex matching

```json
{
  "type": "rule",
  "output": "email_validation",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "user.email",
            "filter": "MATCHES",
            "value": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
          }
        ],
        "then": [
          {
            "type": "request",
            "output": "create_account",
            "config": {
              "url": "https://api.example.com/users",
              "method": "POST",
              "data": {
                "email": "{{ user.email }}"
              }
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "request",
            "output": "validation_error",
            "config": {
              "url": "https://api.example.com/errors/validation",
              "method": "POST",
              "data": {
                "message": "Invalid email format"
              }
            }
          }
        ]
      }
    ]
  }
}
```

## Best practices

### Rule ordering

* Rules are evaluated in order
* First matching rule executes
* Use a final rule without `conditions` for a fallback. An empty `conditions: []` also matches with `AND`, but does not match with `OR`.
* Order rules from most specific to least specific

### Performance

* Put common rules first only when that preserves the intended priority.
* Use simple filters when possible
* Avoid complex regex when simpler filters work
* Use `OR` when any condition should select the same branch.

### Maintainability

* Use descriptive output names
* Keep conditions simple and readable
* Document complex regex patterns
* Group related conditions logically

### Type handling

* Templated values preserve types when possible
* Interpolated unsigned numeric strings auto-convert: `"{{ threshold }}"` returning `"123"` becomes `123`
* Interpolated `"true"` and `"false"` strings auto-convert to booleans
* Non-templated values keep their original type. `EQUALS` and `NOT_EQUALS` use strict equality, so literal `"200"` differs from `200`.

## Common use cases

* **User role routing**: Direct users to different flows based on permissions
* **Order value thresholds**: Apply different processing for high-value orders
* **Status-based actions**: Execute different steps based on entity status
* **Feature flags**: Enable/disable features conditionally
* **A/B testing**: Route users using an experiment assignment supplied in context
* **Validation**: Check data completeness before proceeding
* **Error handling**: Branch on failures captured as data, such as Batch results with `failFast: false`
* **Subscription tiers**: Provide tier-specific functionality
* **Geographic routing**: Route based on location data
* **Time-based logic**: Different behavior for dates/times

## Troubleshooting

### Conditions not matching

* Verify source path points to correct context value
* Check data types match (string vs number)
* Use templating when comparing dynamic values
* Test individual conditions separately

### Wrong branch executing

* Review operator (AND vs OR)
* Check rule order (first match wins)
* Verify all conditions in rule
* Test with simplified conditions

### Type mismatches

* Ensure numeric comparisons use numbers
* Use appropriate filters for data types
* Check templated values convert correctly
* Verify boolean comparisons use IS_TRUE/IS_FALSE

### Performance issues

* Reduce number of conditions
* Simplify complex regex patterns
* Preserve rule priority when ordering rules by expected frequency.
* Supply repeated calculations as input values instead of duplicating them in conditions.
