# Nivalo Cloud MQTT v1.1

Status: **current** (2026-11). v1.1 replaces [Cloud MQTT v1](cloud-mqtt-v1.md) outright. A v1.1
receiver accepts no v1 topic, envelope or payload, and there is no transition period: production
starts on an empty database and devices are re-claimed on v1.1 firmware.

First profile: a standalone ESP32 on Arduino-ESP32 2.0.17 (PubSubClient, MQTT 3.1.1), the Nivalo
gateway (MQTT 5) and EMQX. The STM32 bridge comes later.

- **MUST** marks a wire or safety requirement. Numbers are exact; ranges are inclusive unless stated.
- Schemas in [`schemas/v1.1/`](../schemas/v1.1) define shape. This document defines everything a schema
  cannot express. Fixtures in [`fixtures/v1.1/`](../fixtures/v1.1) are normative examples
  (section 16); a conforming implementation agrees with all of them.
- *Server* means the gateway and API together; *receiver* is whoever parses a message (the gateway for
  uplinks, the device for downlinks; the gateway also validates downlinks before publishing them).

## 1. Topics and transport

All topics are `nivalo/v1.1/devices/{deviceId}/{route}`:

| Route | Direction | Payload schema | Publisher QoS | Retain |
|---|---|---|---|---|
| `telemetry` | device → cloud | `telemetry-batch` | 0 | no |
| `events` | device → cloud | `device-event` | 0 | no |
| `state` | device → cloud | `device-state` | 0 | no |
| `definitions` | device → cloud | `capability-operations` | 0 | no |
| `availability` | device or its Last Will → cloud | `availability` | 0 (Will: 1) | birth and end: yes; heartbeat: no |
| `commands/{commandId}` | cloud → device | `command` | 1 | no |
| `commands/{commandId}/ack` | device → cloud | `command-ack` | 0 | no |
| `ota/{commandId}` | cloud → device | `ota-command` | 1 | no |
| `ota/{commandId}/ack` | device → cloud | `command-ack` | 0 | no |

Schema names stand for `schemas/v1.1/<name>.schema.json`; every message is an `mqtt-envelope` whose
`payload` matches the route's schema.

- `deviceId` and `commandId` are canonical UUIDs (lowercase, hyphenated). Receivers match the topic
  exactly: no other levels, trailing slash, letter case, wildcard or fallback route.
- The device subscribes at QoS 1 to exactly `…/{deviceId}/commands/+` and `…/{deviceId}/ota/+`.
  The gateway subscribes at QoS 1 to the uplink routes. Telemetry, events, state, definitions and
  ACKs may use a shared subscription. Availability MUST use an ordinary subscription on every gateway
  instance, because the broker replays retained messages only to ordinary subscriptions: after a
  gateway restart the retained birth or end arrives again. The epoch rules of 8.2 make the duplicate
  deliveries harmless.
- The device connects with MQTT 3.1.1, clean session, keepalive 60 s, TLS with certificate
  validation (port 8883 production, 8884 staging), and a Last Will on `availability` (QoS 1,
  retained) carrying the `end` payload for the connection being attempted (section 8.1).
- The gateway publishes downlinks with MQTT 5 content type `application/json` and Message Expiry
  Interval `floor(expiresAt − now)` seconds; it does not publish when less than 1 s remains. A
  receiver rejects an explicit MQTT 5 content type other than `application/json`.

## 2. Broker identity

- Claim issues username `{deviceId}` and client ID `nivalo-{deviceId without hyphens}`; manual
  credential issuance uses `device-{deviceId without hyphens}` for both. The pair is immutable for the
  credential; rotation keeps the client ID, re-enrolment issues a new pair.
- Authentication MUST require an active credential, an enabled device, a valid password hash **and**
  a presented client ID ordinally equal to the issued one. A missing, differently cased or padded
  client ID is denied. The server never learns or updates a client ID from a login.
- Authorization is deny-by-default and identical in the broker's inline ACLs and the HTTP authz
  callback. A device may publish only its own five uplink routes and `commands/+/ack`,
  `ota/+/ack`, and subscribe only to its own `commands/+` and `ota/+`. The gateway may subscribe to
  uplinks and publish only `commands/{id}` and `ota/{id}`. Retain is permitted only on
  `availability`. Gateway instances use configured, distinct client IDs.
- Disabling a device or rotating its credential disconnects existing sessions of the old credential.
- The topic device ID, the envelope `deviceId` and the device bound to the authenticated credential
  MUST agree. The tenant is always derived from that device, never from message content.

## 3. Envelope

```json
{"schema":"nivalo.iot.v1.1","messageId":"33333333-3333-4333-8333-333333333333",
 "deviceId":"22222222-2222-4222-8222-222222222222","sentAt":"2026-11-24T12:00:05Z","payload":{}}
```

