SSOLVOTIX / AGENT ENTRYPOINT
DOCUMENT_STATUS=READY

ASK THE GUIDE

Solvotix website assistant

Ask about products, specifications, solutions, integrations, and the API. Answers include links to the website and documentation.

0 / 3000

Solvotix saves questions and replies for later review. Your question and recent messages are sent to OpenAI to answer from the documentation. Do not include API tokens, passwords, access codes, or customer data. AI answers can contain mistakes; check the linked sources. This assistant provides guidance only and cannot operate devices.

Read the agent guide
---
document: solvotix-agent-guide
document_version: "1.1"
language: en
audience: autonomous-coding-agent
read_mode: sequential
api_base_url: https://backend.solvotix.org
openapi_url: https://backend.solvotix.org/v3/api-docs
swagger_url: https://backend.solvotix.org/swagger-ui/index.html
manifest_url: https://solvotix.net/ai-first/agent-manifest.json
authentication: solvotix-api-user-token
tenant_header: Tenant
status: live
---

# SOLVOTIX AGENT EXECUTION GUIDE

## 0. EXECUTION DIRECTIVE

You are integrating software with the Solvotix physical-device platform.

Follow these instructions in order.

1. Read this document completely before changing code.
2. Retrieve the live OpenAPI document before selecting endpoints or generating types.
3. Treat OpenAPI as authoritative for paths, methods, parameters, schemas, and documented responses.
4. Use this document as authoritative for sequencing, physical semantics, verification, risk, and approval rules.
5. Do not invent endpoints, fields, device capabilities, success states, or retry behavior.
6. Begin with authentication and read-only discovery.
7. Do not execute a physical operation until the tenant, device ID, device type, and real-world purpose are known.
8. An HTTP success response can mean accepted or queued. It does not prove physical completion.
9. Verify physical operations through queue state, events, and current device state when available.
10. Never expose tokens, passwords, refresh tokens, Wi-Fi credentials, access codes, private keys, or service-account files.
11. Never automatically retry a non-idempotent physical command.
12. Stop and report uncertainty when this guide, OpenAPI, inventory, and observed state disagree.

## 1. MACHINE RESOURCES

```yaml
html_guide: https://solvotix.net/ai-first/agent-guide
raw_markdown: https://solvotix.net/ai-first/agent-guide.md
structured_manifest: https://solvotix.net/ai-first/agent-manifest.json
openapi_json: https://backend.solvotix.org/v3/api-docs
swagger_ui: https://backend.solvotix.org/swagger-ui/index.html
production_api: https://backend.solvotix.org
```

Preferred read order:

1. `agent-manifest.json`
2. `agent-guide.md`
3. live OpenAPI JSON
4. project-local conventions and existing generated clients

## 2. REQUIRED INPUTS

```text
SOLVOTIX_API_BASE_URL=https://backend.solvotix.org
SOLVOTIX_API_TOKEN=<sat_ token copied from the Solvotix portal>
SOLVOTIX_TENANT_ID=<tenant selected when the API user was created>
```

If the API token or its tenant ID is unavailable, stop and ask the system owner to create an API user in the Solvotix portal. Do not request human login credentials, create placeholder tokens, or embed a token in source code.

### 2.1 Restricted role

The `Restricted` role can be assigned to authenticated human users and tenant-bound API users. It is
a shared backend role, not an OAuth scope. A Restricted identity has broad application access,
including operations otherwise available to an unrestricted tenant user, with these enforced
exceptions:

- Access-code values are masked in JSON responses. This includes booking and room codes, lock-user
  codes, smart-lock slots and master codes, cleaning views, automated-message data, and event data,
  text, and reasons. A value such as `1234` is returned as `1**4`. MIFARE UIDs and credential
  identifiers are masked the same way, so `DEADBEEF` is returned as `D******F`.
- Setting a user's Firebase password with `PUT /api/users/{id}/password` returns `403`.
- Raw gateway message payloads are removed from command responses.
- Gateway queue/message read, refresh, package-download, and delete operations return `403
  Forbidden`. This includes tenant, device, and individual-gateway queue routes.

The `Receptionist` role is unchanged and may receive booking codes. Do not infer Restricted behavior
from Receptionist behavior. A Restricted user may submit an access-code value for an authorized
operation, but must not expect the unmasked value to be echoed in the response. A `403` from a
gateway queue route must not be bypassed or treated as an empty queue; use non-queue state and event
verification that does not expose a code. Do not automatically retry the rejected request.

## 3. SYSTEM MODEL

```text
agent/application
  -> Solvotix REST API
  -> authenticated tenant context
  -> persistent command queue
  -> selected gateway
  -> physical device
  -> queue result / event / device state
```

```yaml
entities:
  api_user: tenant-bound Solvotix machine identity
  tenant: isolated organization, site, or installation
  gateway: connection between Solvotix Cloud and local devices
  sensor: generic API model for a connected node or device
  message_frame: hardware command accepted or queued by the backend
  event: structured hardware or system activity record
  queue: command delivery state between backend, gateway, and device
```

### Public documentation and disclosure boundary

This guide and the manifest describe supported public Solvotix contracts for building applications.
Include only the authentication, inputs, outputs, device capabilities, errors, events, safety,
verification and retry rules that an application developer needs. An operation appearing in
OpenAPI alone does not establish that it is supported for public application use.

Never publish, quote, log or echo secrets, secret-bearing URLs, private configuration, personal
customer or staff data, private service details, deployment or storage details, or security
maintenance and recovery procedures. Use synthetic placeholders in examples. Do not enumerate
private systems or infer their contracts. If public support is uncertain, omit the operation and
request clarification without disclosing private information. Apply this policy to prose, JSON,
examples, event payloads and linked resources. Keep public permission requirements, partial-failure
warnings, offline limitations and physical-operation verification rules accurate.

### Gateway availability

Commands may remain queued until an eligible gateway is available. Gateway-specific commands
require the intended gateway. An online indication does not prove delivery; read the permitted
queue, events and device state. Do not resubmit a command merely because a gateway is offline.

## 4. OPENAPI ACQUISITION

Retrieve the current specification:

```bash
curl --fail --silent --show-error \
  https://backend.solvotix.org/v3/api-docs \
  --output solvotix-openapi.json
```

Validate all of the following:

```yaml
required_top_level_fields:
  - openapi
  - info
  - servers
  - paths
  - components
required_component_fields:
  - schemas
required_security_scheme:
  name: bearerAuth
  type: http
  scheme: bearer
  bearer_format: JWT
```

OpenAPI processing algorithm:

```text
1. Validate the document structure.
2. Select https://backend.solvotix.org as the production server.
3. Index operations by tag, operationId, method, and path.
4. Resolve every local $ref.
5. Read request parameters and requestBody schemas.
6. Read every documented response schema and status.
7. Generate types using the project's existing generator when one exists.
8. Place authentication, tenant selection, safety, and retry behavior in a wrapper.
9. Never edit generated client files directly.
10. Record the OpenAPI info.version, retrieval time, and content hash.
```

Optional client generation:

```bash
npx @openapitools/openapi-generator-cli generate \
  -i https://backend.solvotix.org/v3/api-docs \
  -g typescript-fetch \
  -o generated/solvotix

openapi-generator-cli generate \
  -i https://backend.solvotix.org/v3/api-docs \
  -g python \
  -o generated/solvotix
```

Conflict rule:

```yaml
if_written_example_conflicts_with_openapi:
  action: stop
  report:
    - operation
    - written_value
    - openapi_value
    - proposed_resolution
  forbidden: guessing
```

## 5. CREATE THE SOLVOTIX SYSTEM AND API USER

API users are machine identities for integrations, scripts, and external systems. An API user belongs to exactly one tenant, uses a long-lived bearer token, does not require an interactive user account at runtime, can expire, can have the same roles as a human user, and can be revoked or rotated.

Human setup sequence:

1. Open `https://portal.solvotix.org/login`.
2. Press **Register here** and create the Solvotix system owner account.
3. Sign in and open `https://portal.solvotix.org/home/settings#system-users`.
4. Select the target tenant/system.
5. Create an API user with a descriptive integration name, the minimum appropriate role, and an expiration date when appropriate.
6. Copy the displayed `sat_...` token immediately.
7. Store the token in a secrets manager or protected environment variable.
8. Record the tenant ID selected during creation.

The plaintext token is displayed only when the API user is created or rotated. It cannot be retrieved later.

```yaml
api_user:
  identity_type: machine
  belongs_to_tenants: exactly-one
  token_prefix: sat_
  token_lifetime: long-lived
  expiration: optional
  revocable: true
  rotatable: true
  roles: [Janitor, Cleaning, Receptionist, Restricted, User]
  empty_roles: unrestricted
  role_changes_require_token_rotation: false
  runtime_interactive_account_required: false
  may_manage_api_users: false
```

## 6. STORE THE TOKEN

```text
SOLVOTIX_API_TOKEN=<SAT_API_TOKEN>
SOLVOTIX_TENANT_ID=REPLACE_WITH_BOUND_TENANT_ID
```

Mandatory token rules:

```yaml
token_storage:
  permitted:
    - secrets manager
    - protected server environment variable
  forbidden:
    - frontend or browser bundle
    - Git repository
    - URL or query parameter
    - application log
    - analytics event
    - error report
on_exposure: rotate immediately in the Solvotix portal
```

Do not build an API-token integration as browser-only code. The token grants broad access inside its bound tenant and must remain on a trusted server.

## 7. API-USER AUTHENTICATION

Every API request uses the copied token in the standard bearer header:

```http
GET /api/sensor
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
Accept: application/json
```

```bash
curl "https://backend.solvotix.org/api/sensor" \
  -H "Authorization: Bearer $SOLVOTIX_API_TOKEN" \
  -H "Tenant: $SOLVOTIX_TENANT_ID" \
  -H "Accept: application/json"
```

The `sat_` prefix tells the backend to authenticate a Solvotix API user.

```yaml
authorization_header: Authorization
authorization_format: Bearer sat_<TOKEN>
tenant_header: Tenant
tenant_header_recommended: true
tenant_derived_from_token_when_omitted: true
tenant_mismatch_result: 401 Unauthorized
token_refresh_flow: none
token_rotation: human owner action in portal
```

The token is bound to the tenant selected during creation. Never substitute another tenant ID. Although the backend can derive tenant context from the token, include the `Tenant` header for consistency with generated clients and existing API calls.

## 8. VERIFY AUTHENTICATION

Use a read-only endpoint from the live OpenAPI specification. Start with device inventory:

```http
GET /api/sensor
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
```

Interpret failures:

```yaml
401:
  possible_causes:
    - token missing
    - token malformed
    - token expired
    - token revoked
    - Tenant header does not match token tenant
  action: stop and ask system owner to verify or rotate the API user
403:
  possible_causes:
    - API user attempted API-user credential management
    - operation is not permitted for this identity
  action: stop; do not attempt privilege escalation
```

## 9. API-USER LIFECYCLE BOUNDARY

The integration cannot create, list, rotate, or revoke API users. Those operations require an authenticated regular portal user with tenant membership.

The API-user implementation does not provide OAuth-style scopes. It supports the same roles as
human users. Role changes apply to the next authenticated request without token rotation.
+A missing or empty role list grants unrestricted access. Unknown role
names are rejected rather than ignored. Create API users only for trusted integrations, select the
minimum appropriate role, and isolate each integration with its own token so it can be revoked or
rotated independently.

```yaml
credential_management:
  portal: https://portal.solvotix.org/home/settings#system-users
  performed_by: human tenant member
  create: POST /api/api-users
  list: GET /api/api-users
  rotate: POST /api/api-users/{id}/rotate
  update_roles: PUT /api/api-users/{id}/roles
  revoke: DELETE /api/api-users/{id}
  api_user_calling_management_endpoint: 403 Forbidden
rotation_effect:
  old_token: invalid-immediately
  new_token_visibility: one-time
  revoked_user_reenabled: true
  expiration_preserved: true
access:
  tenant_boundary: enforced
  per_token_scopes_supported: false
  shared_human_api_user_roles: true
  role_changes_effective: next-request-without-token-rotation
  trust_requirement: trusted-integration-only
```

