# Trigger logic

Canonical page: https://docs.ovok.com/signals/standalone/trigger-logic

Learn how to write the rules Signals judges readings with.

A trigger is a rule Signals runs on a patient's readings of one code. It decides whether to raise an alert, resolve one, or do nothing. Its `logic` is [JSON Logic](https://jsonlogic.com): data, not code, run by Signals' rule engine. Write your own for your whole tenant or for one patient, beside or instead of the default triggers.

- **Your own algorithms:** judge any code your devices send, with your own thresholds and messages.
- **Per patient:** a clinician's rule for one patient wins over the tenant's rule for the same code.
- **No deploy:** a trigger takes effect on the next reading.

<Callout type="warn">A rule that fails raises no alert. Test every rule on a test patient before real patients depend on it.</Callout>

## Where triggers live [#where-triggers-live]

| Level | Read | Write | Shape |
| --- | --- | --- | --- |
| Your tenant: every patient | [`GET /tenant`](/api/signals-api---tenants/get-the-caller-s-tenant), `orgSettings.triggers` | [`PATCH /tenant`](/api/signals-api---tenants/update-tenant-settings), `orgSettings.triggers` | Object keyed by code |
| One patient | [`GET /patient/{id}/settings`](/api/signals-api---settings/get-a-patient-s-own-rule-settings), `triggers` | [`PUT /patient/{id}/settings`](/api/signals-api---settings/replace-a-patient-s-own-rule-settings), `triggers` | Object keyed by code |
| Many patients at once | | [`POST /patient/config`](/api/signals-api---patient-config/write-one-config-to-many-patients), `triggers` | Array, each trigger with its `code` |