- `schema` is exactly `nivalo.iot.v1.1`. `messageId`, `deviceId` and `sentAt` are required.
- `correlationId` is required on `commands/{id}`, `ota/{id}` and both ACK routes and equals the route
  ID; it is absent on every other route.
- `firmware` (`version`, `hardware` 1–64 bytes each; `targets`, unique values from `esp32`, `stm32`)
  is required on availability `birth` and absent on every other message. The first profile sends
  `["esp32"]`. The latest accepted birth defines the device's firmware metadata.
- `null` appears only inside event `data` and state `value`; command `arguments` contain no null at
  any depth. Optional fields are omitted, never null.
- `messageId` identifies one logical message. A sender that retries reuses the identical bytes.
  Before the device has a valid clock (section 9) it sends nothing, because `sentAt` cannot be
  fabricated.

## 4. Encoding, limits and validation order

### 4.1 Encoding

- A payload is one JSON object (RFC 8259) in UTF-8 without a byte order mark. Insignificant
  whitespace is allowed and counts toward size limits.
- Receivers reject malformed UTF-8, duplicate member names at any depth, U+0000 anywhere (including
  member names and nested event data), unpaired surrogate escapes, non-JSON tokens such as `NaN`, and
  any content after the object.
- **UTF-8 bytes.** Every `maxLength` K in a v1.1 schema also limits the string to K UTF-8 bytes after
  unescaping. (`minLength` counts characters.)
- **Integer-lexical.** A field of schema type `integer` MUST be a JSON integer token: `1`, never
  `1.0` or `1e0`, even though JSON Schema 2020-12 treats those as integers.
- **Exact decimals.** Telemetry `value` is evaluated as an exact decimal (`2.1125e1` equals
  `21.125`; `1e-7` has seven decimal places). Never use binary floating point for `multipleOf` or
  range checks.
- Timestamps (`common#/$defs/utc`) are `YYYY-MM-DDTHH:MM:SS[.mmm]Z`: a real calendar date in
  2020–2037, no offset, no leap second, zero or exactly three fractional digits.
- Patterns are ECMA-262 regular expressions anchored with `^` and `(?!\n)$`. The lookahead makes
  engines whose `$` also matches before a final newline (Python, .NET) reject it; keep it.
- Names (`common#/$defs/name`, `^[A-Za-z][A-Za-z0-9_.-]{0,63}$`) are compared ordinally. Two names
  that differ only in ASCII letter case are *case twins*.
- Text fields (`common#/$defs/text`) have no leading or trailing space and no C0 control character or
  DEL. Raw value strings (`raw`) are preserved byte for byte, including `""` and surrounding spaces.

### 4.2 Limits

| Limit | Value |
|---|---|
| Payload bytes (whole MQTT payload, measured before decoding) | ≤ 3072; `commands/{id}` ≤ 1536; `ota/{id}` ≤ 2048 |
| Container nesting (the envelope object is level 1) | ≤ 8 levels |
| JSON values (every object, array, string, number, boolean and null; member names excluded) | ≤ 192 |
| Telemetry | 1–8 samples, 1–24 metrics per sample, ≤ 24 readings per message, `raw` ≤ 512 bytes, `unit` ≤ 32 bytes, `value` within ±4294967295.999999 in steps of 0.000001 |
| Event `raw` | ≤ 1024 bytes |
| Generic command arguments (checked by the API at creation) | compact UTF-8 serialization ≤ 768 bytes and ≤ 48 JSON values |
| Command lifetime `expiresAt − issuedAt` | generic: > 0 and ≤ 900 s (default 300); OTA: > 0 and ≤ 7200 s (default 7200) |
| Capability packet | 1–8 operations; per device ≤ 256 live keys and ≤ 512 stored keys |
| ACK `message` | ≤ 95 bytes |
| Uplink observation window (telemetry, events, state) | `sentAt` and every observation time within [receipt − 7 days, receipt + 120 s] |

The limits are independent. A device whose data does not fit splits it across messages before
assigning `messageId`.

### 4.3 Wire rules beyond the schemas

| Rule | Check |
|---|---|
| `identity` | envelope `deviceId` equals the topic device ID |
| `correlation` | `correlationId` present and equal to the route ID exactly on operation routes |
| `command-seq` | the last eight hex digits of the route ID equal `commandSeq` as eight lowercase hex digits |
| `firmware-placement` | `firmware` present exactly on availability `birth` |
| `lifetime` | operation lifetime as in 4.2 |
| `signature-encoding` | `signature.value` is canonical Base64 of strict DER: `SEQUENCE { INTEGER r, INTEGER s }`, minimal positive encodings, `1 ≤ r, s < n` (P-256 order), no trailing bytes |
| `reading-count` | at most 24 metrics across all samples |
| `sample-order` | sample times (`at`, or `sentAt` when absent) strictly increase |
| `duplicate-metric` | no two metrics in one sample with the same name or case twins |
| `observation-window` | as in 4.2, against the gateway's receipt time |
| `heap` | heartbeat `heapFreeB ≤ heapTotalB` |
| `duplicate-capability` | no two operations in one packet with the same `kind` and `name`, and no two upserts of one `kind` whose names are case twins |
| `argument-example` | `argumentExample` parses (under 4.1) as a JSON object |