When a runtime request returns `401`, do not attempt an interactive sign-in. Stop and request API-user verification or rotation from the system owner.

## 10. READ-ONLY DISCOVERY

Execute in this order:

```yaml
steps:
  - method: GET
    path: /api/gateways
    purpose: list tenant gateways
  - method: GET
    path: /api/sensor
    purpose: list tenant devices
  - method: GET
    path: /api/gateways/{gatewayId}/sensors
    purpose: map devices to gateways
  - method: GET
    path: /api/gateways/{gatewayId}/metering/latest
    purpose: inspect gateway metering
  - method: GET
    path: /api/sensor/{deviceId}/pairings
    purpose: inspect device relationships
```

Build this inventory:

```yaml
device_inventory_fields:
  - id
  - name
  - type
  - online_state
  - gateway_ids
  - configuration
  - paired_device_ids
  - supported_operations_from_openapi
  - known_real_world_purpose
```

Gateway responses from `GET /api/gateways` and `GET /api/gateways/{id}` include the
read-only `wifiMac` field: the gateway-reported Wi-Fi station MAC, formatted as
uppercase colon-separated hexadecimal (for example, `AA:BB:CC:DD:EE:FF`). It is
`null` until compatible firmware reports a valid MAC. The backend retains it while
the gateway is offline and when older firmware reconnects without reporting a MAC.
The read-only `wifiIp` field is the last reported local Wi-Fi IPv4 address in
dotted-decimal form (for example, `<LOCAL_IPV4>`). It is `null` until reported,
may change through DHCP, and is not the public Internet address. Both fields are
reported on backend connection and retained while offline; an IP value alone does
not establish current reachability. MAC-only firmware leaves a saved IP intact.
Bluetooth and access-point addresses may differ; use `wifiMac` to identify the Wi-Fi
client in a router or DHCP reservation. It is a network identifier, not proof of
ownership or authentication. Treat reported network identifiers as private tenant data.

```http
GET /api/gateways/{id}
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
```

Use an existing gateway ID from tenant discovery. These are read-only, idempotent
requests with no approval requirement; existing endpoint roles and tenant checks
apply. Inspect `wifiMac` and `wifiIp` on the returned gateway, or on its existing gateway-update
notification. A null MAC is compatible with older firmware and is not a gateway
failure. The detail endpoint returns `404` if the gateway is not found; handle
`401` as described in the authentication contract and respect `403` access denial.
Changing gateway name or description does not change the reported MAC or IP.

Do not map a generic `sensor` to an operation until its device type and compatible endpoint are established.

## 11. DEVICE OWNERSHIP AND ADMINISTRATION

Claiming, deleting or transferring a device changes ownership. Confirm the tenant, device identity,
physical purpose and explicit operator authorization first. Use only the supported operation in
live OpenAPI; do not infer a claim from incoming device traffic.

`DELETE /api/sensor/{id}` requires bearer authentication and the owning `Tenant` context;
unrestricted and Restricted identities may call it. Confirm the device and obtain explicit
operator approval: this is a destructive, ownership-changing operation. It has no request body:

```http
DELETE /api/sensor/<DEVICE_ID>
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
```

A `204` response has no body, including when the device was already absent. It removes the
registration, pending server-side commands/update work, and device references from rooms,
cleaning-room snapshots, lock users, sensor groups, automation targets and other devices'
server-side pairing lists. Bookings lose their device association through the room; bookings,
rooms, room codes, lock users, groups, tasks and history remain. PIN, MIFARE and Wallet credentials
remain assigned to their other devices. Tasks with no remaining devices are retained and skipped.
Server-side gateway node/routing references are also cleared; new physical observations can
report the node again without reclaiming it.

Inventory removal records application event `1039` with `sensor_uuid` and string-valued data
`entityType: "sensor"`, `entityId`, `entityName`, `state: "deleted"`, `actorUserId` and `actorName`.
The name and actor identify the sensor and deleter at deletion time, without depending on the
sensor still existing. The event proves inventory removal, not completion of every cleanup step
or a physical reset. Repeating deletion of an already absent sensor retries cleanup without
creating another deletion event.

The operation does not erase physical credentials/security state, change physical pairings or
send a hardware reset. Commands already sent may still finish. Deletion can fail partially;
reference-cleanup failures return `500` and prevent successful ownership release. Handle `401`
as an authentication or tenant mismatch and `403` as access denial. After an ambiguous response,
inspect inventory and ownership before an authorized retry; never delete a device that has since
been claimed again. Do not automatically retry.

Verify absence with `GET /api/sensor`, room membership with `GET /api/bookings/rooms`, lock-user
membership with `GET /api/lock-users`, and automation targets with `GET /api/automation/locks/tasks`.
Read the retained audit with `GET /api/events/page?sensorUuid=<DEVICE_ID>&page=0&size=40`; event
reads require the same authentication/tenant context, are safe and idempotent, and require no
additional approval. No delivery acknowledgement or physical-reset confirmation follows from
the deletion event. Re-enrollment may require a separate authorized hardware reset.

`DELETE /api/gateways/{id}` requires an ownership-changing approval. It returns `204` on success
and `404` when absent or unavailable in the selected tenant. It does not factory-reset hardware,
delete associated devices, or prove that commands already on hardware were cancelled. Verify
absence with `GET /api/gateways` and `GET /api/gateways/{id}`. An authorized destination claim uses
`POST /api/gateways/{id}/{name}`; verify a non-null response and destination inventory.

`POST /api/gateways/{id}/replacement-request` has no body and sends an authorized replacement
request for a registered tenant gateway. `204` means the request was submitted, not that a
replacement was ordered or delivered. `404` indicates an unavailable gateway/tenant; mail failures
may return `5xx`. This does not remove the gateway. Do not retry an ambiguous response automatically.

Gateway updates accept `pushNotificationDelayMinutes`, a positive minute value defaulting to 5.
Use `PUT /api/gateways/{id}` and verify with `GET /api/gateways/{id}`. The URL selects the gateway;
do not use the body ID to select another gateway. Offline events use action `1027`.

Account and tenant deletion are destructive. `DELETE /api/users/{id}/account` affects that user's
memberships across tenants. `DELETE /api/tenants` accepts the target tenant in its documented body;
the tenant context remains in the authentication headers. A successful HTTP response alone is
insufficient to establish every cleanup outcome. Read authorized membership and inventory state
before further actions. See the manifest for public response meanings and retry restrictions.

### User password changes

`PUT /api/users/{id}/password` accepts `{"password":"<NEW_PASSWORD>"}`. The ID comes from
`GET /api/users`. The password must be nonblank and at least six characters; whitespace is
preserved. Unrestricted tenant-bound API users may call it; Restricted identities receive `403`.
The target must belong to the tenant. A `204` confirms the account update, and the old password is
not required. This changes the account across all its tenants; it does not guarantee immediate
session termination. Obtain approval for that exact account-wide credential change, never echo
the password, and resolve ambiguous results with the account owner before another mutation.

### Reusable gateway Wi-Fi settings

| Operation | Method and path | Meaning |
|---|---|---|
| List saved networks | `GET /api/tenants/gateway-wifi` | `200` array of SSID/password entries; empty if none |
| Save one network | `PUT /api/tenants/gateway-wifi` | `204`; preserves other networks |
| Forget one network | `DELETE /api/tenants/gateway-wifi?ssid=<URL_ENCODED_SSID>` | `204`, including already absent |

Saving requires `{"ssid":"<SSID>","password":"<PASSWORD>"}`. SSIDs are 1–32 UTF-8 bytes;
passwords are 0–64 UTF-8 bytes, with empty permitted for an open network. Preserve exact case and
whitespace. A missing delete SSID returns `400` and deletes nothing. Unrestricted access is
required; Restricted identities receive `403`. Obtain approval before storing credentials and
confirm gateway connectivity separately. These operations do not configure or reconnect gateways.
Responses use `Cache-Control: no-store`; never log or expose credentials. Read before retrying an
ambiguous mutation and privately compare the intended entry. The manifest lists other errors.

## 12. SMART LOCK RECIPES

### 12.1 Pulse-open

```yaml
operation: pulse_open_smart_lock
risk: physical
approval_required: true
idempotent: false
method: POST
path: /api/smartlocks/{lockId}/pulse-open
body: null
preconditions:
  - lockId belongs to selected tenant
  - device type supports smart-lock operations
  - door purpose is known
success_meaning: command accepted or queued
physical_completion_confirmed: false
verification:
  - inspect device queue
  - inspect sensor events
  - re-read device state when available
automatic_retry: forbidden
```

Prefer `pulse-open` for ordinary access. Persistent operations require stronger confirmation:

```text
POST /api/smartlocks/{lockId}/open
POST /api/smartlocks/{lockId}/close
```

### 12.2 Add access codes

```http
POST /api/smartlocks/{lockId}/codes/add
Content-Type: application/json
```

```json
{ "codes": ["<VALID_PIN>"] }
```

```yaml
risk: security-sensitive
approval_required: true
code_constraint: 4-7 digits per current backend documentation
log_codes: forbidden
automatic_retry: forbidden
verification:
  - GET /api/smartlocks/{lockId}/codes/slots
  - inspect queue and related events
```

Code values are sensitive strings; preserve leading zeroes and satisfy the target lock's PIN
length. Never log them. Queue acceptance and a pending slot do not confirm lock installation.
Verify `GET /api/smartlocks/{lockId}/codes/slots`, delivery events and device state. Do not retry
an ambiguous mutation automatically.

Remove selected codes with `POST /api/smartlocks/{lockId}/codes/remove`. Deleting all codes with
`DELETE /api/smartlocks/{lockId}/codes` is destructive and requires explicit confirmation.

### Lock-user PIN length

`POST /api/lock-users` and `PUT /api/lock-users/{id}` (also `/api/lockusers`) require
all numeric PINs to contain exactly the selected tenant's `roomCodeLength` ASCII digits.
The setting accepts 4–7 and defaults to 4. Read it through `GET /api/tenants`; in the
portal open **Settings → Smart locks → Generated room code length**, save the setting,
then open **Access → Lock users → Create PIN code**. The PIN input accepts only digits,
limits input to that length, and requires the full length before adding or saving. Optional
PINs for MIFARE cards, including assignment from the event log, follow the same rule.
PIN entry is disabled until tenant settings load; a load failure requires reloading the page.
Leading zeros remain part of the PIN string.

Use the existing bearer authentication and selected `Tenant` header. The authentication
filter supplies tenant context; no tenant parameter is added. Existing authorization
rules apply. Example when `roomCodeLength` is 4:

```http
POST /api/lock-users
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
Content-Type: application/json

{"name":"Staff","sensorIds":["<LOCK_ID>"],"codes":["0123"]}
```

An invalid PIN returns `400` before saving or queuing; fix the payload or tenant setting
before resubmitting. `PUT` also validates retained MIFARE PINs, including when
`mifareCredentials` is omitted/null. Changing the tenant setting does not resize or delete
existing PINs; mismatched codes must be removed or replaced before the profile can be saved.
UID-only cards remain allowed. The optional `code` in
`POST /api/lock-users/{id}/mifare-credentials` uses the same exact-length validation.
The target lock's existing-code-length constraint still applies during dispatch.

Risk is security-sensitive access modification; obtain approval for the intended credentials
and assigned locks. A `200` returns the saved profile and means commands were accepted for
queueing, not physical delivery. `PUT` reconciles changes; `POST` creates a new profile and
is not idempotent. Do not automatically retry an ambiguous mutation: read the profile first,
then inspect upload status, lock code slots and actions `1028`/`1029` in `GET /api/events`
to confirm delivery. A missing profile on `PUT` returns `404`; authentication errors require
correcting credentials/tenant context before retrying.

### 12.2.0 Read lock-user numeric-code delivery status

