OpexFlow updates itself in place. An **update file** (`opex-flow-<version>-<platform>.opexupd`) carries one signed executable
for one platform. The connector verifies it, stages it, and a small root-run updater swaps the executable, restarts the
service and goes back to the old version when the new one does not come up. Open **Update** in the dashboard menu (or
Ctrl/Cmd+K, *Update...*). Anyone can read the status; every action needs the **admin** role and is audited
(`update.check`, `update.download`, `update.upload`, `update.discard`, `update.apply`, `update.cancel`).

## What is checked

Every update file is checked **before it is staged** and **again by the root updater before it touches anything**. A file that
fails is refused with a code and changes nothing:

| Code | Refused because |
|---|---|
| `malformed` | Not an update file, truncated, or its manifest is invalid. |
| `unsigned` | No signature. Unsigned updates are **always** refused; there is no switch. |
| `bad_signature` | The signature does not match, or the signing key is not trusted here. |
| `wrong_product` / `wrong_platform` | The file is for another product, or for another platform than this build (`linux-aarch64`, `linux-x86_64`, `linux-x86_64-gnu`, `darwin-aarch64`, `darwin-x86_64`, `windows-x86_64`). |
| `checksum` | The executable does not match the signed size or SHA-256 (changed or damaged in transit). |
| `not_newer` | The version is not newer than the running one. Downgrades are only possible from the command line (`--allow-downgrade`). |
| `too_old` | The release needs a newer starting version (`min_from`). Install the intermediate release first. |
| `maintenance_expired` | The license's maintenance window ended before this release was published (see below). |

Updates are signed with the OpexCG key built into the connector. For an internal test channel add more signers:

```yaml
update:
  trusted_keys:
- id: acme
  public_key: <base64 raw 32-byte Ed25519 public key>
```

## Configuration

```yaml
update:
  enabled: true                        # dashboard panel + /api/update
  server_url: https://flow.opexcg.com
  check_every_hours: 24                # 0 = never contact the server (air-gapped)
  apply: none                          # none | systemd
  service: opex-flow                   # systemd unit the updater restarts
  backup_dir: /var/backups/opex-flow   # outside data_dir, root-owned
  health_timeout_secs: 90              # the new version must answer /api/ready in this time
  trusted_keys: []
```

`apply` decides who installs:

- **`none`** (default): the dashboard downloads or accepts the file and stages it. You install it on the host with
  `sudo opex-flow update apply FILE`. Nothing in the service can replace the executable.
- **`systemd`**: the **Install** and **Schedule** buttons write a request file that `opex-flow-update.path` hands to
  `opex-flow-update.service`, which runs as root. `scripts/deploy.sh` installs and enables both units; it never changes your
  `config.yaml`. If `connector.data_dir` is not `/var/lib/opex-flow`, change the `PathExists=` line in the `.path` unit.

## Online

With `check_every_hours` above 0 the **active** node asks the update server (`GET /updates/latest?platform=...&current=...`)
at that interval, and on **Check now**. A newer release shows its notes and size. **Download** fetches it, checks the size and
SHA-256 the server announced, runs every check above and stages it. The server only points at a file: nothing is installed
that does not carry a valid OpexCG signature. With `check_every_hours: 0` the connector never contacts the server, the
check and download buttons are off, and the Update dialog says so.

## Offline: upload in the dashboard

On a machine with internet, download the file for your platform from the download page ("Offline update file"). Carry it to the
site and choose **Upload update file** in the dialog (256 MiB limit; the file is streamed to disk and verified, a refusal names
the code). Once staged it behaves exactly like a downloaded one.

## Offline: copy the file and run the CLI

When the dashboard is not reachable, or for `apply: none`:

```bash
opex-flow update verify opex-flow-2.4.0-linux-aarch64.opexupd     # signature, checksum, manifest; exit 1 on failure
sudo opex-flow update apply opex-flow-2.4.0-linux-aarch64.opexupd # asks for confirmation; --yes skips it
```