### 4.4 Validation order

Receivers reject a message as a whole. The fixtures name the first failing check in this order;
an implementation only has to reject: `topic`, `size`, `encoding`, `json`/`duplicate-member`,
`depth`, `value-count`, envelope `schema`, `identity`, `correlation`, payload `schema`,
`command-seq`, `firmware-placement`, then the remaining route rules of 4.3.

## 5. Telemetry

```json
{"samples":[
  {"at":"2026-11-24T12:00:00Z","metrics":[{"name":"temp","value":21.125,"unit":"C"},{"name":"door","raw":" open "}]},
  {"metrics":[{"name":"temp","value":21.5,"unit":"C"}]}]}
```

- Each metric carries exactly one of `value` (number) or `raw` (text). A sample without `at` is
  observed at `sentAt`. A name may repeat in a later sample.
- One envelope is one atomic ingest unit: the server validates every reading, then in one
  transaction claims the ledger key (device, route, `messageId`) with the SHA-256 of the exact payload
  bytes, stores all readings (ordered by sample, then metric) and updates usage, or stores nothing.
  The same key with the same bytes is a duplicate: acknowledge, change nothing. The same key with
  different bytes is a permanent conflict. Downstream work (alerts, realtime) runs after commit, at
  most once per stored reading.
- **Unit stability.** Per (device, metric name), the first accepted unit, including no unit, is
  fixed. A reading with another unit rejects its whole envelope. Changing a unit needs a new name.
- Out-of-window envelopes (4.2) are rejected, not stored and not billed. A known duplicate is
  acknowledged before the window is re-checked.

## 6. Events and state

- `events`: `name` (the `state.` prefix is reserved in any case), `severity`
  (`debug`/`info`/`warning`/`error`/`critical`, default `info`), optional `observedAt` (default
  `sentAt`), and at most one of `data` (any JSON, including null) or `raw` (text). The server stores
  `data` as JSON and `raw` as a JSON string, both exactly.
- `state`: `name` and `value` (any JSON, including null). Stored as event `state.{name}`, severity
  `info`, observed at `sentAt`.
- Both are ingested with the same ledger rules as telemetry and each is one billable event
  (section 13), whatever its name.

## 7. Data, presence and control are separate

Availability, definitions, ACKs and downlinks are never billed and never change data history.
Only availability changes presence; telemetry, events, state, ACKs and definitions never do (the
server may track data activity times separately).

## 8. Availability and presence

### 8.1 Device

- `boot` is a persisted counter, incremented and durably written once per boot before any MQTT
  connection. `connection` is a RAM counter incremented before every CONNECT attempt, including
  failed ones. `(boot, connection)` is the **epoch**, compared lexicographically; it MUST never repeat
  or decrease for a device ID. Before `connection` would pass 4294967295 the device starts a new boot
  epoch. A claimed device whose boot counter is missing or unreadable does not connect; it must be
  re-claimed.
- Before each CONNECT the device builds the Last Will: a fresh envelope (new `messageId`, current
  `sentAt`) with `{"kind":"end","status":"offline","boot":B,"connection":C,"reason":"will"}`.
- After CONNECT and both subscriptions: retained `birth` (`seq` 0, envelope `firmware` required),
  then the capability refresh (section 12.4). A client that can observe SUBACK waits for both QoS 1
  grants and otherwise disconnects and retries. The Arduino/PubSubClient profile cannot observe
  SUBACK, so it publishes birth once both SUBSCRIBE packets are written. That is safe: a device that
  is not subscribed receives no operation, so its operations expire without an effect, and the
  gateway's republication (10.3) covers a transient loss.
- While connected: a non-retained `heartbeat` every 600 ± 30 s (monotonic timer) with `seq` 1, 2, …
  within the epoch and current health (`uptimeS`, `heapFreeB`, `heapTotalB`, optional
  `wifiRssiDbm`, `droppedBatches`). Heartbeats carry no customer data.
- Graceful disconnect: retained `end` with `reason` `shutdown`, then DISCONNECT.

### 8.2 Server state