`GET /api/lock-users` and `GET /api/lock-users/{id}` return computed upload status
on each lock user. The compatibility alias `/api/lockusers` has the same behavior.
Use the existing bearer authentication and selected `Tenant` header; tenant context
comes from the authentication filter, not an endpoint argument. Existing lock-user
role restrictions apply. Restricted users receive masked credentials, but device IDs
in the upload-status list remain available because they contain no credential values.

```http
GET /api/lock-users
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
Accept: application/json
```

Relevant response fields (other lock-user fields omitted):

```json
{
  "codesNotUploadedToAllSensors": 14,
  "sensorIdsWithCodesNotUploaded": ["lock-a", "lock-b", "lock-c", "lock-d", "lock-e", "lock-f", "lock-g"]
}
```

The count is pending **lock/code pairs**, not distinct locks: two missing codes on
seven locks yield 14 pairs and seven device IDs. `sensorIdsWithCodesNotUploaded`
is a distinct list of assigned code-capable sensors missing confirmation for at
least one numeric code. It is computed in the same pass as the count, before response
masking. Confirmation requires a matching slot in `ADDED_TO_LOCK` state with
`uploadedToLockAt` present. Missing slots, other states, or absent timestamps remain
pending. Unsupported or unresolved assigned sensors are excluded, matching the
existing count. No numeric codes or no pending pairs produces an empty list.
MIFARE and wallet credentials are not included in this numeric-code list.

This field is read-only, transient, and recalculated on list/get and the existing
create/update/MIFARE service responses. Clients must not submit it as desired state.
For a fresh status after other mutations, read the lock user again. Map these IDs to
names from tenant inventory; polling this response verifies stored delivery
confirmation without fetching or comparing credential values on the client.

Reading is idempotent, requires no additional operation approval, creates no queue
entries or events, and never repairs or resends codes. A successful response does
not by itself prove delivery: inspect the status fields. Retry transient read failures
with bounded backoff; do not retry authentication or authorization failures. List
returns `200` (including an empty array); get returns `404` for a missing user and
`400` for an invalid ID. Shared authentication failures are `401`/`403`.

### 12.2.1 Add a MIFARE credential to a lock user

A lock user is a logical access profile that holds credentials and the lock sensors those
credentials apply to. Numeric codes are set through the `codes` array on the lock user itself.
MIFARE card credentials are added one at a time through a dedicated route, in the same way a code is
added: the credential is stored on the lock user and then queued for every assigned lock sensor.

```http
POST /api/lock-users/{lockUserId}/mifare-credentials
Content-Type: application/json
```

```json
{ "mifareUid": "DEADBEEF", "code": "1234" }
```

`mifareUid` is the card UID as hex, with or without spaces, colons, or dashes. It must be 4, 7, or
10 bytes, that is 8, 14, or 20 hex characters, and is stored uppercase. `code` is optional. When it
is present the card and that PIN together form one two-factor credential. The PIN must contain
exactly the tenant's `roomCodeLength` ASCII digits (4–7; default 4), and match the length of
access codes already stored on the lock. When `code` is omitted
the card alone opens the lock.

```yaml
risk: security-sensitive
approval_required: true
uid_constraint: 4, 7, or 10 bytes of hex
code_constraint: optional; exactly tenant.roomCodeLength ASCII digits (4-7; default 4), same length as the lock's existing codes
supported_device_types: [lock_8015, lock_s42]
log_credentials: forbidden
idempotency: re-posting a UID already on the lock user replaces its PIN; it does not create a second entry
automatic_retry: forbidden
verification:
  - GET /api/lock-users/{lockUserId} and read mifareCredentialsNotUploadedToAllSensors
  - GET /api/smartlocks/{lockId}/codes/slots
  - GET /api/events for action 1028 with data.credentialType mifare or mifare_pin
```

Only smart locks with the extended credential store accept MIFARE credentials. Assigned sensors of
any other device type are skipped without error, so a `200` response does not mean every assigned
sensor received the credential; confirm per lock through the slot list. Credentials and numeric
codes share the same slot space on the lock.

The response is the updated lock user. `mifareCredentialsNotUploadedToAllSensors` counts assigned
lock/credential pairs the lock has not confirmed yet, the same way `codesNotUploadedToAllSensors`
does for numeric codes. A `200` means the credential was stored and queued, not that the physical
lock has it.

Remove one credential with `DELETE /api/lock-users/{lockUserId}/mifare-credentials/{mifareUid}`.
This queues removal from every assigned lock on which no other lock user still grants the same card.
Removing a UID the lock user does not have returns the unchanged lock user.

Deleting a lock user, or removing a sensor or credential through `PUT /api/lock-users/{id}`, queues
the same removals. `DELETE /api/smartlocks/{lockId}/codes` erases MIFARE credentials along with
numeric codes.

### 12.2.2 Wallet cards

Wallet card issuance and reader activation are separate capabilities. A card record, an installation
package, a phone installation, a lock assignment and a confirmed upload are distinct states.

| Purpose | Public operations |
|---|---|
| Card metadata | `GET/POST /api/wallet-certificates`; `GET/PUT/DELETE /api/wallet-certificates/{id}` |
| Phone installation artifact | `POST /api/wallet-certificates/{id}/package` |
| Send installation email | `POST /api/wallet-certificates/{id}/email` |
| Assign to a lock user | `POST /api/lock-users/{lockUserId}/wallet-certificates` |
| Remove a lock-user assignment | `DELETE /api/lock-users/{lockUserId}/wallet-certificates/{walletCertificateId}` |
| Room assignments | `GET/POST /api/bookings/rooms/{roomId}/wallet-certificates` |
| Remove a room assignment | `DELETE /api/bookings/rooms/{roomId}/wallet-certificates/{walletCertificateId}` |

Use the existing generated client and OpenAPI schemas for the complete request objects. All
operations use bearer authentication and tenant context, without a tenant argument. Platforms
are `APPLE` and `ANDROID`. Private keys and service-account material are never request inputs.
The response's credential ID is read-only and sensitive. Supported credential devices are
`lock_8015` and `lock_s42`; unsupported assigned sensors are skipped.

Package generation returns an Apple `application/vnd.apple.pkpass` artifact or Android JSON with
a short-lived `saveUrl` and `expiresAt`. Treat artifacts and links as secrets. Generating them
does not grant physical access or confirm installation. A card must be active and within its
validity window to enroll; inactive/expired new assignments return `409`. A future assignment
waits for its start date. Metadata updates or deleting a card can queue credential removal.
Offline locks retain credentials until removal reaches them, so pass expiry is not proof of
offline lock revocation. A shared credential remains while another assignment grants it.

The email operation accepts `{"email":"<RECIPIENT_EMAIL>"}`: one valid trimmed address, up to
254 characters, without line breaks, display names or lists. Obtain approval for that recipient
and send. `SUBMITTED` means SMTP acceptance; `SUPPRESSED` means no send under the current
recipient policy. Neither proves inbox delivery, phone installation or access. Email sends are
non-idempotent; never automatically retry an ambiguous result. Errors include `400` invalid
recipient, `404` missing card, `409` inactive/expired card, `502` unconfirmed submission and
`503` unavailable package generation. Do not expose an installation link in agent output.

Verify card metadata with `GET /api/wallet-certificates/{id}`, phone installation on the phone,
and assigned lock upload through slots and events `1028`/`1029`. See
`wallet_certificate_policy` in the manifest for card design and assignment details.

### 12.2.3 Wallet NFC readers

Read `GET /api/sensor/{id}` and `configuration.walletNfc`; Google and Apple status are separate.
Absent/unknown status does not establish support. The initial unknown projection is
`{"supported":false,"active":false,"status":"unknown","setupRequired":true}`.
Google reader support is experimental for `lock_s42` firmware 117 or later and is not a
Google-certified terminal implementation. Apple VAS reader support is unavailable in this firmware;
Apple pass generation does not establish reader support.

Use the generated `sensorAction` operation with unrestricted access:

```http
POST /api/sensor/<DEVICE_ID>/action
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
Content-Type: application/json

{"action":"wallet_nfc_setup","value":"google"}
```

| Action | Effect |
|---|---|
| `wallet_nfc_setup` | Enable NFC on the selected lock and start reader provisioning |
| `wallet_nfc_status` | Query reader status |
| `wallet_nfc_activate` | Activate a verified installed profile after propagation |
| `wallet_nfc_disable` | Disable reader use while retaining keys |
| `wallet_nfc_purge` | Disable and erase local merchant profiles |
| `wallet_nfc_rotate` | Start replacement on previously enrolled tenant locks |
| `wallet_nfc_delete` | Delete an inactive profile; decimal key version in string `subAction` |
| `wallet_nfc_revoke` | Revoke a retired public key; decimal key version in string `subAction` |

All use `value=google`. Never put keys, certificates or a tenant ID into the action body.
Mutations require explicit approval for their scope; rotation affects previously enrolled locks
and purge erases local merchant profiles. `value=apple` returns `409`. Limited-role identities
receive `403`; invalid action/platform/key version returns `400`, unavailable device `404`,
state conflicts `409` and unavailable configuration/platform `503`.

An HTTP `200` means queued, not active. Public statuses include `unknown`, `unsupported`,
`setup_required`, `provisioning`, `staged`, `active`, `disabled`, `failed`, `unconfirmed` and
`nfc_disabled`. Inspect `requestId`, `errorCode`, `readyAt`, `observedAt` and the public snapshot
when provided. Reported runtime flags alone do not verify a profile or radio health. An active
reader also requires enabled NFC. Firmware or security-session changes invalidate old confirmation.

Explicit action validation errors use `application/problem+json`; read safe `detail` and `status`
instead of guessing from HTTP `409`. Decode JSON Blobs/strings when older generated clients return
those forms. Public device errors distinguish invalid configuration, stale generation, busy,
full profiles, missing profiles, protected active keys, storage failure, unsupported operation and
key-version collision. Display unknown codes as text without exposing private diagnostics.

Provisioning can wait for up to 24 hours of platform propagation; requests can become unconfirmed
after 120 seconds. Read status before any explicitly approved retry. Rotation is non-idempotent.
Revocation requires verified replacement across the recorded locks; offline/unknown devices can
block it. Revoking a cloud key does not instantly update phones. Purging a reader does not remove
phone passes or card credentials. Verify `walletNfc`, event `1038`, NFC state, card enrollment and
a real phone tap independently. A tap diagnostic alone does not prove accepted access.

### 12.3 Device configuration and tenant defaults

| Purpose | Public operation |
|---|---|
| Read configuration | `GET /api/smartlocks/{id}/configuration` |
| Set overrides | `PUT /api/smartlocks/{id}/configuration` |
| Reset one override | `DELETE /api/smartlocks/{id}/configuration/{field}` |
| Reset all overrides | `DELETE /api/smartlocks/{id}/configuration` |

An override takes precedence over the tenant default. A sparse `overrides` object preserves
omitted keys; null removes an override. A value equal to the default follows future default
changes. Unknown keys return `400`. Supported fields are `soundLevel` (`off`, `low`, `medium`,
`high`), sensitive six-digit-or-empty `systemCode`, `nfcEnabled` on S42, `accessMode` and
`googleWalletEnabled` on compatible S42 firmware. Obtain approval for device changes.

```json
{"overrides":{"soundLevel":"low","nfcEnabled":true}}
```

Reads and resets expose `defaults`, `overrides`, `effective`, `reported`, capability flags and
`configurationDeliveryPending`. A PUT returns a `MessageFrame`; a null message does not establish
that no asynchronous reader work was requested. A `409` can follow a settings save when delivery
is pending. Read configuration and queue state before an approved retry. HTTP success does not
prove physical application; offline devices keep previous settings until delivery.

`GET/PUT /api/tenants` includes supported tenant defaults. `roomCodeLength` is 4–7 (default 4)
and affects newly generated codes without rewriting existing codes. Lock code lengths must remain
compatible. `walletEnabled` controls card management; `googleWalletReaderEnabled` controls the
reader default, falling back to `walletEnabled` when unset. Device overrides remain independent.
Enabling reader settings can initiate tenant-wide asynchronous work; approve that scope first.