`apply` takes `--config PATH` (default `config.yaml`, then `/etc/opex-flow/config.yaml`), `--install PATH` (the executable to
replace, default the running one), `--service NAME` or `--no-restart`, `--allow-downgrade` and `--yes`. It runs the same steps
as the dashboard. On Windows and macOS it swaps the executable and tells you to restart the process or service yourself;
`run-request` and the systemd restart are Linux only. `opex-flow update check` asks the update server from the command line.

## Scheduling

**Install now** requests the install immediately. **Schedule** takes a date and time (up to 90 days ahead); the staged file
is requested when it is due. **Cancel schedule** removes it; discarding the staged file removes it too. A scheduled install
needs `apply: systemd`. Pick a quiet time: the service restarts, and records in flight are drained the way a normal stop does.

## What an install does

1. Verifies the bundle again (as root, without following links in the data directory).
2. Backs up every `*.db` in the data directory with `VACUUM INTO` (a consistent snapshot while the service runs) and the
   top-level `*.json` state files into `<backup_dir>/<from>-to-<to>-<timestamp>/`. If this fails, nothing changes.
3. Writes the new executable next to the old one, keeps the old one as `<install>.prev`, and renames the new one into place.
4. Restarts the service and polls `GET /api/ready` for `health_timeout_secs`.
5. Records `update/result.json`: `updated`, `rolled_back`, `refused` or `failed`, with the message and the backup path. The
   dialog shows the last result.

### Rollback

If the restart fails or `/api/ready` does not answer in time, the updater renames `<install>.prev` back, restarts the old
version and records `rolled_back`. The staged file stays, so you can read the reason and try again or discard it. The data
backup is **not** restored automatically: a new version that started and then failed may have changed the databases, so a
restore is a deliberate step. To restore, stop the service, copy the `.db` and `.json` files from the backup directory over
the data directory, and start the service. Old backups are not deleted; remove them when you no longer need them.

## High availability

Update the **standby** first, then fail over, then update the former active node. The periodic check runs only on the active
node. The health check treats a standby that is up (503 with `"role":"standby"`) as healthy, so a node that restarts into the
standby role passes. See [High availability](/docs/high-availability). Both nodes need the same version before you
rely on a failover again.

## Docker

A container's executable lives in the image, so the in-app updater does not replace it: keep `apply: none` and treat the
dashboard as a notification that a newer release exists. Update by pulling the new image and recreating the container; the data
directory volume carries over.

## License maintenance

An expired license never blocks installing a release that was published while maintenance was valid. A license may carry a
maintenance end date (shown in the License panel): a release with `released_at` on or before that date is always allowed, a later
one is refused with `maintenance_expired`. No date means every release is allowed. The gate is checked when the file is staged,
when the install is requested, and again by the root updater. See [Licensing](/docs/licensing).

## REST and MCP

| Route | Role | Notes |
|---|---|---|
| `GET /api/update/status` | viewer | Version, `available`, `staged`, license `gate`, `schedule`, `pending`, `last_result`. |
| `POST /api/update/check` | admin | Ask the update server. |
| `POST /api/update/download` | admin | Fetch, verify and stage the announced file. |
| `POST /api/update/upload` | admin | Raw `application/octet-stream` body, 256 MiB maximum. |
| `DELETE /api/update/staged` | admin | Drop the staged file and its schedule. |
| `POST /api/update/apply` | admin | `{"at": "RFC 3339"}` optional. 409 `apply_unavailable` unless `apply: systemd`. |
| `DELETE /api/update/schedule` | admin | Cancel a scheduled install. |

Errors are `{error, code}`: 422 for the check codes above, 409 for `apply_unavailable`, `nothing_staged`, `apply_pending`,
`check_disabled` and `busy`, 413 `too_large`, 502 `server_unreachable`. The MCP tool `update_status` returns the status object;
installing is not available through MCP.

## Building update files

Release engineers pack and sign with the same key as packages:

```bash
opex-flow update pack --binary target/aarch64-unknown-linux-musl/release/opex-flow \
  --version 2.4.0 --platform linux-aarch64 --notes-file CHANGELOG-2.4.0.md \
  --key-env OPEX_PACKAGE_KEY --key-id opexcg-1 -o dist/opex-flow-2.4.0-linux-aarch64.opexupd
```

Optional: `--released-at RFC3339` (default now) and `--min-from VERSION`.