Per device the server stores the highest epoch, its highest online `seq`, a terminal flag, the
freshness time `freshAt`, the end receipt time `offlineAt`, the latest heartbeat (vitals) of the
epoch, and the firmware metadata of the latest applied birth. Updates are atomic compare-and-set
across gateway and API instances. For each wire-valid availability message, received at gateway UTC
time `r`:

1. An online message (`birth`, `heartbeat`) with `sentAt > r + 120 s` is **rejected**: no effect.
2. An epoch lower than the stored one is **ignored**.
3. A higher epoch replaces the stored one: not terminal, no `seq`, no `freshAt`, no vitals.
4. If the epoch is terminal, the message is **ignored** (the first `end` wins regardless of
   `sentAt`, retain flag or arrival order).
5. `end`: mark terminal, `offlineAt = r`.
6. `birth`: update firmware metadata. If `seq` is not above the stored `seq` (a heartbeat arrived
   first, or a retained birth is replayed) the outcome is **metadata** only.
7. A `heartbeat` whose `seq` is not above the stored `seq` is **ignored** (duplicates never extend
   freshness).
8. Otherwise store `seq`, set `freshAt = max(freshAt, min(sentAt, r))` and, for a heartbeat, the
   vitals.

### 8.3 Status

Computed on read at time `now` (and pushed to realtime when it changes, including on timeout):
`disabled` (administrative) wins; no epoch → `unknown`; terminal → `offline`;
`now − freshAt ≥ 1320 s` (22 min) or no `freshAt` → `unknown`; otherwise `online`. A retained or
buffered birth with an old `sentAt` therefore cannot make a session fresh.

## 9. Device clock

- The clock is **valid** only if an SNTP synchronisation completed in this boot, the last one was at
  most 6 h ago by the monotonic timer, and no backward step of more than 2 s has been observed since
  (it becomes valid again when a synchronisation reaches the last trusted instant). Current time is
  the last synchronised UTC plus monotonic elapsed time.
- When the device claims an operation (10.4) it derives a monotonic deadline: the monotonic time at
  the claim plus `expiresAt − now`. At every trusted synchronisation while the operation is active it
  derives the deadline again from the new time and keeps the earlier of the two, so a
  synchronisation can shorten the deadline but never extend it, also across several
  synchronisations. Every later expiry check takes a fresh reading of validity, current time and the
  monotonic timer, and fails once the monotonic timer reaches the deadline or the current time
  reaches `expiresAt`.
- Without a valid clock the device opens no TLS/MQTT connection. If the clock becomes invalid while
  connected, the device starts no new effect.
- SNTP gives approximate, unauthenticated time; this is not a tamper guarantee.

## 10. Commands and OTA jobs

Generic commands (`commands/{id}`, schema `command`) and OTA jobs (`ota/{id}`, schema `ota-command`)
are both **operations** and share one per-device sequence and execution journal.

### 10.1 Issuance (server)

- `commandSeq` is allocated per device under a per-device lock in the job's insert transaction:
  1, 2, 3, … across both classes, never reused or wrapped.
- The operation ID is a random UUID v4 whose last eight hex digits are `commandSeq` (42 →
  `…-44440000002a`). IDs are globally unique.
- `issuedAt` is the server's creation time. `expiresAt` defaults to `issuedAt` + 300 s (generic) or
  + 7200 s (OTA); a caller may request an earlier deadline. A past or over-limit deadline is rejected
  at creation.
- The stored payload object is immutable and republished byte-identically; only the envelope
  `messageId` and `sentAt` change between publications.
- An OTA job is created only by the firmware job endpoints, under the tenant's firmware-write
  authority, from a verified artifact (section 11). Its payload is built by the server. Nothing in a
  generic command, its arguments, a URL supplied by a caller or a capability report can create or
  select an OTA job.
- The artifact's tenant, target, product ID and optional device restriction MUST match the
  destination device (its tenant, a target in its latest birth, its product, its ID) at enqueue and
  again before every publication. Two units of one product in one tenant pass the device prechecks
  of 11.3 equally, so only this check keeps a unit-specific artifact on its unit.

### 10.2 Generic command allow-list (server)

At creation and again immediately before each publish the server accepts a generic command only if:

1. `command` is a valid name and is not reserved (`flash`, `requestDefinitions`, `firmware.*`,
   `ota.*`, in any letter case), except the exact built-in `requestDefinitions`, which requires
   `arguments` `{}` and makes the device republish its catalog;
2. `arguments` is an object without null at any depth, within the 768-byte and 48-value limits;
3. otherwise `command` is a **live function in the device's merged catalog** (exact name; section 12)
   **and** the device's product defines a server-side argument schema for that name that `arguments`
   satisfies. A reported function without a product argument schema is visible but not dispatchable.
   `argumentExample` never authorises anything.

### 10.3 Dispatch (server)