`PUT /api/sensor/{id}` cannot overwrite authoritative reported device or reader state. The URL
selects the device; unknown devices return `404`. For configuration controls in the portal, open
**Devices**, the supported device's three-dot menu, then **Configuration** or **Wallet NFC**.

Read-only `bootHistory` retains up to 20 recorded boot observations. `unstable` reflects at least
three recorded boots within six hours, and `unstableSince` identifies the current incident.
These are observations rather than diagnoses; do not provoke reboots for verification.

Battery-instability events use action `49` and `data.state=suspected_motor_brownout` for
`lock_8015` and `lock_s42`. A report suggests a restart during motor operation; it does not prove
battery damage. Pending motor commands may be cancelled, but already sent commands cannot be
recalled. Inspect batteries and the queue before approving another motor command. Notification
preference `sensorBatteryUnstable` is exposed by the documented user notification-settings
operations; it is independent of low-battery alerts. Read events to verify a report, not notification
delivery. Never trigger physical commands merely to test a warning.

### 12.4 Read and set the tenant-wide lock access mode

```http
GET /api/smartlocks/configuration/access-mode
PUT /api/smartlocks/configuration/access-mode
Authorization: Bearer <token>
Tenant: <TENANT_ID>
Content-Type: application/json
```

```json
{
  "accessMode": "standard"
}
```

The access mode is the default inherited by keypad locks, lock controllers, and wireless code
panels in the tenant (device types 7, 8, 9, and 10), unless a device overrides it. It is the same tenant setting as the `accessMode` field
of the tenant resource; these endpoints exist so a client can read and change only that value
without submitting a full tenant object.

| Value | Device behavior |
|---|---|
| `standard` | A valid code opens the lock and the device closes again on its own. |
| `openUntilClosed` | A valid code keeps the lock open until `*` is pressed on the keypad, a close command is sent, or the physical system menu locks it. |
| `forcedClosed` | Local codes and cards are refused and reported as invalid. The lock can only be opened over the API or from the physical system menu. |

A device that is already held open is never closed by a credential, in any mode: after an
`open` command, a system-menu unlock, or an `openUntilClosed` latch, a valid code or card is
reported as valid and confirmed on the device, but does not schedule a close behind it. The timed
openings are unaffected, so `pulse-open` and the `standard` grant still close on their own.

`GET` returns the stored mode together with `allowedModes`, the list of values this backend
accepts. A tenant that has never been configured reads as `standard`, which is also how a device
with no stored mode behaves.

`PUT` accepts only the three values above; anything else returns 400. A successful save persists
the tenant default and queues an action-27 configuration message only where a device's effective
settings change, with update-time set to `false`. Device overrides remain in effect. Delivery is asynchronous: the 200 response means saved and
queued, not applied. A device that is out of range keeps its previous mode until it is heard from
again, and a mode changed locally on a keypad (system menu option `8`) stays in effect on that
device until the tenant configuration is delivered again.

`forcedClosed` prevents local codes/cards on affected devices from opening the lock and closes a lock that
`openUntilClosed` was holding open. It does not disable the API open commands or the physical
system menu. Confirm the operational intent before switching a tenant into it, and confirm that at
least one supported way in remains for the people on site.

```yaml
risk: physical-or-operationally-dangerous
approval_required: true
idempotent: true
automatic_retry: forbidden-after-ambiguous-response
verification:
  - GET /api/smartlocks/configuration/access-mode confirms the stored tenant value only
  - GET /api/sensor/{sensorId} configuration.reportedAccessMode confirms what a device actually runs
  - inspect the device queue
  - confirm delivery or acknowledgement
  - test a code on the physical lock before relying on the new mode
```

## 13. RELAY RECIPES

```text
POST /api/relay/{relayId}/open
POST /api/relay/{relayId}/open-until-closed
POST /api/relay/{relayId}/close
POST /api/relay/{relayId}/pulse/ms/{milliseconds}
POST /api/relay/{relayId}/pulse/seconds/{seconds}
POST /api/relay/{relayId}/pulse/minutes/{minutes}
POST /api/relay/{relayId}/pulse-open
```

```yaml
risk: physical-or-operationally-dangerous
approval_required: true
idempotent: false
mandatory_preconditions:
  - relay real-world purpose known
  - safe duration known
  - target device and tenant confirmed
warning: relay may operate a door, heater, motor, appliance, or alarm interface
automatic_retry: forbidden
```

Generate a package for direct delivery to a relay (for example, by a mobile app over BLE):

```http
POST /api/relay/{relayId}/package
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
Content-Type: application/json
```

Persistent open and close:

```json
{ "operation": "open" }
```

```json
{ "operation": "close" }
```

Timed pulse (unit must be `milliseconds`, `seconds`, or `minutes`):

```json
{
  "operation": "pulse",
  "value": 5,
  "unit": "seconds"
}
```

Consumption-limited open accepts an energy allowance in kilowatt-hours:

```json
{
  "operation": "consumption",
  "kwh": 1.5
}
```

The backend converts `kwh` to a device pulse allowance and returns `consumptionPulseCount`.
Invalid or out-of-range values are rejected. `kwh: 0` cancels an active countdown and
closes the relay. Deliver the generated package unchanged.

A successful response returns the selected protocol `action` and `subAction`, a generated
`messageId`, and the complete node-core package as both `packageBase64` and `packageHex`.
Decode exactly one representation and deliver those bytes unchanged. The endpoint only creates
the package: it does not queue, deliver, or execute it, and HTTP 200 does not confirm physical
completion.

```yaml
risk: physical-or-operationally-dangerous
approval_required: true
mandatory_preconditions:
  - relay belongs to the authenticated tenant
  - relay real-world purpose is known
  - target device, operation, and bounds are explicitly confirmed
  - a direct transport to the intended relay is available
idempotent: false
automatic_retry_generation: allowed only before any delivery attempt
automatic_retry_delivery: forbidden
verification:
  - verify transport-level delivery
  - verify device acknowledgement or current relay state
  - do not expect a gateway queue entry or backend event from package generation
errors:
  - 400 for a non-relay sensor, unknown operation, missing pulse value/unit, missing or non-finite kwh, invalid calibration, or an out-of-range calculated pulse count
  - 404 when the sensor does not exist in the tenant
```

Set default pulse duration:

```http
PUT /api/relay/{relayId}/default-milliseconds
Content-Type: application/json
```

```json
{ "openMilliseconds": 150 }
```

### 13.1 Scheduled lock automation

Use `GET /api/automation/locks/triggers/config` to discover trigger definitions. Task operations
are `GET/POST /api/automation/locks/tasks`, `PUT/DELETE /api/automation/locks/tasks/{taskId}` and
`POST /api/automation/locks/tasks/{taskId}/run`. They require superuser access; limited callers
receive `403`. The Lock Automation module must be enabled for execution. Disabling it suspends
execution while leaving tasks manageable.

Triggers are `open`, `close`, `pulse_open`, `add_code` and `remove_code`. Movement triggers support
locks/controllers and relays. Code triggers require standalone numeric PINs on code-capable
locks/controllers; they do not support relays, cards or wallet credentials. Every target must
support the chosen operation. PINs are strings of 4–7 ASCII digits and must match each device's
existing PIN length. A PIN managed by a lock user cannot be used as a standalone task PIN.

Schedules support `ONCE`, `DAILY`, `WEEKLY` and `MONTHLY`, with interval counted from `startDate`.
Weekly schedules need weekdays and monthly schedules need month days. Nonexistent month days are
skipped. Use `HH:mm` time and `YYYY-MM-DD` dates; the default zone is the tenant zone. Scheduled
execution is approximate and missed occurrences can be skipped. A scheduled removal is not a
credential-expiry guarantee: a PIN may remain if removal is missed or not delivered.

Use generated OpenAPI schemas for task requests. Creation and run-now are non-idempotent;
after an ambiguous result read tasks, queues and events before any authorized retry. An update
replaces task configuration; for code triggers an omitted/null code preserves the existing code,
while masked/empty values are rejected. Switching to a movement trigger requires code omitted/null
and clears it. Task responses can contain the real PIN under the caller's response masking policy;
never copy it into task names, events, logs or agent output.

Run-now can return HTTP `200` even if some or all devices failed. Inspect every per-device status.
`queued`, `already_present`, `already_pending` and `already_absent` describe accepted intent or
server-side no-ops, not physical delivery. Verify events `1036`/`1037`, structured `occurrence`,
queue state and the device. Manual occurrences use `manual:<runId>`. A manual run can overlap a
scheduled run. Deleting/disabling a task does not recall commands already queued or remove PINs
it previously installed. Obtain explicit approval for unattended physical/security-sensitive work.
The manifest's `lock_automation_policy` defines status meanings and per-operation retry rules.

## 14. THERMOSTAT AND TEMPERATURE RECIPES

```http
POST /api/thermostat/{thermostatId}/target-temperature
Content-Type: application/json
```

```json
{
  "temperature": 21.0,
  "gw_id": "<OPTIONAL_GATEWAY_ID>"
}
```

```text
POST /api/thermostat/{thermostatId}/on
POST /api/thermostat/{thermostatId}/off
POST /api/thermostat/{thermostatId}/restart
POST /api/thermostat/{thermostatId}/wifi
POST /api/thermostat/{thermostatId}/delete-wifi
GET  /api/temperature-control/stats
GET  /api/temperature-control/history/{sensorId}
```

Wi-Fi credentials are secrets. Never print or persist them outside the intended secret store.

### 14.1 Decode temperature and humidity

Nodes report measurements inside their Bluetooth advertisement. `GET /api/sensor` returns every
sensor of the tenant with that advertisement attached as `adv_data`, whose `sensor_data` field is the
three measurement bytes as an uppercase hex string, six characters, byte 0 first.

```json
{
  "id": "<SENSOR_ID>",
  "type": "temperature",
  "unit": "read",
  "temperatureC": 20.92,
  "lastHeardFrom": "2026-01-14T09:12:04.000+00:00",
  "adv_data": {
    "node_type": 4,
    "battery_level": 87,
    "sensor_data": "2C082D"
  }
}
```

On temperature nodes — `type` `temperature` (node type 4) and `wall_thermostat` (node type 11) —
the three bytes decode as follows.

| Byte | Meaning | Decoding |
|---|---|---|
| 0-1 | Temperature | signed 16-bit little-endian hundredths of a degree Celsius: `celsius = int16le(byte0, byte1) / 100` |
| 2 | Relative humidity | unsigned byte, whole percent, `0`-`100` |

Bytes 0-1 equal to `FFFF` mean the node has no valid temperature reading. In the example above,
bytes `2C 08` are `0x082C` = 2092, so 20.92 °C, and byte `2D` is 45 % relative humidity.

The backend decodes the temperature already and returns it on every sensor as `temperatureC` in
degrees Celsius. Prefer that field; decode bytes 0-1 yourself only when verifying a raw
advertisement. When the sensor is not a temperature node, has never advertised, or carries the
`FFFF` no-reading marker, `temperatureC` is the non-numeric value NaN and is serialized as the
string `"NaN"`. Treat that as "no reading"; never report it as a measurement, and never coerce it to
`0`.

Humidity is not decoded, aggregated, or stored anywhere in the backend. Byte 2 of `sensor_data` on
`GET /api/sensor` is the only source, and it is a live value only: there is no humidity history and
no humidity alarm.

On relay nodes (`relay`, `high_voltage_relay`) byte 0 is the open state, `00` closed and `01` open,
and bytes 1-2 are unused. Every other node type reports `000000`.

Lock nodes (`lock_8015`, `lock_s42`, `lock_controller`, `lock_wireless_code_panel`) report their
open state in `adv_data.node_settings` instead, not in `sensor_data`. `node_settings` is three bytes
as an uppercase hex string; byte 0 carries bit flags:

| Mask | Meaning |
|---|---|
| `0x0F` | advertising power profile, `0`-`9` |
| `0x10` | lock is held open |
| `0x80` | node uses the encrypted communication layout |