Every route is under `/v1/signals/api`. Call them as a [Manager application](/signals/standalone#app-types) or a project admin.

- **`triggers` is replaced whole** on `PATCH /tenant` and `PUT /patient/{id}/settings`. Read the stored triggers first and send every one you keep.
- **`POST /patient/config` writes one code at a time.** Each trigger replaces the patient's trigger for its code and leaves the others alone. `"delete": true` removes the patient's trigger for the code, and the patient's band for it.
- **A trigger without `logic`** is refused, and the answer lists it.

### Which trigger judges a code [#which-trigger-judges-a-code]

For each code a reading carries, Signals runs one trigger:

1. The patient's own trigger for the code, else the tenant's.
2. Within each, a `system|code` key, such as `http://loinc.org|8867-4`, wins over the bare code.
3. Failing both, the `*` trigger: the patient's, else the tenant's. It skips the tenant's `informationalCodes`.

Triggers run in ascending `order`.

### From the read shape to the write shape [#from-the-read-shape-to-the-write-shape]

`GET /tenant` answers `orgSettings.triggers` as an object keyed by code. `PATCH /tenant` and `PUT /patient/{id}/settings` take that object as it is. `POST /patient/config` takes an array instead: each key becomes the entry's `code`, and the `*` key becomes `"code": "*"`.

<Tabs items={["Read: GET /tenant", "Write: POST /patient/config"]}>
<Tab value="Read: GET /tenant">

```json
{
  "orgSettings": {
    "triggers": {
      "8867-4": {
        "display": "Heart rate",
        "constants": { "high": 110 },
        "logic": { "if": [{ ">": [{ "var": "value" }, { "var": "high" }] }, "Heart rate above 110 /min", false] }
      }
    }
  }
}
```

</Tab>
<Tab value="Write: POST /patient/config">

```json
{
  "ids": ["resident-001"],
  "triggers": [
    {
      "code": "8867-4",
      "display": "Heart rate",
      "constants": { "high": 110 },
      "logic": { "if": [{ ">": [{ "var": "value" }, { "var": "high" }] }, "Heart rate above 110 /min", false] }
    }
  ]
}
```

</Tab>
</Tabs>

With `jq`, the conversion is `.orgSettings.triggers | to_entries | map({code: .key} + .value)`.

## Trigger fields [#trigger-fields]

| Field | Meaning |
| --- | --- |
| `code` | Array form only: the code the trigger judges, a `system\|code` key, or `*`. |
| `logic` | The rule. A JSON object or array, or the same as JSON text. Signals stores it as sent; the default triggers are stored as text. |
| `constants` | Named values the rule reads as variables, such as `{"low": 50, "high": 110}`. |
| `valueKey` | The name the reading's value is read under. `value` when absent. |
| `display`, `notes` | Labels for people. Signals does not read them. |
| `order` | Where the trigger runs among one reading's triggers, ascending. `0` when absent. |
| `everyReading` | `true` runs it on every reading of the patient, even one that does not carry its code. |
| `schedule` | `{"at": "07:00", "timeZone": "Europe/Berlin"}` runs it once a local day instead of on readings. UTC when you name no zone. |
| `every` | A number of seconds: runs it at most once in each such period instead of on readings. `schedule` wins when both are set. |
| `onAck`, `onClose` | Logic run when someone acknowledges an alert (`onAck`), or when Signals closes everything a patient has open, such as on discharge (`onClose`). It sees `now`, `patient`, `state`, and the `alert` or close `reason`, and may return `remember`, `forget` and `note` [actions](#actions). |
| `delete` | `POST /patient/config` only: `true` removes the trigger. |
| `metadata` | `POST /patient/config` only: free-form labels kept with the trigger. Signals does not read them. |

A scheduled run has no reading: `tick` is `true`, `vitals` is empty and there is no `value`.

## What a rule sees [#what-a-rule-sees]

| Name | Value |
| --- | --- |
| `value` | The reading's value for the code being judged: a number, or text. Under your `valueKey` when you set one. Absent when the reading has no value for the code. |
| `vitalCode` | The code being judged, such as `8867-4`. |
| Each key of `constants` | As you set it. A constant never replaces `value`, `code`, `valueQuantity` or `valueString`. |
| `code`, `valueQuantity`, `valueString` | The reading's FHIR coding and value for the code being judged. |
| `vitals` | Every code the reading carries, with its value. Also under `system\|code` when the reading names a system. |
| `absent` | Per code without a value, its `dataAbsentReason` code. |
| `samples` | Per code sent as `valueSampledData`, its samples as `[epochMs, value, …]`, oldest first. |
| `sourceRefIds` | Per code, the `refId` of the reading its value came from, or `null`. |
| `observedAt` | The reading's clinical time, ISO 8601. |
| `lastSeenAt` | The clinical time of the patient's newest reading before this one, or `null`. |
| `now` | When the rule runs, in epoch milliseconds. |
| `tick` | `true` on a scheduled run. |
| `patient` | The patient's `id`, `refId`, `tenantId` and `project`. |
| `state` | What the patient's rules stored with [`remember`](#actions). |
| `settings.individual`, `settings.org` | The patient's own rule settings and the tenant's `orgSettings`: `bands`, `outOfBed`, `triggers`, and any other key you store there. |
| `open` | The patient's open alerts, each `{"code", "variant"}`. |

Read a value with `var` and a dotted path, `{"var": "settings.org.bands.8867-4"}`, or with `val` and a list, `{"val": ["settings", "org", "bands", {"var": "vitalCode"}]}`. A `val` segment may be computed.

## What a rule returns [#what-a-rule-returns]

| Result | What Signals does |
| --- | --- |
| `true` | Raises an alert on the code, or refreshes the open one, with the message "`<code>` triggered at value `<value>`." |
| `false`, `null` or `""` | Resolves the code's open alert as `recovered`. |
| Text | Raises an alert with the text as its message. Text that is JSON, such as `"true"`, is read as that JSON. |
| `{"alert": true, "value": 132, "message": "…"}` | Raises an alert with that value and message. Text in `value` is stored as the alert's payload. `variant` names the alert's kind, `trigger` when absent. `{"alert": false}` resolves as `recovered`. |
| An [action](#actions) | Applied. |
| A list | Each item in turn. `null` items are skipped, so a list resolves nothing unless an item does. |

Anything else, such as a number, fails the rule.

<Callout type="warn">Logic inside an object literal does not run. Build an object from logic with `eachKey`.</Callout>

## Actions [#actions]

Return an action to do more than raise or resolve. Each has an operator that builds it.

| Operator | Arguments | What it does |
| --- | --- | --- |
| `fire` | `[code, variant, message, value, payload, period, limitSeconds]` | Raises an alert on `code`. Only `code` is required; pass `null` to skip one. `variant` is `trigger` when absent, `payload` is text stored with the alert, `period` is `{"start", "end"}`, and `limitSeconds` is the limit in force. |
| `resolve` | `[code, reason]` | Resolves the open alert of `code`, a list of codes, or `*` for every open alert of the patient. `reason` is `recovered`, `returned_to_bed`, `away`, `no_threshold` or `stale`; any other fails the rule. |
| `remember` | `[key, value, key, value, …]` | Stores values in the patient's `state` for later evaluations. |
| `forget` | `[key]` or `[[key, …]]` | Removes keys from `state`. |
| `record` | `[code, value, components, period]` | Stores a computed number as a derived reading of `code`, sent as [`observation.derived`](/signals/standalone/webhooks/observation-derived). It is never judged. |
| `note` | `[name]` | Counts and logs a named condition. It changes nothing. |

`no_threshold` closes the code's episode as `THRESHOLD_CHANGED`. See [Alerts and episodes](/signals/alerts-and-episodes).

## Operators [#operators]

Signals runs rules on [json-logic-engine](https://github.com/TotalTechGeek/json-logic-engine) 5.0.7, which reads an object it does not know as data. A misspelt operator therefore fails when the rule runs, not when you save it. Use only the operators below.

### Standard and engine operators [#standard-and-engine-operators]

| Group | Operators |
| --- | --- |
| Data | `var`, `val`, `exists`, `missing`, `missing_some`, `get`, `keys`, `length`, `preserve` |
| Logic | `if` (also `?:`), `and`, `or`, `!`, `!!`, `??`, `try`, `throw` |
| Comparison | `==`, `===`, `!=`, `!==`, `<`, `<=`, `>`, `>=` |
| Arithmetic | `+`, `-`, `*`, `/`, `%`, `max`, `min` |
| Text | `cat`, `substr`, `in` |
| Lists | `map`, `filter`, `reduce`, `all` (also `every`), `some`, `none`, `merge`, `in` |
| Objects | `eachKey`, `pipe` |

These are not in the original JSONLogic specification:

| Operator | Example | Result |
| --- | --- | --- |
| `val` | `{"val": ["vitals", {"var": "vitalCode"}]}` | The value at a path given as a list. |
| `exists` | `{"exists": "lastSeenAt"}` | `true` when the path is present, even as `null`. |
| `get` | `{"get": [{"var": "band"}, "high", 110]}` | A key of an object, or the default. |
| `keys` | `{"keys": [{"var": "vitals"}]}` | An object's keys. |
| `length` | `{"length": {"var": "samples.8867-4"}}` | The length of a list or text, or an object's key count. |
| `??` | `{"??": [{"var": "individual"}, {"var": "org"}]}` | The first argument that is not `null`. |
| `try` | `{"try": [{">": [{"var": "value"}, 5]}, false]}` | The first argument that does not fail. |
| `throw` | `{"throw": "NO_BAND"}` | Fails the rule. |
| `eachKey` | `{"eachKey": {"value": {"var": "value"}, "alert": true}}` | An object with each value's logic run. |
| `pipe` | `{"pipe": [{"eachKey": …}, {"if": …}]}` | Runs each step on the previous step's result. The first step reads the rule's data. |

- **Text and numbers:** comparing text with a number, or doing arithmetic on text, fails the rule. Guard with `try` when a code can carry text.
- **`null` in comparisons:** `<`, `<=`, `>` and `>=` read `null` as `0`, so `{">": [{"var": "value"}, null]}` is `true`. Check a limit with `!==` `null` before you compare with it.

### Signals operators [#signals-operators]

| Operator | Arguments | Result |
| --- | --- | --- |
| `mean`, `stddev`, `rmssd` | `[list]` | Of a list of numbers. Anything else in the list fails the rule. |
| `median`, `sum`, `count`, `cv`, `sort` | `[list]` | Of the list's numbers; anything else is dropped. `cv` is the coefficient of variation, standard deviation over mean; `sort` is ascending. |
| `percentile` | `[list, rank]` | The `rank` percentile, 0 to 100, of the list's numbers. |
| `slope` | `[list]` | The least-squares slope of `[epochMs, value]` points, such as `window`'s, in value units per second. |
| `beatIntervals`, `pulseIntervals` | `[samples]` | The intervals between beats or pulses in `[epochMs, value, …]` samples. |
| `round` | `[value, decimals]` | Rounded, to whole numbers when `decimals` is absent. |
| `floor`, `ceil`, `exp` | `[value]` | As in mathematics. |
| `pow` | `[base, exponent]` | `base` to the power `exponent`. |
| `clamp` | `[value, low, high]` | `value` held between `low` and `high`. |
| `since` | `[time]` | Seconds from `time` (ISO 8601 or epoch ms) to now. |
| `secondsBetween` | `[from, to]` | Seconds from `from` to `to`. |
| `localMinuteOfDay` | `[time, timeZone]` | Minutes since local midnight in an IANA zone, such as `Europe/Berlin`. |
| `clockMinutes` | `["HH:MM"]` | Minutes since midnight. |
| `window` | `["code", seconds]` | The patient's live readings of `code` in the last `seconds`, as `[epochMs, value]`, oldest first, the readings being judged included. |
| `daily` | `["code", days, aggregate, options]` | One `{"day", "value", "count"}` per local day, oldest first. |
| `json` | `[value]` | The value as JSON text. |
| `compact` | `[object]` | The object without its `null` keys, at every depth. |
| `apply` | `[logic, data]` | Runs `logic` against `data`. |
| `fire`, `resolve`, `remember`, `forget`, `record`, `note` | See [Actions](#actions) | An action. |

- Number operators answer `null` for `null` and for a result that is not a finite number.
- `window` reaches back at most 28 days (`2419200` seconds). `daily` takes 1 to 28 `days`, an `aggregate` of `mean`, `min`, `max`, `sum`, `count`, `first`, `last` or `median`, and `options` of `category`, `timeZone`, `dayStartsAt` (`"HH:MM"`) and `component`.
- `window` and `daily` arguments must be written out, or read from `constants`: Signals loads the readings before the rule runs. A computed argument fails the rule.

## Examples [#examples]

### A threshold with constants [#a-threshold-with-constants]

Raises an alert below 50 or above 110 beats per minute and resolves it in between. Change the limits in `constants` without touching the logic.

```json title="Trigger for 8867-4"
{
  "code": "8867-4",
  "display": "Heart rate",
  "constants": { "low": 50, "high": 110 },
  "logic": {
    "if": [
      { "<": [{ "var": "value" }, { "var": "low" }] },
      { "eachKey": {
        "alert": true,
        "value": { "var": "value" },
        "message": { "cat": ["Heart rate below ", { "var": "low" }, " /min"] }
      } },
      { ">": [{ "var": "value" }, { "var": "high" }] },
      { "eachKey": {
        "alert": true,
        "value": { "var": "value" },
        "message": { "cat": ["Heart rate above ", { "var": "high" }, " /min"] }
      } },
      false
    ]
  }
}
```

| Reading | Result |
| --- | --- |
| 132 | Alert, value 132, "Heart rate above 110 /min" |
| 42 | Alert, value 42, "Heart rate below 50 /min" |
| 80 | The open alert resolves as `recovered` |

### Individual and tenant bands [#individual-and-tenant-bands]

Judges breathing rate against the patient's own band, else the tenant's, from `settings.individual.bands` and `settings.org.bands`. A band may set `low`, `high` or both; `"NO_THRESHOLD"` switches the code off.

```json title="Trigger for 9279-1"
{
  "code": "9279-1",
  "display": "Breathing rate",
  "logic": {
    "pipe": [
      { "eachKey": {
        "code": { "var": "vitalCode" },
        "value": { "var": "value" },
        "band": { "??": [
          { "val": ["settings", "individual", "bands", { "var": "vitalCode" }] },
          { "val": ["settings", "org", "bands", { "var": "vitalCode" }] }
        ] }
      } },
      { "if": [
        { "===": [{ "var": "band" }, null] }, null,
        { "===": [{ "var": "band" }, "NO_THRESHOLD"] }, { "resolve": [{ "var": "code" }, "no_threshold"] },
        { "and": [
          { "!==": [{ "var": "band.low" }, null] },
          { "<": [{ "var": "value" }, { "var": "band.low" }] }
        ] },
        { "fire": [{ "var": "code" }, "low", { "cat": ["Below ", { "var": "band.low" }] }, { "var": "value" }] },
        { "and": [
          { "!==": [{ "var": "band.high" }, null] },
          { ">": [{ "var": "value" }, { "var": "band.high" }] }
        ] },
        { "fire": [{ "var": "code" }, "high", { "cat": ["Above ", { "var": "band.high" }] }, { "var": "value" }] },
        { "resolve": [{ "var": "code" }, "recovered"] }
      ] }
    ]
  }
}
```

The first step gathers what the second needs, because each `pipe` step reads only the step before it. With the tenant's band `{"low": 8, "high": 25}` and the patient's `{"low": 10, "high": 30}`:

| Reading | Result |
| --- | --- |
| 27 | The patient's band applies: resolves as `recovered` |
| 9 | Alert, variant `low`, "Below 10" |
| 27, with no band of the patient's | Alert, variant `high`, "Above 25" |
| Any, with the band `"NO_THRESHOLD"` | Resolves as `no_threshold` |

Set the bands with `PATCH /tenant` (`orgSettings.bands`) and `PUT /patient/{id}/settings` (`bands`). The default triggers read the same keys.

## Best practices [#best-practices]

- **Test on a test patient.** Post readings in, out of and on the edge of the band with `Prefer: respond-sync`: the answer lists the alerts the rule raised.
- **Keep limits in `constants` or `bands`,** not in the logic, so one rule serves every patient.
- **Guard every limit** with `!==` `null`, and every comparison on a code that can carry text with `try`.
- **Start from a default trigger.** Read them with `GET /tenant`; they use every pattern on this page.

## See also [#see-also]

- [Basics](/signals/standalone)
- [Alerts and episodes](/signals/alerts-and-episodes)
- [Webhooks](/signals/standalone/webhooks)
- [Signals route policies](/access-policies/signals)