- At most one operation per device is live (`published`, `accepted` or `running`). Operations are
  published in `commandSeq` order. The next one is published only after the previous has ended
  (10.5). If it ended as a server-assigned `indeterminate` after the device reported `accepted` or
  `running`, later operations wait until the device's result arrives (10.4) or an operator
  reconciles it.
- The gateway attempts to publish the same operation (same ID and payload bytes) when it is leased,
  again after every new birth epoch, and every 30 s, also after `accepted` or `running`. The device
  answers duplicates from its journal (10.4), so the next publication recovers a lost ACK. A lost or
  late ACK is never a reason to create a new operation.
- Every attempt (lease, birth or timer) re-reads the operation and publishes only if it is still
  live, that is not ended (10.5) by a device result, expiry, cancellation or retirement, and passes
  device enablement, tenant, the allow-list (generic) or the artifact match (OTA, 10.1), presence
  `online` and at least 1 s of remaining lifetime. Otherwise it sends nothing, including from a
  lease taken before the change. A late device result for an earlier publication is still applied.
- Before every network publish the gateway durably records that the operation may have been sent
  (`queued` → `published`), in the same atomic update as that check, so a crash between the
  publish and its bookkeeping never leaves a sent operation `queued`.

### 10.4 Device execution

The device keeps a durable **journal** per device ID: the highest consumed sequence `highWater` and
the record of that operation (ID, class, payload fingerprint, phase `claimed` or `done`, terminal
result). The record survives reboot, Wi-Fi changes, credential resets and OTA, and is written and
read back before it is relied on. A claimed record means "the effect may have begun". The
**fingerprint** is the SHA-256 of the exact UTF-8 bytes of the envelope's `payload` value as received,
from its opening `{` to its closing `}`; the envelope around it (`messageId`, `sentAt`, member order,
whitespace) is excluded.

The device handles the downlinks of its device ID on **one executor**, a single task that makes every
journal transition: the claim, a rejection before the effect and the terminal result. The table
check below and the transition it leads to are one step on that executor, so two deliveries of one
sequence can never both execute and an older delivery can never overwrite a newer claim. The device
is **busy** from the claim until the operation's terminal result is durable, including an OTA
download and activation.

A downlink is **identified** when its topic, size, encoding, JSON, complexity, envelope schema and
`deviceId` are valid, `correlationId` equals the route ID, and `payload.commandSeq` is a JSON integer
1–4294967295 encoded by the route ID. The rest of the payload need not be valid. An unidentified
downlink is dropped without an ACK. For an identified one with sequence `n`:

| Condition | Device action |
|---|---|
| `n < highWater` | ACK `indeterminate` / `replay_suppressed`. No effect. |
| `n = highWater`, same ID, class and fingerprint | Replay: ACK `running` while busy, otherwise the journaled terminal result (even after expiry). |
| `n = highWater`, anything different | ACK `failed` / `id_conflict`. No effect; the journal is unchanged. |
| `n > highWater` while busy | Drop without ACK; not consumed (the server redelivers). |
| `n > highWater` | Execute as below. |

Execution of a new operation:

1. Validate: payload schema and lifetime, else `invalid_command`. Generic: the built-in
   `requestDefinitions` is handled by the device itself, whatever the application registers: it
   starts the refresh of 12.4 and succeeds. Any other `command` needs a registered handler, else
   `not_allowed`, and passes the handler's own argument check, else `invalid_command`. OTA: the
   prechecks of section 11.3, else `ota_rejected`.
2. Clock: invalid → `clock_unsynced`; `issuedAt > now + 2 s` → `clock_unsynced`;
   `now ≥ expiresAt` → `expired`.
3. A failure in 1–2 is journaled as a terminal `failed` result for `n` (consuming the sequence) and
   ACKed. A `clock_unsynced` ACK caused by an invalid clock is published once the clock is valid.
4. Journal `claimed` for `n` (durable) and derive the monotonic deadline (section 9), then ACK
   `accepted`.
5. Re-check the clock and the deadline (section 9) on a fresh reading immediately before the effect.
   For OTA the effect is the activation call, so the reading is taken after the pending record of
   11.4 is durable; a reading from before that write does not count. Failure: journal and ACK
   `failed` (`expired` or `clock_unsynced`); the handler is not called and no image is activated.
6. Call the handler once. Journal its result, then ACK it: `succeeded`; `failed` / `handler_failed`
   only when the handler knows the effect did not happen; otherwise, for example a timeout or error
   after an output may have changed, `indeterminate` / `execution_unknown`. Work that has started may
   finish after `expiresAt`.