Bit `0x10` is set while the lock is open with nothing scheduled to close it: a backend open, a
forced open, a system-menu unlock, or an open-until-closed latch. It is clear for a timed open,
which closes itself, so a pulse open does not raise it. On the wireless code panel the bit
describes the paired relays the panel drives. The node re-advertises within moments of the state
changing rather than waiting for its next periodic advertisement. Firmware older than v115 always
reports the bit as `0`, and mask the byte rather than comparing it whole, since the power profile
and encryption bits share it.

Readings are only as fresh as the last advertisement the gateways heard. Judge age with
`lastHeardFrom` before acting on a value, and do not treat an unchanged reading as proof the node is
online. For historical or aggregate temperature use `GET /api/temperature-control/history/{sensorId}`,
which returns 5-minute readings already decoded to `temperatureC`, and `GET /api/temperature-control/stats`,
which returns the newest 5-minute snapshot with `averageTempC`, `lowestTempC`, `highestTempC` and the
`sensorCount` that contributed. Sensors without a valid reading are excluded from both, and no
snapshot is written for an interval in which no sensor had one.

```yaml
risk: read-only
approval_required: false
idempotent: true
sources:
  - GET /api/sensor for the current temperature and the only humidity value
  - GET /api/temperature-control/history/{sensorId} for stored per-sensor temperature readings
  - GET /api/temperature-control/stats for the newest tenant-wide temperature snapshot
decoding:
  temperature: signed-16-bit-little-endian-hundredths-celsius-from-sensor_data-bytes-0-1
  temperature_no_reading_marker: FFFF
  humidity: unsigned-percent-from-sensor_data-byte-2
verification:
  - compare temperatureC with bytes 0-1 of adv_data.sensor_data
  - check lastHeardFrom before treating a reading as current
never:
  - report a NaN temperature as a measurement
  - expect humidity in the temperature history or stats endpoints
```

## 15. DEVICE PAIRING

```http
PUT /api/sensor/{sensorId}/pairings
Content-Type: application/json
```

```json
{
  "sensorIds": [
    "<PAIRED_DEVICE_ID_1>",
    "<PAIRED_DEVICE_ID_2>"
  ]
}
```

```yaml
read_current: GET /api/sensor/{sensorId}/pairings
fetch_from_hardware: POST /api/sensor/{sensorId}/pairings/fetch
risk: configuration-changing
approval_required: true
verification: compare stored and fetched pairings
```

## 16. FIRMWARE LIFECYCLE

```text
GET    /api/node-updates/firmwares
POST   /api/node-updates/sensors/{sensorId}
DELETE /api/node-updates/sensors/{sensorId}
DELETE /api/node-updates/sensors/{sensorId}/queue
```

Start with `{"version":"<AVAILABLE_VERSION>"}` using a compatible version returned by the public
catalog. Firmware changes require a known target, stable power/connectivity, a maintenance window,
understood rollback limits and explicit approval. Never automatically retry an ambiguous start.
HTTP success means accepted work; verify update progress, events and the reported device firmware.

During an update, regular commands can remain queued and new non-update commands can be rejected.
A concurrent start or generic queue deletion during an active update returns `409` without changing
the running update. Other devices are unaffected. Cancellation through
`DELETE /api/node-updates/sensors/{sensorId}` returns `200` with the removed update-package count,
including zero; it does not establish the physical device's firmware or rollback state.

For smart-lock transitions from legacy firmware to version 111 or later, slots 1–987 migrate and
slots 988–1980 require codes to be pushed again. A downgrade to legacy firmware requires all codes
to be pushed again. Warn the operator and plan code resynchronization before approving a version
transition. Do not infer access availability from successful update submission.

## 17. QUEUE AND EVENT VERIFICATION

```yaml
queue_endpoints:
  tenant: GET /api/gateways/getqueue
  device: GET /api/gateways/queue/device/{deviceId}
  device_transfer_packages: GET /api/gateways/queue/device/{deviceId}/packages
  gateway: GET /api/gateways/{gatewayId}/gwqueue
event_endpoints:
  tenant: GET /api/events
  device: GET /api/events/sensor/{sensorId}
  room: GET /api/events/byRoom/{roomId}
  paged: GET /api/events/page
```

`GET /api/events/page?page=0&size=40` reads the newest tenant events first. The response is a
page with `content`, `totalElements`, `number`, `size`, and `last`; page numbers start at 0.
Request subsequent pages until `last` is true. `size` defaults to 40 and must be 1–100. Optional
`from` and `to` must be supplied together as inclusive ISO-8601 instants, for example
`GET /api/events/page?page=0&size=40&from=2026-04-01T00%3A00%3A00Z&to=2026-04-15T23%3A59%3A59Z`.
Add one of `sensorUuid=<uuid>`, `roomId=<id>`, or `bookingId=<id>` to filter; these filters
cannot be combined, and room queries require the time range. A supplied `bookingId` must not be
blank. Results are ordered by descending creation time and ID. Invalid pagination,
filters or dates return 400; an unknown room returns 404. The same bearer authentication and
`Tenant` header as other event reads are required. This paginated endpoint allows `Receptionist`,
`Restricted`, or unrestricted access (an empty role list). Receptionist responses censor access codes
for all page filters, including room queries. Missing or invalid authentication returns 401; a role
without access returns 403. Correct authentication or permissions before retrying those failures.
This is a low-risk read with no request body, device command, or queue change. It has no physical
effect, needs no approval, and is idempotent and safe to retry. Offset pages can shift
when events arrive between requests, so clients should deduplicate by event ID and refresh the first
page for new activity. A 200 means only that events were retrieved; an event's presence alone does
not prove that a physical device completed an operation. Verify the specific operation and device
state according to its command contract.

To read the recorded timeline for one booking, use its `Booking.bookingId`, rather than another identifier, and authenticate in that booking's tenant:

```http
GET /api/events/page?bookingId=booking-123&page=0&size=40
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
```

There is no request body or tenant query argument. Optional `from` and `to` bounds select event
creation time and must be supplied together. Direct matches use exact `data.bookingId` in the
tenant's events. The endpoint also finds otherwise unlinked access/code events by codes recorded
in the booking's retained directly linked events. Results are deduplicated, and optional `from`/`to` bounds apply to both kinds of result. No current booking
lookup is required: retained events and code history for a deleted booking remain usable. An unknown booking ID
or a booking with no matching events returns 200 with an empty `content` array and
`totalElements: 0`, rather than 404. A blank booking ID, conflicting filters, invalid page/size,
or invalid date bounds returns 400; correct the input before retrying.

Results may contain booking creation (1033), update or checkout (1034), deletion (1035), sent
messages (1030), and device events that carry that booking ID. Code correlation additionally
includes credential-result events (action 33, sub-actions 8/9/12/13) and code add/remove events
(1028/1029) without a saved booking link. For lock action 33, sub-actions
8/12 report accepted PIN/extended credentials and 9/13 report rejected credentials. Interpret
`data.valid` as a string; other credential metadata may be absent. Accepted credentials do not
prove physical entry. Use the event registry below for the other action and metadata meanings.

Code discovery reads `data.code` from all retained directly linked booking events, including
events outside the requested date range or page. Leading zeros are preserved and codes match
exactly. Inferred events must have `createdDate` within at least one inclusive `data.start` /
`data.end` stay window recorded in those linked events. All valid recorded stay windows are
considered, so earlier snapshots can cover an access event even if checkout later shortened
the booking. Missing, malformed, or reversed stay bounds are ignored; without any valid window
or recorded code, only directly linked events are returned. Events already linked to a different
booking are excluded from inference. Code correlation spans the tenant's devices and has no
additional device filter. Reuse of the same code within a recorded stay window can still make
inferred attribution ambiguous; do not treat it as certain guest identity or proof of entry.

Returned events can lack `data.bookingId`; do not discard them solely for that reason.

This is a partial recorded timeline: unrelated events and unrecorded changes are outside its coverage. Booking update events contain selected snapshot values,
not a complete list of field changes with old and new values. An empty result does not prove
that no changes or access attempts occurred. Apply the same role permissions and Receptionist
code censoring described above; contacts, message bodies, and credential identifiers may still
be sensitive. This low-risk read needs no approval, has no physical effect or queue entries,
and is idempotent. Retry transient read failures with bounded backoff and deduplicate event IDs.
Verify retrieval through `content`, `totalElements`, and `last`, then request subsequent pages
until `last` is true; use fixed bounds for historical reads. Verify physical operations separately
through device state and the operation's documented confirmation events.

Booking update events use `action: 1034`. Inspect `data.state` instead of inferring a
transition from the booking snapshot: `checked_out` means the booking changed from not checked
out to checked out, while `updated` means another field changed and may still contain
`checkedOut: "true"` as the current state. Treat only `data.state: "checked_out"` as a checkout
event. Event reads are safe and require the same bearer authentication and tenant context as the
other tenant-scoped API operations.

### 17.0.1 Event action registry

Events have two action namespaces. Values `0` through `40`, `48` for Google Smart Tap and `49` for a suspected motor brownout come from the device protocol. Values
`1024` through `1039` are server-generated application events. Do not compare a `sub_action`
without first checking its parent `action`.

| Action | Device-protocol meaning | Action | Device-protocol meaning |
|---:|---|---:|---|
| 0 | gateway online | 1 | button pressed |
| 2 | passive alarm triggered | 3 | active alarm triggered |
| 4 | temperature high | 5 | unusual motion |
| 6 | battery low | 7 | power surge |
| 8 | water leakage | 9 | unauthorized access |
| 10 | door left open | 11 | ventilation anomaly |
| 12 | freezing temperature | 13 | high air pressure |
| 14 | temperature too low | 15 | device online |
| 16 | device offline | 17 | gateway status |
| 18 | test | 19 | alarm cleared |
| 20 | update advertising profile | 21 | firmware update |
| 22 | firmware update chunk | 23 | firmware update chunk complete |
| 24 | restart node | 25 | new node |
| 26 | ask for time | 27 | set time |
| 28 | relay pulse, milliseconds | 29 | relay pulse, seconds |
| 30 | relay open | 31 | relay close |
| 32 | relay pulse, minutes | 33 | lock operation |
| 34 | wall thermostat operation | 35 | restart |
| 36 | restart mode on | 37 | restart mode off |
| 38 | gateway ping with status | 39 | gateway metering data |
| 40 | relay pulse count | 48 | Google Smart Tap provisioning / diagnostics |
| 49 | suspected motor brownout restart | — | — |

| Action | Application event | `data.state` | Important data |
|---:|---|---|---|
| 1024 | room marked cleaned | `cleaned` | `entityId`, optional `entityName`, `actorUserId` |
| 1025 | room marked dirty | `dirty` | `entityId`, optional `entityName`, `actorUserId` |
| 1026 | gateway marked online | `online` | `entityId`, `actorUserId` |
| 1027 | gateway marked offline | `offline` | `entityId`, `actorUserId` |
| 1028 | smart-lock code added | `added` | device identity, sensitive `code`, `actorUserId` |
| 1029 | smart-lock code removed | `removed` | device identity, sensitive `code`, `actorUserId` |
| 1030 | booking message sent | not set | booking/room, channels, recipient and message fields |
| 1031 | sensor restart mode enabled | `on` | device identity, `actorUserId` |
| 1032 | sensor restart mode disabled | `off` | device identity, `actorUserId` |
| 1033 | booking created | `created` | booking snapshot |
| 1034 | booking updated | `updated` or `checked_out` | booking snapshot; only `checked_out` is a checkout transition |
| 1035 | booking deleted | `deleted` | final booking snapshot |
| 1036 | lock automation dispatch accepted or successful code no-op | `queued`, `already_present`, `already_pending`, `already_absent` | `taskId`, `taskName`, `trigger`, `occurrence`; no PIN |
| 1037 | lock automation failed | producer status or `failed` | task and occurrence details; no PIN or exception text |
| 1038 | wallet reader provisioning / tap diagnostic | see §12.2.3 | public profile, request ID, outcome and timing; no private keys |
| 1039 | sensor deleted from inventory | `deleted` | `entityType=sensor`, `entityId`, `entityName`, `actorUserId`, `actorName`; does not prove complete cleanup or a physical reset |