After a reboot, a `claimed` generic record becomes `indeterminate` / `execution_unknown`; a claimed
OTA record is reconciled by section 11.4. A duplicate delivery is answered from the journal as above.
In addition, after every birth and with every heartbeat the device republishes the ACK of its
journaled record if that record is `done` (from memory, without a journal write), so a lost terminal
ACK reaches the server even after the operation expired. If the journal for the current device ID is
missing or corrupt, or cannot be written, the device accepts no downlinks (drops them without ACK)
until it is re-claimed (section 15); a freshly claimed device starts with `highWater` 0. At
`highWater` 4294967295 the device accepts no further downlinks.

This gives at-most-once physical execution with visible uncertainty, not guaranteed delivery: QoS 0
ACKs can be lost and the server then shows `indeterminate` until a republished result arrives.

### 10.5 ACK

`commandSeq` and `status` are required; `message` (≤ 95 bytes) is optional; `progress` (integer
0–100) only on `running`; `code` is required on `failed` and `indeterminate` and absent otherwise.

| Status | Meaning | Codes |
|---|---|---|
| `accepted` | journaled as claimed | — |
| `running` | handler running (optional, repeatable) | — |
| `succeeded` | effect completed | — |
| `failed` | effect did not happen | `expired`, `clock_unsynced`, `invalid_command`, `not_allowed`, `id_conflict`, `storage_error`, `ota_rejected`, `handler_failed` |
| `indeterminate` | effect may have happened; it will not be attempted again | `execution_unknown`, `replay_suppressed` |

Server processing: the ACK route class, device, ID and `commandSeq` must match the stored operation,
else the ACK is ignored. An ACK of any status for an operation never recorded as may-have-been-sent
(`queued`, or `cancelled`) is ignored. `failed`/`id_conflict` is a diagnostic only and changes
nothing. Status only moves forward (`published` → `accepted` → `running` → terminal) and `progress`
never decreases. The first terminal device result is final.

An operation **ends** without a device result when it expires, is cancelled or its device is retired
(section 15). If it is still `queued` it becomes `cancelled`. Otherwise it may have been sent and may
have acted, so it becomes `indeterminate` (server-assigned, never `cancelled`); a later terminal
device result replaces a server-assigned `indeterminate`.

| Server state | Meaning |
|---|---|
| `queued` | created, never handed to the network |
| `published` | may have been sent (recorded before every publish), no device report yet |
| `accepted`, `running` | as reported by the device |
| `succeeded`, `failed`, `indeterminate` | terminal device result, or a server-assigned `indeterminate`: may have been sent, ended without a device result |
| `cancelled` | never published (cancelled, expired or retired while `queued`) |

The realtime contract (`schemas/signalr-device-hub-v1.contract.json`) carries these states.

## 11. OTA

### 11.1 Manifest and signature

```json
{"commandSeq":43,"issuedAt":"2026-11-24T12:00:00Z","expiresAt":"2026-11-24T14:00:00Z",
 "manifest":{"format":2,"target":"esp32","productId":"11111111-1111-4111-8111-111111111111",
             "securityVersion":7,"sizeBytes":3,"sha256":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
 "url":"https://firmware.example.invalid/vector/abc",
 "signature":{"algorithm":"ecdsa-p256-sha256","keyId":"test-only-vector-1","value":"…"}}
```

The signature is ECDSA P-256 with SHA-256, standard padded Base64 of ASN.1 DER, over exactly these
ASCII bytes (LF line ends, final LF required, integers in base 10 without leading zeros, lowercase
UUID and digest):

```text
NIVALO-FIRMWARE-SIGNATURE-V2\n{target}\n{productId}\n{securityVersion}\n{sizeBytes}\n{sha256}\n
```

Every manifest field is covered, so changing the product ID, security version, size or digest
invalidates the signature. `url` is a temporary download locator outside the signature: absolute
HTTPS, lowercase host, optional port 1–65535, no userinfo, no fragment, ≤ 512 bytes. [`fixtures/v1.1/vectors/ota.json`](../fixtures/v1.1/vectors/ota.json)
has a test-only key and signatures; its key MUST NOT appear in any trust store.

### 11.2 Products, keys and signing (server)

- Staging and production use **different product IDs**. A device accepts only its provisioned
  product ID, so an image signed for one environment never installs in the other.
- The signer signs only for a product the authenticated organisation has release authority for, and
  verifies the image's embedded product ID and security version against the manifest first. Within
  (product ID, target) each security version maps to one digest: re-signing identical bytes is
  idempotent, another digest at the same version is refused. Every release raises the version.
- The device's trust store is compiled into its image and selected by `keyId`. Release key IDs never
  start with `test-`.

### 11.3 Device prechecks (before any download)

In order, failing with `failed` / `ota_rejected`: `keyId` in the trust store; signature valid over
the canonical bytes; `productId` equals the provisioned product ID; `securityVersion` greater than
the floor `max(running image's security version, committed floor)`; `sizeBytes` no larger than the
inactive application slot; `url` origin equals the device's configured API origin, compared as parsed
scheme, host and effective port (443 when absent). A URL the device cannot parse fails this check.

### 11.4 Install and reconcile (device)

The device is busy (10.4) throughout steps 1–3 and until step 4 has journaled the result.

1. After `accepted`: download over certificate-validating HTTPS without redirects, enforcing exactly
   `sizeBytes` bytes and `sha256`, and check the image's embedded product ID and security version
   against the manifest. Failure: `failed` / `ota_rejected`.
2. Persist a pending record from the signed manifest: the claimed operation's `commandSeq`,
   `productId`, `securityVersion`, `sizeBytes` and `sha256`. Failure: `failed` / `storage_error`.
3. Re-check the clock and the deadline on a fresh reading taken after step 2 (10.4 step 5),
   immediately before the activation call. Failure: journal the `failed` result, then clear the
   pending record. Otherwise call activation (boot-partition selection) once and reboot. If the call
   reports that the image was definitely not selected (for example image validation failed), journal
   `failed` / `ota_rejected`, then clear the pending record; the running image stays. If the call
   fails in a way that may have selected the image (for example a flash write error), keep the claim
   and the pending record and reboot; step 4 decides. The device never calls activation a second
   time for one operation.
4. At boot, before connecting: if the journal holds a `claimed` OTA record and the pending record
   carries its `commandSeq`, hash the first `sizeBytes` bytes of the running image's slot (the rest
   of the slot is padding). If the running image's embedded product ID, security version and that
   SHA-256 equal the pending record, commit the floor, then journal `succeeded`; otherwise journal
   `indeterminate` / `execution_unknown` (also for a claimed OTA record without such a pending
   record). Only then clear the pending record; a pending record that does not belong to a claimed
   OTA record is just cleared. Every write is idempotent, so a reset during this step repeats it at
   the next boot. The result is ACKed after birth (10.4).
5. Redelivery is answered from the journal; the device never installs twice for one operation.

This is application-level downgrade protection. Physical flash access, NVS erase and bootloader
bypass are outside it; secure boot, flash encryption and hardware rollback are later ESP-IDF work.

## 12. Capabilities

### 12.1 Operations

A `definitions` packet has `source` (`esp32`; `mcu` is reserved for the bridge), `revision`
(1–2147483647) and 1–8 `ops`, each one of: upsert variable, upsert function, remove variable, remove
function. Upserts carry a closed `definition`; function names may not be reserved names (10.2).

```json
{"source":"esp32","revision":8,"ops":[
  {"op":"upsert","kind":"variable","name":"temp","definition":{"dataType":"number","unit":"C"}},
  {"op":"upsert","kind":"function","name":"setLed","definition":{"argumentExample":"{\"state\":true}","dangerLevel":"operational","returnType":"integer"}},
  {"op":"remove","kind":"variable","name":"oldTemp"}]}
```

The firmware release owns a monotonic catalog revision. Any changed definition, rename or removal
advances it; repeating unchanged entries reuses it.

### 12.2 Merge (server)

The catalog is stored per (device, source, kind, name) with the key's revision and its normalized
definition, or a tombstone. Normalization fills the defaults (`historyEnabled` true, `sortOrder` 0;
`timeoutSeconds` 30, `dangerLevel` `safe`, `sortOrder` 0). One packet is applied in one transaction,
all or nothing:

1. Reject the packet on a schema failure or `duplicate-capability` (4.3).
2. Compare each operation on key k with the stored entry of k (a packet has one operation per key,
   so their order does not matter): no entry or a lower stored revision → apply (an upsert creates
   or revives, a remove stores a tombstone, also for unknown keys); higher stored revision → skip;
   equal revision → skip if the normalized content is equal (both tombstones, or equal definitions),
   otherwise reject the packet (`revision-conflict`).
3. A case-only rename, a remove and an upsert of one kind whose names are case twins, applies as a
   pair: if either half is skipped by step 2, both are skipped. A repeated rename therefore changes
   nothing.
4. Reject the packet if the result has live case twins of one kind (`name-collision`), more than 256
   live keys or more than 512 stored keys (`limit`).

Absence means no change. Tombstones are kept for the device ID's lifetime. A case-only rename is one
packet: a remove of the old name and an upsert of the new one at a higher revision. Rejected packets
change nothing and are logged; there is no response to the device.

### 12.3 Effective catalog

There is no approval step: the merged live entries are the device's effective catalog. A removed
function stops being dispatchable immediately. Dispatch is additionally gated by the product's
server-side argument schemas (10.2).

### 12.4 Refresh

After every birth, and when it receives `requestDefinitions`, the device publishes its whole current
catalog at the current revision: every live entry and a remove for every name the firmware has
retired, in packets of at most 8 operations. Dependent changes that must apply together go in one
packet; a case-only rename is always sent as its remove and upsert pair in one packet.