Action-specific sub-actions:

| Parent action | Sub-action values |
|---:|---|
| 33, lock operation | 1 pulse open; 2 open; 3 close; 4 add codes; 5 remove codes; 6 set configuration; 7 delete all codes; 8 valid legacy PIN; 9 invalid legacy PIN; 10 pair devices; 11 fetch paired devices; 12 valid extended credential; 13 invalid extended credential; 14 add extended credential; 15 closed by `*` |
| 34, wall thermostat | 1 set Wi-Fi; 2 set target temperature; 3 turn on; 4 turn off; 5 restart; 6 delete Wi-Fi; 7 receive debug data |
| 39, gateway metering | 12 five-minute; 13 hourly; 14 total; 15 consumption changed |

Sub-action `15` is reported by the lock itself when someone presses `*` to end an
open-until-closed hold, on firmware v115 and later. It carries no credential and no payload, so it
has none of the code or credential `data` keys: the event is the fact that the lock was closed at
the door, with `sensor_uuid` and the event timestamp. A `*` press on an already closed lock reports
nothing. Locks running earlier firmware never send it, so its absence is not evidence that a lock
was not closed.

Extended credential result events (action 33 with sub-action 12 or 13) expose `slot`, `valid`,
`state`, `factorCount`, `credentialType`, and `credentialId`. MIFARE factors additionally expose
`mifareUid`; wallet factors expose `walletPlatform`; PIN factors use `code`. A rejected credential
uses slot `0`. Credential identifiers and PINs are security-sensitive.

Common structured `data` keys are `entityType`, `entityId`, `entityName`, `state`,
`actorUserId`, `roomId`, `bookingId`, `code`, `slot`, `valid`, `factorCount`, `credentialType`,
`credentialId`, `mifareUid`, `walletPlatform`, `triggerId`, `taskId`, `taskName`, `trigger`,
`occurrence`, `channels`, `message`, `emailMessage`, `smsMessage`, `recipient`, `recipientEmail`,
and `recipientPhone`. Keys are event-specific and may be absent. Access codes, recipient details,
and message bodies are sensitive and must not be exposed outside their authorized purpose.

Example checkout transition:

```json
{
  "action": 1034,
  "sub_action": null,
  "roomId": "room-101",
  "data": {
    "entityType": "booking",
    "entityId": "booking-123",
    "bookingId": "booking-123",
    "roomId": "room-101",
    "state": "checked_out",
    "checkedOut": "true",
    "actorUserId": "system"
  }
}
```

```yaml
authentication: "Authorization: Bearer sat_<TOKEN>"
tenant_context: "Tenant: <TENANT_ID> is required and is resolved by the authentication filter"
preconditions:
  - use an event endpoint appropriate to the tenant, device, or room
  - provide valid inclusive ISO-8601 bounds where required
risk: read-only
approval_required: false
idempotency: safe
retry_policy: retry transient read failures with bounded backoff; do not create conclusions from duplicate records
verification:
  - identify the event by action and structured data
  - interpret sub_action only under its parent action
  - treat queued as accepted, not physically completed
  - corroborate physical operations with later device state or device-originated events
errors:
  - 400 means an invalid identifier or time range
  - 401 or 403 means authentication or authorization failed
  - 404 on a room query means the room was not found
```

Verification algorithm:

```text
1. Capture the returned message ID and target device.
2. Set local status to requested or queued.
3. Inspect device and gateway queue state.
4. Inspect relevant events.
5. Re-read current device state when supported.
6. Report exactly one state:
   requested | queued | delivered | confirmed | failed | unknown
7. Never translate queued into completed.
```

### 17.1 Manually transfer a device queue

```http
GET /api/gateways/queue/device/{deviceId}/packages
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
```

The response is an array in outbound queue order. Each entry contains `deviceId`, `queuedAt`,
`messageId`, `action`, `subAction`, `packageBase64`, and `packageHex`. The package fields encode
the same complete 212-byte node-core message. Decode exactly one representation and deliver the
bytes unchanged through the device's direct transport.

This endpoint is read-only and tenant-scoped. It preserves the queued message ID, timestamp,
payload, and checksum, and does not mark, remove, or acknowledge a message. An empty array means
the tenant currently has no pending messages for that device.

```yaml
risk: depends-on-queued-operation
approval_required_before_delivery: inherit from each queued operation
download_idempotent: true
automatic_retry_download: allowed before delivery
automatic_retry_delivery: forbidden
mandatory_preconditions:
  - target device and tenant confirmed
  - queued action and sub-action understood
  - direct transport reaches the intended device
delivery_order: preserve response order
sensitive_data:
  - packages may contain credentials, access codes, or configuration
  - never log or persist decoded payloads outside approved secure storage
verification:
  - require device or transport acknowledgement for each message ID
  - verify resulting device state when supported
  - HTTP 200 confirms download only, never delivery or physical completion
queue_removal:
  endpoint: DELETE /api/gateways/queue/message/{messageId}
  precondition: remove only after positive device acknowledgement for that message ID
  automatic_removal_on_download: false
errors:
  - 500 when a queued node-core message cannot be serialized
```

### 17.2 Node-core package format

Lock packages, relay packages, and downloaded queue packages use the same fixed 212-byte message:

| Offset | Length | Field | Encoding |
|---:|---:|---|---|
| 0 | 6 | message ID | raw bytes; displayed as 12 uppercase hex characters |
| 6 | 2 | timestamp | unsigned 16-bit Unix-seconds value, little-endian |
| 8 | 1 | action | unsigned protocol action |
| 9 | 1 | sub-action | unsigned protocol sub-action |
| 10 | 201 | data | operation-specific bytes followed by zero padding |
| 211 | 1 | checksum | XOR of bytes 0 through 210 |

The timestamp contains the low 16 bits of Unix time and therefore wraps. Do not interpret it as
a standalone wall-clock timestamp. `packageBase64` and `packageHex` encode the entire message,
including its checksum; clients must decode one representation and must not recalculate, replace,
or otherwise modify fields in a downloaded queued package.

The node-core package is not itself a complete BLE transport specification. Service UUIDs,
characteristics, MTU negotiation, chunk framing, write mode, timeouts, and acknowledgement frames
must come from the supported device transport library or firmware protocol for the target device.
Do not guess these values. If no supported transport implementation is available, stop before
delivery.

Queue downloads can contain any queued device command, including security-sensitive configuration,
access-code payloads, restart operations, pairing operations, or firmware traffic. Inspect `action`
and `subAction`, determine that the target transport supports that operation, and apply the original
operation's approval policy. Downloading does not reserve a queue entry or suspend gateway delivery;
avoid manual transfer while a gateway can concurrently deliver the same command.

### 17.3 Tested mobile BLE discovery and delivery

This section defines the tested direct-delivery implementation for Solvotix node-core devices. It
applies when a mobile application must find a nearby device and deliver a package returned by the
relay package endpoint or manual queue-transfer endpoint.

```yaml
advertisement:
  expected_local_name: SVN
  solvotix_manufacturer_id: 0x79fd
  local_name_reliable_on_android: false
node_core_gatt:
  service_uuid: 12345678-1234-5678-1234-56789abcdef0
  write_characteristic_uuid: 12345678-1234-5678-1234-5678efbeadde
  package_bytes: 212
  preferred_write_mode: write-without-response
  fallback_write_mode: write-with-response-when-characteristic-requires-it
  maximum_chunk_bytes: 215
```

Do not use the backend `active`, online, or offline field to determine physical proximity. That
field describes backend communication state, not whether the phone currently receives the device's
BLE advertisement.

Discovery algorithm:

```text
1. Load the tenant's sensor inventory and normalize every sensor UUID to lowercase hexadecimal
   without separators.
2. Initialize BLE and obtain the platform scan and connect permissions.
3. While the device screen is visible, run a low-latency scan with duplicate advertisements enabled.
4. Use one application-wide scan coordinator. Starting a scan must stop and replace the previous
   native scan owner because mobile BLE plugins commonly expose one global scan operation.
5. Read local name and manufacturer data from every advertisement.
6. Accept the exact local name SVN, but never require it: Android may omit the name.
7. Identify a Solvotix advertisement by manufacturer ID 0x79fd or by a manufacturer-derived UUID
   that matches the authenticated tenant's sensor inventory.
8. Construct the primary 8-byte sensor identifier as the manufacturer ID in little-endian byte
   order followed by the first six manufacturer payload bytes. Also tolerate stacks that expose
   the complete identifier as payload bytes 0..7 or 2..9.
9. Mark an inventory device nearby only when its normalized UUID matches a current advertisement.
10. Refresh last-seen time for duplicate advertisements and remove nearby state after 10 seconds
    without an advertisement.
11. Renew a long-running scan periodically and retry a failed scan after a short delay.
12. Stop scanning before connecting. Resume scanning after disconnect while the screen remains
    visible.
```

Platform permissions:

```yaml
android:
  runtime:
    - Bluetooth scan permission
    - Bluetooth connect permission
  behavior:
    - request Bluetooth enablement when disabled
    - do not assume localName or device.name is present
ios:
  configuration:
    - provide the Bluetooth usage description required by the current iOS SDK
  behavior:
    - initialize Bluetooth only in response to an application flow that needs it
```

Direct-delivery algorithm:

```text
1. Confirm that the target inventory UUID currently maps to a nearby BLE device ID.
2. Obtain explicit approval for the physical operation when required by its risk class.
3. Display a blocking communication overlay before requesting or decoding the package. Keep it
   visible through connection, discovery, all writes, and disconnection.
4. Decode exactly one backend package representation. Require exactly 212 bytes and do not alter
   the package.
5. Stop the active scan and disconnect any stale connection for the target BLE device ID.
6. Connect and discover the specified node-core service and write characteristic. Do not select an
   unrelated writable characteristic as a substitute.
7. Read the negotiated MTU when supported. Use chunk size max(20, min(215, MTU - 3)); when MTU is
   unavailable, assume MTU 23 and send 20-byte chunks.
8. Write chunks sequentially. Prefer write-without-response when advertised; otherwise use
   write-with-response. Do not automatically retry after any chunk delivery attempt.
9. Treat completion of all BLE writes as transport completion, not proof that the physical action
   occurred. Use a device acknowledgement or observed current state when the firmware exposes one.
10. Disconnect in a finally/finalization path, report success or failure in the overlay, and restart
    continuous scanning after a short settling interval.
```

For manual queue delivery, preserve response order and use one connection/write lifecycle per
package unless the supported firmware transport explicitly guarantees multi-package framing. Delete
`DELETE /api/gateways/queue/message/{messageId}` only after the application's required positive
delivery acknowledgement for that exact message. Stop at the first failure; never delete the failed
message or later messages.

Logging must include lifecycle stages and non-sensitive identifiers, but never package bytes,
credentials, access codes, tokens, or decoded package payloads. Useful stages are scan ownership,
known UUID match, connection, characteristic discovery, negotiated MTU, chunk offset and length,
completion, failure, disconnection, and scan restart. Avoid per-advertisement logging; log a nameless
UUID match once per device to diagnose Android discovery without flooding the console.

UI requirements for direct communication:

```yaml
nearby_action_visibility: derived-from-current-ble-advertisement
internet_action_visibility: independent-of-ble-proximity
communication_overlay:
  show_before_async-work: true
  states: [connecting, transferring, success, failure]
queue_prompt:
  condition: queued-messages-and-device-nearby
  text: Do you want to transfer the messages to the device?
```

## 18. PUBLIC API SURFACE CATALOGUE

The production OpenAPI document is authoritative for individual request and response schemas. The
catalogue below identifies the supported public API families and their integration role. Confirm both public support and the current OpenAPI operation before using a route.

### 18.1 Machine-integration API families

All routes below use bearer authentication and tenant context unless their live OpenAPI operation
explicitly says otherwise:

| Base path | Integration purpose | Important mutation semantics |
|---|---|---|
| `/api/gateways` | gateway inventory, node inventory, metering, firmware, gateway relay and queues | commands are asynchronous; verify queue/events/state |
| `/api/sensor` | sensor inventory, generic actions, claiming, pairing and communication history | action support depends on device type |
| `/api/smartlocks` | lock commands, access codes, configuration and direct packages | physical/security-sensitive; no automatic retry |
| `/api/relay` | persistent, timed and consumption-limited relay commands and packages | physical purpose and bounds must be confirmed |
| `/api/thermostat` | thermostat on/off, targets, Wi-Fi and restart | Wi-Fi and restart are operationally dangerous |
| `/api/temperature-control` | temperature statistics and history | read-only |
| `/api/node-updates` | node firmware discovery, start, abort and queue cleanup | maintenance approval required |
| `/api/events` | tenant, device and room event verification | event presence does not always prove physical completion |
| `/api/messages` | recent raw protocol-message history | temporary, approximately 24-hour retention |
| `/api/bookings` | bookings, rooms, guest messages and room-code lifecycle | room codes are security-sensitive |
| `/api/cleaning` | cleaning rooms, settings and completion state | role-restricted |
| `/api/automation` | available automation definitions | read-only discovery |
| `/api/automation/messages` | automated-message logs and trigger lifecycle | sending side effects and recipient data require approval |
| `/api/automation/locks` | scheduled open/close/pulse tasks; standalone add/remove PIN tasks on code-capable locks/controllers | superuser only; schedules unattended physical operations; task responses include the stored PIN under existing response masking rules |
| `/api/modules` | tenant module settings | changing modules can alter available workflows |
| `/api/email-branding` | tenant email-branding configuration | validate all public URLs and sender presentation |
| `/api/lock-users` | logical lock-user lifecycle, numeric codes and MIFARE card credentials | security-sensitive; `/api/lockusers` is a compatibility alias |
| `/api/wallet-certificates` | tenant Apple/Android wallet-card metadata and phone-install artifacts | package generation is security-sensitive and does not prove phone installation or physical access |
| `/api/tenants` | tenant lifecycle | create/update are administrative; delete is destructive |
| `/api/tenants/gateway-wifi` | list reusable gateway Wi-Fi networks; save or forget an entry by exact SSID | unrestricted tenant members only; security-sensitive; synchronous storage, no gateway commands |
| `/api/users` | human users and notification registrations | account deletion and role changes are security-sensitive |
| `/api/ai` | tenant AI settings and authenticated conversation threads | may process personal data; follow retention policy |

`GET /api/messages?page=0&size=40` returns the newest 40 protocol messages for the authenticated
tenant. It requires the bearer token and `Tenant` header, has no request body, and is read-only with
no approval requirement. `page` is zero-based; `size` defaults to 40 and must be 1–100. The `200`
response retains `messages`, `newMessages`, and `latestTimestamp` and adds `page`, `totalElements`,
and `last`. Request later pages until `last` is true. Pass the first response's `latestTimestamp`
as `before` on those requests, for example
`GET /api/messages?page=1&size=40&before=1786528800000`, so newly received records do not shift
the selected time window. Deduplicate by `recordId` because records can still arrive with the same
millisecond timestamp. Optional `after` is an inclusive Unix-millisecond lower bound, useful after
clearing a client-side log. Optional `since` still changes only `newMessages` and does not restrict
the returned page. An invalid page, size, or reversed `before`/`after` range returns `400`. Reads
can be retried. Message history is temporary, approximately 24 hours, and is not a durable audit trail;
a `200` proves only that stored traffic was retrieved, not that a gateway or device acted on a
command. Check the relevant queue, event, and device state before reporting physical completion.

### 18.1.1 Booking, cleaning and messaging application contracts

Booking and room operations use the public `/api/bookings` family. Verify the exact operation
and schema in OpenAPI. Receptionist authorization is required where documented. Use
`Booking.bookingId` in booking paths; do not substitute a display reference or another ID.
Access codes, booking links, contacts and rendered messages are sensitive.

Read-only booking occupancy fields include nullable `adults`, `children` and computed
`numberOfGuests`; the total is unknown if a required component is unknown. Never present an adult
count as a complete guest count. Reservation-wide monetary totals can repeat across room bookings;
do not sum them as independent room charges or infer confirmed payout from a credited amount.

`GET /api/cleaning/rooms` and `GET /api/cleaning/rooms/{roomId}` expose booking guest counts and a
current room total under existing cleaning-role permissions. Future arrivals do not contribute to
the current occupied-room count. Missing information can make the room total null. Hiding booking
details also hides the total; hiding booking codes does not remove guest counts.

`arrived`/`arrivedAt` reflect the first observed valid use of a booking's room code, asynchronously.
They are read-only and do not prove a particular person physically entered. Check-in, check-out,
access validity, code retention and physical credential delivery remain separate states.

A booking code can be retained after checkout/expiry for up to seven days measured from the stored
booking end. Retention does not extend guest access or prove that a credential remains active on a
lock. Explicit reactivation changes access and needs operator approval. Verify actual lock slots,
queue and credential events when relying on revocation or restored access.

`GET /api/bookings/bookings` can return the read-only, nullable `roomCodeActiveAfterCheckout`
warning. It concerns recorded lock credential state after the booking end; it is not proof of
physical access or current connectivity. The manifest defines its exact projection and limits.

#### Automated guest messages

Configure rules with `GET/POST /api/automation/messages/triggers` and
`PUT /api/automation/messages/triggers/{id}` using the generated schemas. Approve the recipients,
content and trigger changes before saving. Rules can send to already eligible bookings, so a new
rule is not a harmless draft unless explicitly configured as a template. Read configured rules
before retrying an ambiguous create/update.

Public rule fields include:

| Field | Application meaning |
|---|---|
| `offsetMinutes` | Start-time eligibility offset for `when_start_time_has_passed`; integer default 0, negative before start, positive after |
| `byWeekdays` | Full weekday names, evaluated on the send day in the tenant zone; empty means all days |
| `roomIds` | Restrict booking-guest rules to rooms; empty means all rooms |
| `sendOnlyWhenRoomClean` | Wait for an assigned clean room, or an assigned room on a checked-in booking |
| `onlySendIfPaidOrCheckedIn` | Wait for paid-in-full within the documented tolerance, or checked-in |

On update, omitted/null weekday and room filters preserve existing selections; empty arrays clear
them. Names are normalized; invalid weekdays/room entries return `400`. A nonempty room filter
requires booking-guest delivery. Unassigned bookings wait if an enabled channel needs `{room}`,
`{code}`, `{roominstructions}` or a room-specific block; generic confirmations can proceed.
Eligibility offsets and filters do not extend the booking window or guarantee delivery time.
Editing wording/offsets does not resend successful channels for the same rule and booking/code
cycle. A new rule can send again. Exact field semantics and trigger-specific expiry windows are
in the manifest's automated-message policies.

The booking response's read-only `automatedMessageBlockReason` uses `0` ALL_OK, `1` ROOM_NOT_CLEAN,
`2` NOT_PAID, `3` NO_RECIPIENT_CHANNEL, `4` DISPATCH_FAILED and `5` ROOM_NOT_INCLUDED. Legacy `6`
is normalized to `0`. A zero value or `messageSent` does not prove inbox receipt. Inspect the
per-channel log and its delivery status.

#### Message logs and dashboard totals

`GET /api/automation/messages/logs/bookings/{bookingId}` is a read-only Receptionist operation.
Results are newest first; an empty list can mean an unknown booking or no retained logs. Contacts,
message bodies and codes must remain inside the authorized application view. Do not publish or log
them. No response is proof that a physical device acted.

Read `deliveryStatus`, `deliveryChannel`, `deliveryMessageId`, `deliveryStatusUpdatedAt`,
`deliveredAt`, `readAt` and `deliveryAttempts` for phone delivery. Attempts can include `errorCode`
and `errorMessage`. Channels are `sms` and `whatsapp`; `READ` is WhatsApp-only. `ACCEPTED` and
`IN_TRANSIT` do not prove receipt. `DELIVERED` and `READ` require recorded evidence. Email status is
separate: `emailDeliveryStatus=ACCEPTED` means SMTP submission, `FAILED` definite failure, and
`UNKNOWN` an unconfirmed or historical outcome. It is not an email inbox/read receipt.

Legacy/unlinked attempts can remain `UNKNOWN`, timestamps can be null, and an absent log or a
timeout does not prove that no message was sent. Read status again to refresh it; never resend
merely to refresh a status. Email and phone failures are independent. Preserve public safe error
codes and messages without exposing raw exceptions, credentials or private diagnostics.

`GET /api/dashboard` returns six tenant monthly totals: `smsSentThisMonth`, `smsSentLastMonth`,
`emailsSentThisMonth`, `emailsSentLastMonth`, `whatsappSentThisMonth` and `whatsappSentLastMonth`.
SMS totals count parts rather than messages and can use encoding estimates; later delivery data
can change them. Email/WhatsApp totals count recorded successful channels. Month boundaries use
the tenant timezone with UTC fallback. Counts are not exact supplier invoice quantities, recipient
receipt or a complete inventory of every message. Reads are repeatable and send nothing.

#### Room-code policy and health

`GET /api/bookings/rooms/{roomId}/codes/health` is a read-only Receptionist operation. Room states
include `HEALTHY`, `DEGRADED`, `NO_CODES` and `NO_CODE_CAPABLE_LOCKS`; code states include
`UPLOADED`, `MISSING`, `PENDING_UPLOAD`, `PENDING_REMOVAL`, `PENDING_CONFIRMATION` and `UNKNOWN_STATE`.
Unresolved assigned devices prevent a healthy result. A confirmed uploaded slot has
`ADDED_TO_LOCK` state and `uploadedToLockAt`; a pending/queued command is not completion.
The response includes sensitive code/booking identifiers; do not log it.

`PUT /api/bookings/rooms/code-generation-settings` accepts a nonempty `roomIds` list and distinct
excluded digit strings in `excludedDigits`, leaving at least two digits available. This can remove
unused conflicting codes and queue replacements; active conflicting codes wait until release.
It changes physical access policy and requires approval. Read rooms before an ambiguous retry and
verify each room's health, queues and device delivery afterward. Tenant `roomCodeLength` affects
new generation/selection without rewriting existing codes or proving target-lock compatibility.

### 18.2 Browser and guest application APIs

The documented browser session exchange at `/api/auth/session` uses a Firebase ID token and an
HTTP-only session cookie. A `sat_` API-user token cannot be exchanged for a browser cookie. Machine
tokens stay on trusted servers.

Guest operations are booking-scoped and have their own authorization contract. A tenant header
alone is not booking authorization. Use only the exact guest operation and parameters declared
in OpenAPI. Some existing guest operations use `tenantId` query context; do not add it to the
machine API or invent new tenant arguments. Never expose booking access URLs in public output.

| Purpose | Public guest path |
|---|---|
| Access validity | `/api/guest-portal/bookings/{bookingId}/validity` |
| Tenant display name | `/api/guest-portal/bookings/{bookingId}/tenantName` |
| Tenant timezone | `/api/guest-portal/bookings/{bookingId}/timezone` |
| Feature visibility | `/api/guest-portal/bookings/{bookingId}/display-settings` |
| Messages | `/api/guest-portal/bookings/{bookingId}/messages` |
| Save missing phone | `PUT /api/guest-portal/bookings/{bookingId}/phone` |
| Review/confirm contacts | `GET/PUT /api/guest-portal/bookings/{bookingId}/contact-details` |
| Report departure | `POST /api/guest-portal/bookings/{bookingId}/checkout` |
| Cancel pending departure | `POST /api/guest-portal/bookings/{bookingId}/checkout/cancel` |

Access validity is policy state, not a physical-lock reading. Checked-out bookings are denied;
configured grace can affect the end cutoff but does not override an explicit departure deadline.
Display-settings failure must fail closed: hide optional actions/content and require valid time.
Display settings do not bypass authorization. Tenant name/timezone can remain readable outside
the stay when the booking exists; timezone values have no invented UTC fallback.