## 13. Usage units

Per tenant and UTC month of **server acceptance**:

```text
units = ceil(T / 16) + E
```

`T` is accepted telemetry readings (metrics, not messages) and `E` accepted events plus state
observations. Each accepted envelope is charged the change in the month-to-date value, computed with
integer arithmetic in the ingest transaction, so batching and splitting do not change the total.
Duplicates, rejected envelopes, availability, definitions, ACKs and downlinks add nothing. The server
also records `T`, `E`, envelope count and bytes separately.

Enforcement is a server setting (off for the owner's production). When on, an envelope that would
take the month-to-date units above the plan limit is refused whole (nothing stored or charged),
without affecting other tenants. Prices and plan limits are outside this protocol.

## 14. Errors

- The gateway rejects an invalid message whole, records a bounded diagnostic without the payload,
  credentials or URLs, and acknowledges it to the broker so it is not redelivered. Transient storage
  failures are retried. A rejected message has no effect on data, usage, presence or jobs.
- The device drops unidentified downlinks silently and answers identified ones only with the ACK
  codes of 10.5. ACK messages never echo payloads, credentials or URLs.
- The API validates internal ingest at the same limits as MQTT, so no path bypasses them.

## 15. Setup code and claim

Each unit has one owner-held setup code (16 random Crockford Base32 characters, 80 bits) provisioned
over USB into a factory namespace. It is the WPA2 passphrase of the local setup access point and
nothing else. It never appears in MQTT, claim requests or responses, logs or any cloud API, and the
cloud neither stores nor checks it. Claiming is unchanged ([device-claim-v1](device-claim-v1.md)).

A Wi-Fi or credential reset keeps the setup code, the provisioned product ID, the OTA floor, the
command journal and the boot counter. Claim exchange rejects a hardware ID that is already bound to a
device. Re-claiming such a unit requires the owner to delete or retire that device first; retirement
disables the device and its credential, disconnects its sessions and ends its non-terminal
operations as in 10.5 (`indeterminate` if they may have been sent, `cancelled` otherwise). The
re-claim then gives a new device identity with a new journal. Any other re-enrolment of bound
hardware is out of scope for v1.1: the owner's units are claimed fresh on an empty database.

## 16. Fixtures

All under `fixtures/v1.1/`, parsed as JSON with numbers kept exact:

| File | Content |
|---|---|
| `schemas/<schema>.json` | Instances per schema (or `$defs` pointer) with `valid`. A `rule` (`utf8-bytes`, `integer-lexical`) marks a case a stock JSON Schema validator may accept but section 4.1 rejects. |
| `messages.json` | Complete messages: topic, exact payload (`payload` text or `payloadBase64`), `receivedAt`, `expect` `accept`/`reject` and the first failing `rule` (4.4). |
| `vectors/presence.json` | Availability sequences with the outcome and projection after each step (section 8). |
| `vectors/command-execution.json` | Payload fingerprints and device journal steps: deliveries, completions, heartbeats, reboots, power loss, clock states; expected ACKs, handler calls, OTA activations, pending record, floor and journal (sections 9–11). |
| `vectors/command-dispatch.json` | Server allow-list decisions (10.2), OTA artifact match (10.1) and operation states (10.3, 10.5). |
| `vectors/capability-merge.json` | Packets against stored catalogs with outcome and resulting catalog (section 12). |
| `vectors/ingest-metering.json` | Ledger, unit stability and usage arithmetic (sections 5 and 13). |
| `vectors/ota.json` | Test-only key, signature vector, signature mutations, device prechecks and the signed mock image used by the install vectors (section 11). |

`tests/protocol_v1_1.py` is a small executable reading of this document; CI replays every fixture
against it. The fixtures have no MQTT transport, so the subscription rules (the ordinary availability
subscription of section 1, birth after both subscriptions and the SUBACK profiles of 8.1) are
verified in the gateway and firmware test suites.

## 17. Changes from v1

- New topic root `nivalo/v1.1`, envelope marker `nivalo.iot.v1.1`, closed objects, byte and
  complexity limits; no legacy `acks/{id}` route or ACK aliases.
- Batched telemetry with exact decimals and stable units; billing by usage units.
- Session-epoch availability with ordered Last Will, 10-minute heartbeat and computed `unknown`.
- Operations carry `commandSeq`, `issuedAt` and `expiresAt`; the device enforces expiry and executes
  at most once with a durable journal; new ACK status `indeterminate` and failure codes.
- OTA has its own route and job type; manifest format 2 signs product ID and security version.
- Capability reports are per-key merged deltas with tombstones; no approval step.
- MQTT client ID bound to the issued credential.