Contact review includes personal data and uses `Cache-Control: no-store`. A phone-only save does
not confirm both contacts. Explicit contact confirmation requires the documented phone/email and
`contactDetailsConfirmed=true`; it is not phone/email ownership verification. Confirmed contacts
are protected by the documented booking-update policy. Read back values after an ambiguous save.

An explicit guest checkout reports departure and schedules a five-minute deadline. HTTP `200`
does not mean checkout is completed: `checkedOut` initially stays false, `checkedIn` is unchanged
and `checkoutTime` carries the deadline. Normal grace does not extend that deadline. Completion is
asynchronous; local state does not establish completion in another system or physical revocation.
Repeating a pending/completed report returns `403` and does not extend it. Do not automatically
repeat an ambiguous report; read booking validity.

Cancellation is available only while the report is pending, the deadline is future and the original
end can be restored. It has no body and requires the documented `tenantId` query context and
explicit guest intent. `200` returns `BookingValidityResponse`; `409` indicates no longer
cancellable/conflicting state. It restores the original end without undoing completed checkout
elsewhere. If that end is already past, ordinary validity rules may still deny access. Read validity
and `canCancelCheckout`; cancellation does not prove a physical change. Staff reopening through
the documented booking PUT is a separate approved operation.

Configure public guest content with `GET/PUT /api/guest-portal-admin/settings` using authenticated
tenant context. Guest clients must not call this administrative operation. Read before sending
the complete settings object. General-language templates and room instructions resolve
independently and compose at `{roominstructions}`; activated-language and booking-window checks
still apply. Saving a translation does not activate its language. Do not log rendered codes/links.

Automated templates support `{guestportal}` links and
`{guestportalbutton="Open guest portal", color="#1068F0", textColor="#F8F8F8"}` in email body
content. Place button tokens outside HTML tags/links. Numeric/text arrival and departure variables
use tenant-local dates. `{bookingId}` displays `externalId` when present, otherwise `bookingId`;
this display substitution never changes API path identifiers. Preview content before an approved
send. The manifest defines full language precedence and date formatting.

### 18.3 API-user management

API-user creation, role changes, rotation and revocation require an authenticated interactive
tenant member. Runtime `sat_` integrations cannot manage API users. Use the portal's **Settings →
System users**. Rotation invalidates the old token immediately and returns the replacement only
once. Do not implement human login or credential-management workarounds in the runtime integration.

## 19. ERROR POLICY

```yaml
http_400:
  meaning: invalid request or payload
  action: validate against live OpenAPI
  retry_unchanged: false
http_401:
  meaning: missing, invalid, expired, revoked, or tenant-mismatched API token
  action: stop and request API-user verification or rotation from the system owner
  automatic_retry: false
http_403:
  meaning: authorization or tenant access denied
  action: verify roles and selected tenant
  bypass: forbidden
http_404:
  meaning: endpoint or resource unavailable
  action: refresh OpenAPI and inventory
http_409:
  meaning: state conflict
  action: inspect current state before resolution
http_5xx:
  meaning: server failure
  read_retry: exponential backoff permitted
  physical_command_retry: forbidden until queue and events are inspected
network_failure_after_send:
  state: ambiguous
  action: inspect queues and events before any retry
```

## 20. RISK AND APPROVAL MATRIX

```yaml
read_only:
  examples: [inventory, state, history, metering, queues]
  default_agent_permission: execute
reversible:
  examples: [temperature target, ordinary short pulse]
  default_agent_permission: confirm target and bounds
security_sensitive:
  examples: [access codes, users, permissions]
  default_agent_permission: require explicit approval
destructive:
  examples: [delete device, tenant, codes, queue data]
  default_agent_permission: require explicit confirmation
ownership_changing:
  examples: [claim gateway, claim sensor]
  default_agent_permission: require explicit approval
operationally_dangerous:
  examples: [persistent relay, persistent lock, Wi-Fi, firmware, scheduled lock automation]
  default_agent_permission: require purpose, safe conditions, and explicit approval
```

## 21. SECRET HANDLING

Never expose or log:

```yaml
secrets:
  - Solvotix sat_ API token
  - private key
  - Solvotix session cookie
  - Wi-Fi SSID when classified as private
  - Wi-Fi password
  - smart-lock access code
  - any authentication or capability token
```

Also exclude card identifiers, private customer/staff data, signed installation links,
secret-bearing URLs and private configuration or operational details. Use redaction
markers such as `<REDACTED_TOKEN>` and `<REDACTED_ACCESS_CODE>`.

## 22. COMPLETION CRITERIA

Do not report the integration complete until all applicable statements are true:

```yaml
completion:
  - live OpenAPI retrieved and validated
  - generated or typed client matches project conventions
  - API token is loaded only from a protected secret source
  - API token begins with sat_
  - bound tenant ID is explicit
  - read-only authentication check succeeds
  - gateway inventory loads
  - device inventory loads
  - device capabilities are mapped from type and OpenAPI
  - secrets are redacted
  - physical commands are approval-gated
  - non-idempotent commands are not automatically retried
  - accepted, queued, delivered, and confirmed states remain distinct
  - queue and event verification is implemented
  - direct BLE discovery does not depend on the local name or backend online status
  - direct BLE delivery uses the documented service, characteristic, and MTU-safe chunking
  - scanning stops for connection and resumes after disconnection
  - queue messages are removed only after the required positive delivery acknowledgement
  - failure and ambiguity are surfaced to the caller
```

## 23. BOOTSTRAP PROMPT

```text
Integrate this project with Solvotix. First retrieve and read https://solvotix.net/ai-first/agent-manifest.json, https://solvotix.net/ai-first/agent-guide.md, and https://backend.solvotix.org/v3/api-docs. Read all three before editing code. The system owner creates the Solvotix system at https://portal.solvotix.org/login and creates a tenant-bound API user at https://portal.solvotix.org/home/settings#system-users. Use the copied sat_ token only from a protected server-side secret and send it as Authorization: Bearer sat_<TOKEN> with the bound Tenant header. Do not implement interactive user authentication for the integration. Identify the project's language, architecture, existing HTTP client, and code-generation conventions. Implement typed API access, gateway discovery, device discovery, and queue/event verification. Treat hardware commands as asynchronous. Never report physical success solely from an accepted or queued response. Never log tokens, Wi-Fi credentials, access codes, or private customer data. Begin with read-only discovery. Require explicit approval for physical, security-sensitive, destructive, ownership-changing, Wi-Fi, and firmware operations. Do not automatically retry non-idempotent physical commands. Use only supported public application contracts. Never publish private services, personal data, deployment details or security maintenance procedures. If the guide, OpenAPI, inventory, and observed state disagree, stop and report the conflict instead of guessing.
```

## 24. EMAIL BRANDING, TEMPLATES AND UPLOADED LOGOS

Navigate to **Settings → Messaging → Email branding** (`/home/settings#messaging`).
Choose **Email template**, use **Upload logo** or the optional **Logo URL**, edit the brand
and contact fields, inspect **Email preview** in **Mobile view** or **Desktop view**, then
select **Save email branding**. The preview uses unsaved form values and representative
content; it sends no email. Actual email-client rendering can differ.

The existing operations are `GET /api/email-branding` and `PUT /api/email-branding`.
Both use bearer authentication and tenant context supplied globally by the authentication
filter, with no tenant path or query argument. Machine clients send
`Authorization: Bearer sat_<TOKEN>` and `Tenant: <TENANT_ID>`; the token is tenant-bound.
Human clients use the normal portal authentication and selected tenant. The shared role
policy allows unrestricted (empty-role) identities and `Restricted`; other role-limited
identities receive `403`. These operations do not change authorization or SMTP settings.

GET returns `200` with `EmailBrandingSettings`, creating an empty settings record if absent.
PUT returns `200` with the persisted settings, including the uploaded logo. Read before
writing to preserve the current contact fields and confirm the selected tenant.

```http
PUT /api/email-branding
Authorization: Bearer sat_<TOKEN>
Tenant: <TENANT_ID>
Content-Type: application/json

{
  "template": "modern",
  "primaryColor": "#08788C",
  "secondaryColor": "#001838",
  "name": "Example Hotel",
  "logoUrl": "https://example.com/logo.png",
  "logoBase64": "",
  "website": "https://example.com",
  "addressLine": "Example Street 12",
  "supportEmail": "reception@example.com",
  "supportPhone": "+47 22 55 88 99"
}
```

This example uses the URL and removes a previously uploaded logo. To upload instead, set
`logoBase64` to a complete `data:image/png;base64,<BASE64_IMAGE_BYTES>` or
`data:image/jpeg;base64,<BASE64_IMAGE_BYTES>` data URI. The placeholder is not a valid image;
encode the actual file bytes. No multipart upload or separate upload endpoint is used.

| Field | Meaning and update behavior |
|---|---|
| `template` | `classic` (centered, framed), `modern` (teal, left-aligned header), `minimal` (unframed), or `elegant` (navy header, serif branding, orange accent). Omitted/null preserves the stored selection; blank resets to `classic`. Missing or unknown legacy stored values render as Classic. Unknown nonblank values on PUT return `400`. |
| `primaryColor` | Modern-template header and accent color as a six-digit hex code such as `#08788C`. Omitted/null preserves the saved value; blank resets to `#08788C`. GET prefills the default for legacy or new settings. Ignored by other templates. Header text automatically uses a contrasting built-in light or dark color. |
| `secondaryColor` | Modern-template outer-background and main-text color as a six-digit hex code such as `#001838`. Omitted/null preserves the saved value; blank resets to `#001838`. GET prefills the default for legacy or new settings. Ignored by other templates. |
| `logoBase64` | Valid PNG/JPEG data URI, at most 524288 decoded bytes, and 1–2048 pixels on each side. Media type and image content must match. Omitted/null preserves the stored upload; empty/blank removes it. GET and PUT return the stored data URI. |
| `logoUrl` | Optional absolute HTTP(S) URL without credentials, used only when no valid uploaded logo exists. A recipient can block remote image loading. |
| `name`, `addressLine`, `supportEmail`, `supportPhone` | Escaped display text in the header/footer; contact fields do not set From or Reply-To. |
| `website` | Optional absolute HTTP(S) URL without credentials, linked in the header. |

Existing text and URL fields are replaced on PUT; omitted/null/blank values clear them.
`id`, `tenantId` and ownership metadata are server-managed for this operation and are not
used to select another tenant. Surrounding whitespace is trimmed. The frontend's **Remove
logo** clears both the upload and logo URL; clearing only `logoBase64` through the API
allows a saved `logoUrl` to appear again.

Uploaded logos take precedence over logo URLs. The branded mail service decodes the saved
image and embeds it in a `multipart/related` MIME message, referenced as `cid:branding-logo`.
The outgoing HTML does not contain a base64 data URI and the uploaded image does not need
remote hosting. Existing settings without a selected template use Classic. Invalid legacy
stored image data is ignored so it does not prevent sending the message body. The message
content is retained inside the chosen layout. The footer includes saved contact details and
the Solvotix attribution. This applies to future messages that support tenant branding; saving does not resend previous messages or send a preview message.

Risk: reversible tenant-wide presentation change. Confirm the intended tenant and branding;
existing authorization to edit branding is sufficient. No physical-operation approval is
needed. GET is safe to retry. Repeating PUT with the same complete values is idempotent,
with last-write-wins behavior and no version check. After an ambiguous save, GET and compare
before retrying so a newer edit is not overwritten. No device queue entry, hardware operation
or branding event is created. Verify persistence with GET. To verify actual inbox rendering,
use a separately authorized existing email-sending workflow and inspect the received message;
the preview and successful save do not prove delivery.

Errors: `400` for missing tenant context, malformed JSON, an unsupported template, an invalid
color code, invalid image data, excess image size/dimensions, or invalid URLs; `401` for failed authentication or
API-token tenant mismatch; `403` for denied role or tenant access. Correct invalid input before
retrying. On server or network failure, follow the read-before-retry policy. No events or
additional event input keys are required by these settings operations.