# Node protocol v1

This page is for anyone who builds or debugs a control plane, or runs nodes by hand. It is the
full API that `hermitboxd` serves on each host, and the fleet endpoints a node calls back on. The
SDKs, the CLI and the HTTP API talk to the control plane; the control plane reaches each host only
through this protocol.

The control plane talks to one `hermitboxd` per host over **HTTPS with mutual TLS**, with JSON
bodies, under `/v1`. The protocol's unit is the *workload*: a spec (image, environment,
resources, storage, ports, stop behaviour) that `hermitboxd` keeps on this host, running or
stopped. Nothing in the protocol names Docker.

> The Rust types in [`src/protocol.rs`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/src/protocol.rs) and
> [`src/protocol/wire.rs`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/src/protocol/wire.rs) are the source of truth.
> The control service uses [generated node API types](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/src/wire.ts).
> Before the first public release, protocol changes update both ends together. From that release,
> changes within a major version are additive and adjacent releases interoperate.

## Conventions

- **Transport.** TLS 1.3 only, and a client certificate is required. The certificate must chain
  to the host's `client_ca`, carry extended key usage `clientAuth`, and name one of
  `allowed_clients`. A missing or foreign certificate is refused during the handshake. A valid
  certificate for a name that isn't allowed gets `403 forbidden`, and its connection is closed
  after it. There is no 0-RTT. A handshake must finish within 5 s, and handshakes in progress are
  capped per peer address and overall: a connection past either cap is closed at once. A
  connection whose handshake finished is not counted.
  - **In fleet mode** (a `[fleet]` section, no `[api.tls]`), the node's sandbox certificate, the CA
    and `allowed_clients` all come from enrollment (below). Its certificate names the node
    (`<nodeId>.nodes.<deployment>.fleet`), not an address: a client dials the node's address and
    verifies that name.
- **Versioning.** The major version is in the path (`/v1`). Every response carries
  `blocklyd-protocol: 1`. `GET /v1/health` lists `protocol.supported` and `features`.
  - `hermitboxd` refuses unknown request fields with `422 invalid_request`. Control checks the
    capabilities reported by the node before requesting an operation that depends on them.
- **Request ids.** Send `x-request-id` (1–64 of `[A-Za-z0-9_-]`) to correlate. `hermitboxd` echoes
  it, or generates one, and logs it with every line about that request.
- **Caching.** Every response is `cache-control: no-store`.
- **Workload ids.** 1–63 of `a-z 0-9 -`, starting and ending with a letter or digit. A UUID is
  valid. Anything else in the path gets `400 invalid_workload_id` before any handler runs.
- **Errors.** Every error but a `405` (which has no body) and a `stop` body over the size limit
  (a plain-text `413`) has the same shape. The `code` is the contract; the `message` is for people
  and might change.

  ```json
  { "error": { "code": "precondition_failed", "message": "…", "details": { "currentSpecDigest": "sha256:…" } } }
  ```

## Idempotency

Every verb is safe to repeat.

| Verb | Repeating it |
|---|---|
| `PUT /v1/workloads/{id}` | Same spec → `200 unchanged`, nothing touched. Keyed by id, so a retry never makes two workloads. |
| `POST …/start` | Already running → `200 {changed: false}`. |
| `POST …/suspend` | Already suspended → `200 {changed: false}`. |
| `POST …/stop`, `POST …/kill` | Already stopped → `200 {changed: false}`. |
| `DELETE …` | Already gone → `200 {existed: false}`. |
| `POST …/exec` | Not idempotent by nature. Send `Idempotency-Key`: `hermitboxd` runs the command once per key (10 minutes, in memory) and returns the first answer to repeats. The same key with a different request gets `422 idempotency_key_reused`. Failures aren't cached. |

Operations on one workload are serialized on `hermitboxd`: a concurrent duplicate waits for the
first, then finds the work done. Operations run to completion even when the client disconnects
mid-request. So a retry after a dropped connection finds a finished stop rather than half of one.

## Placement epochs (fleet mode)

Epochs keep an old copy of a workload, left on a node after a move, from running or changing
again. A fleet control plane gives every new home of a workload a **placement epoch**, a number
that only rises: the first placement, each move, restore and recovery. It sends the epoch with
every mutating request in the `blocklyd-epoch` header. `hermitboxd` stores it with the copy, in
its record and as the container label `blocklyd.epoch`. Each verb checks it against the copy's
own:

| Verb | Rule | Why |
|---|---|---|
| `PUT` (ensure) | Its epoch, or a newer one, which takes the copy over | A new placement can land on a node that already holds an older copy |
| `POST …/start`, `…/suspend`, `…/exec`, `…/export`, `…/snapshots`, `…/restore` | Exactly its epoch | Running a copy, copying it out or filling it is only ever for the current placement (a restore for a new epoch PUTs it first) |
| `POST …/stop`, `…/kill`, `DELETE` | Its epoch or any newer one | A newer placement can always stop, kill or delete an older copy |
| `…/snapshots/{snapshot}/upload`, `DELETE …/snapshots/{snapshot}` | None | A snapshot never changes, whichever placement made it |

- **Older** than the copy's: `409 stale_epoch` (`details.askedEpoch`, `details.currentEpoch`).
- **Newer** where only exactly its own matches: `409 epoch_ahead`: PUT the spec with that epoch first.
- **No header** for a copy that has one: `428 epoch_required`. A workload made without an epoch keeps
  the single-node protocol: none is asked for, and none is checked.
- **A superseded copy** (fenced: see `…/fence`) refuses everything except stop, kill and delete with
  `409 superseded`, and is never started again, by anyone, including `hermitboxd`'s own restarts. Only a
  PUT for an epoch newer than the one that superseded it brings it back.

## Endpoints

### `GET /v1/health`

`200` → `NodeHealth`:

```json
{
  "status": "ok",
  "docker": true,
  "reconciled": true,
  "daemonVersion": "0.2.0",
  "protocol": { "current": 1, "supported": [1] },
  "features": ["exec-idempotency-key", "logs-follow-across-restarts", "conditional-put",
               "placement-epochs", "data-transfer", "local-snapshots", "export-exclude",
               "execution-lease", "certificate-renewal", "resume-after-reboot", "multipart-upload",
               "self-upgrade", "suspend", "signed-upgrade"],
  "nodeId": "fra-box-1",
  "deploymentId": "staging"
}
```

`status` is `degraded` while the runtime is unreachable or `hermitboxd` hasn't reconciled with it
yet.

### `GET /v1/node`

Host facts and capacity:
- node and deployment
- `hermitboxd` version, uptime, resident memory and CPU time
- kernel, CPUs, load, memory, disk under the state directory, trash size
- `capacity`: `allocatableMemoryMb`, `runningMemoryMb`, `provisionedMemoryMb`, ports total and
  allocated
- workloads by state
- Docker version, cgroup version and driver, security options, whether live-restore is on
- the last reconciliation
- host-level `issues`:
  - orphaned data (`orphan_data`);
  - a non-isolated network (`network_not_isolated`);
  - live-restore off (`live_restore_off`);
  - an unreadable record (`unreadable_record`);
  - a container with no valid workload id (`unlabelled_container`);
  - a container with no record and no readable record label (`unrecoverable_container`);
  - a snapshot whose `snapshot.json` can't be read, or a name under `snapshots/` that isn't a
    snapshot's (`unreadable_snapshot`, found when `hermitboxd` starts and left alone).
- `daemon`: version, start time, uptime, resident memory, CPU time
- `fleet` (fleet mode): node id, control plane, the lifecycle it last said, the last contact and its
  age, the last error and latency, and heartbeats answered and failed. It also gives the execution
  lease left (`leaseRemainingSeconds`) and when it last renewed its certificates in this run
  (`certificateRenewedAt`).

### `GET /v1/workloads[?changedSince=<rfc3339>]`

`200 { "workloads": [WorkloadView…], "observedAt": "…" }`. With `changedSince`, it lists only
workloads whose state changed, or whose record was updated, at or after that time. This is the
level-triggered listing the control plane's `observeChanged` needs: one call per host, answered from
`hermitboxd`'s own observations.

### `PUT /v1/workloads/{id}` — ensure

Body: `WorkloadSpec`.

```json
{
  "image": "ghcr.io/example/http-app:1.0",
  "entrypoint": null,
  "env": { "APP_MODE": "production", "PORT": "8080" },
  "secrets": { "APP_TOKEN": "…" },
  "resources": { "memoryMb": 3072, "cpuMillis": 2000, "cpuWeight": null, "pidsLimit": null },
  "storage": { "mountPath": "/data", "sizeGb": 5 },
  "ports": [
    { "name": "http", "containerPort": 8080, "protocol": "tcp", "audience": ["edge", "control"] },
    { "name": "admin", "containerPort": 9090, "protocol": "tcp", "audience": ["control"] }
  ],
  "stop": { "signal": "SIGTERM", "timeoutSeconds": 90 },
  "restart": { "policy": "on-failure", "maxRetries": 3 },
  "labels": { "blockly.sandbox": "0b6f1f2e-…" }
}
```

| Field | Rules |
|---|---|
| `image` | `[A-Za-z0-9._-/:@]`, ≤ 255. Must start with one of the host's `allowed_images` prefixes, each of which ends in `/`, `:` or `@`, and read as an OCI reference; a prefix ending in `:` or `@` admits only the repository its name reads as (`alpine:` admits `alpine:3.24`, never `alpine:5000/x/y` on the registry `alpine:5000`). |
| `entrypoint` | Optional argv, 1–64 arguments of ≤ 64 KiB, no NUL. |
| `env`, `secrets` | Names `[A-Za-z_][A-Za-z0-9_]*` of ≤ 128. Values ≤ 64 KiB, no NUL. ≤ 256 variables and 512 KiB in all. A name is in one or the other. |
| `resources.memoryMb` | Required. Hard limit with no swap, between `min_memory_mb` and what the host allocates. |
| `resources.cpuMillis` | Optional CFS ceiling: 100 to cores × 1000. Container only; process and Wasm refuse it. It is also what the JVM counts as its processors. |
| `resources.cpuWeight` | Optional cgroup weight, 2–262144. Container only; absent means proportional to memory: 1024 per 4 GB. Process and Wasm refuse explicit weights. |
| `resources.cpuReservationMillis` | Optional admission reservation, 100 to cores × 1000; not an enforced CPU ceiling. Send only after `cpu-reservation` is announced. Unit CPU remains reserved in the control ledger even for a peer that has not announced this field. |
| `resources.pidsLimit` | Optional, 64–65536. Absent means the host default (4096). |
| `storage.mountPath` | Absolute path of plain components, not `/`. |
| `storage.sizeGb` | 1–4096. Reported against measured use; **not enforced** in v1. |
| `ports` | ≤ 8. Names `[a-z][a-z0-9-]{0,15}` are unique. `(protocol, containerPort)` pairs are unique. `audience` is a non-empty subset of `edge` and `control`. |
| `stop.timeoutSeconds` | 1–600. The grace between the signal and the kill. |
| `restart` | `no` or `on-failure`. `maxRetries` is 0–10, and 0 means never. `hermitboxd` restarts a failed workload itself, after a short backoff: every container's Docker restart policy is `no`, because Docker's `on-failure` restarts containers after an unclean reboot. It never restarts one after a requested stop, once it is fenced, or, in fleet mode, without the execution lease: the last heartbeat answer's `leaseSeconds`, counted from when that beat was sent (`restart_requires_contact_seconds` if the answer names none). A restart is admitted against memory as a start is: one that doesn't fit isn't made, and the workload stays `crashed` with the issue `insufficient_capacity`. A restart it withholds is not tried later. The retries a run has used are kept in the workload's record, so a restart of `hermitboxd` doesn't hand them out again; a requested start or a new spec begins a new run. After the host restarts, it resumes what was running when the host went down: in fleet mode only once it holds a lease, after applying the fences of the answer that granted it. After a restart of `hermitboxd` alone, in the same boot, it resumes nothing (see "After the host restarts"). |
| `labels` | ≤ 32. Keys `[a-z0-9._/-]`. The `blocklyd.` prefix is reserved. Values ≤ 256. |
| `resumesOn` | Optional, ≤ 128 characters. What a suspended workload can wake into from memory: see "Semantics". Not part of the spec digest. Announced as the feature `suspend`. |

Every validation problem comes back at once: `422 invalid_request`, with `details.fields` a
list of `{field, problem}`.

**Semantics.** Ensure means "this workload exists with this spec", as HTTP `PUT` does.
- **Absent:** `hermitboxd` creates it, stopped. `201 Created`, `outcome: "created"`.
- **Present with the same spec and secret values:** nothing happens. `200`,
  `outcome: "unchanged"`.
- **Present with a different spec** (or a rotated secret): `hermitboxd` makes a new generation.
  - It pulls the new image first; if that fails, nothing is touched.
  - It stops the old container gracefully and makes a new one on the **same data** and the
    **same host ports** for port names that remain.
  - It starts the new one if the old one was running.
  - `200`, `outcome: "replaced"`, `restarted: true|false`.
- **A `retained` workload** (compute removed, data kept) gets compute again: `replaced`.
- **A `suspended` workload with a different spec that names the same `resumesOn` as the spec it
  was suspended on** stays suspended, its memory kept. `200`, `outcome: "deferred"`, and the view's
  `pendingSpecDigest` names the spec. It is put in place at the workload's next boot. That is a
  cold start after a resume that didn't come back, or a start after a stop, a kill, a fence or a
  restart of the host. A resume wakes what is in memory and keeps the spec waiting. A `PUT` of the
  spec it runs drops a deferred one (`unchanged`); any other `PUT` replaces it as above, stopping
  it gracefully first, without starting it again.

Conditional headers, standard HTTP:

| Header | Meaning | Refused with |
|---|---|---|
| `If-None-Match: *` | Create only. Never touch an existing workload. | `412 precondition_failed` if it exists |
| `If-Match: "<specDigest>"` | Replace only this exact current spec. An apply can't overwrite a newer one. | `412` with `currentSpecDigest` |
| `If-Match: *` | Replace only if it exists. | `412` if absent |

Responses carry `ETag: "<specDigest>"`. The spec digest is `sha256:` over the canonical JSON of
the spec without secret values. Changed secrets are detected by comparing the container's
environment instead, since `hermitboxd` keeps no copy of them.

Refusals:

| Status and code | When |
|---|---|
| `409 no_free_ports` | The host has no free ports. |
| `507 insufficient_disk` | Free disk is under `min_free_disk_mb`. |
| `503 runtime_unavailable` | Docker is down. |
| `504 timeout` | The image pull ran past its limit. |

`EnsureResponse`: `{ "outcome", "restarted", "workload": WorkloadView }`. `outcome` is `created`,
`unchanged`, `replaced` or `deferred`.

### `GET /v1/workloads/{id}`

`200 WorkloadView`, with an `ETag`:

```json
{
  "id": "sb-1",
  "generation": 1,
  "epoch": 3,
  "supersededBy": null,
  "specDigest": "sha256:…",
  "image": "…",
  "state": "running",
  "health": "healthy",
  "exit": null,
  "restartCount": 0,
  "lastFailureAt": null,
  "startedAt": "…",
  "finishedAt": null,
  "changedAt": "…",
  "ports": [{
    "name": "http", "protocol": "tcp", "containerPort": 8080, "hostPort": 42000,
    "endpoints": { "edge": ["10.0.0.5:42000"], "control": ["10.0.0.5:42000"] }
  }],
  "resources": { "memoryMb": 3072, "cpuMillis": 2000, "cpuWeight": null, "pidsLimit": null },
  "storage": { "mountPath": "/data", "sizeGb": 5, "usedBytes": 745123840, "measuredAt": "…" },
  "labels": { "blockly.sandbox": "…" },
  "secretNames": ["APP_TOKEN"],
  "issues": [],
  "locate": { "containerName": "blockly-staging-sb-1", "containerId": "…", "dataDir": "/var/lib/hermitboxd/workloads/sb-1/data" },
  "createdAt": "…",
  "updatedAt": "…"
}
```

`state`, and how it maps onto the control plane's `ObservedState`:

| `state` | Meaning | Control plane |
|---|---|---|
| `creating` | Accepted; its container isn't made yet (an interrupted create). | `stopped` |
| `created` | Made and not running since. | `stopped` |
| `running` | Running. | `running` |
| `stopping` | A requested stop is in progress. | `stopping` |
| `stopped` | Exited after a requested stop, or with code 0, 130 or 143. | `stopped` |
| `crashed` | Exited with a failure on its own, or `exit.oomKilled`. | `crashed` (with `exit`) |
| `restarting` | The restart policy is bringing it back. | `starting`, plus `lastFailureAt` as `failedAt` |
| `missing` | `hermitboxd` has a record but the runtime lost the container. | `absent` |
| `retained` | Compute removed on request, data kept. | `absent` |
| `unknown` | The runtime can't be asked right now. | `unknown` |
| `fenced` | Superseded by a newer placement: stopped, kept, never started again. | `stopped` (the fleet adapter never reports a stale copy as the sandbox) |
| `suspended` | Suspended on request (`…/suspend`), its memory kept; a start resumes it. Only a workload asked to suspend is ever in it. | asleep, its memory kept |

A few fields need a word:
- **`endpoints`** is the control plane's `endpoint(handle, port, audience)`: per audience, the host
  addresses and port where the edge or the control plane reaches it. IPv6 is `[addr]:port`.
- **`restartCount`** counts `hermitboxd`'s restarts after failures since the last requested start or
  new spec. It survives restarts of `hermitboxd`.
- **`issues`** lists what reconciliation or an operation found. The codes are `container_missing`,
  `create_incomplete`, `record_rebuilt`, `digest_mismatch`, `port_mismatch`, `port_conflict`,
  `port_out_of_range`, `duplicate_container`, `unexpected_container`, `over_storage`, and two
  more:
  - `insufficient_capacity`: a restart after a failure didn't fit in memory. It stays until the
    workload is started or replaced.
  - `restore_finished`: a restore cut short by a crash after its data was complete was finished
    when `hermitboxd` started. Whoever asked for it might not have heard.
- **`pendingSpecDigest`**, present only while one waits: the digest of a spec a `PUT` deferred
  while the workload was suspended, put in place at its next boot.
- **`backend`**, present once the tier's runtime info has been observed: `{ "engine", "rootless" }`,
  naming the concrete engine (`docker`, `podman`, `firecracker`, `process` or `agentos`) and whether
  it runs rootless. Each ready tier also announces `tier-<tier>:engine-<engine>` and
  `tier-<tier>:rootless` or `tier-<tier>:rootful` in `features`.
- **`locate`** is for operators. It is informational, never a contract.

### `POST /v1/workloads/{id}/start`

`200 PowerResponse { changed, forced: false, workload }`.

A start of a `suspended` workload resumes it: the same process, from the same start, with what it
held in memory, and `resumed: true`. A resume that doesn't come back within
`workloads.resume_timeout_seconds` (10 by default) is killed and the workload started afresh on its
data, with `resumed: false`. `resumed` is absent on any other start. A start that boots the
workload puts a deferred spec in place first.

| Status and code | When |
|---|---|
| `409 no_compute` | The workload is retained. |
| `409 not_created` | An interrupted create; PUT again. |
| `409 container_missing` | The runtime lost the container; PUT again. |
| `409 insufficient_capacity` | Running memory would exceed the allocatable memory. This is the control plane's `RuntimeFull`. |
| `409 port_conflict` | Something else holds its host port. |

### `POST /v1/workloads/{id}/suspend`

With the epoch header (exact). Suspends a running workload with Docker's cgroup freezer: its
processes stop where they are and its memory is kept, until a start resumes it. A suspended
workload holds its memory on the node, as a running one does, and counts against what the node
gives out.
- `200 PowerResponse`; `changed: false` when it is already suspended.
- `409 not_running` for a workload that isn't running.
- Stop, kill, fence and delete reach a suspended workload as a running one: a stop's signal arrives
  as it thaws, so it saves on the way out. Export answers it as it answers a running one. Exec needs
  a running process, and a suspended one runs nothing: `409 not_running`.

### `POST /v1/workloads/{id}/stop`

The body is optional: `{ "timeoutSeconds": 1–600 }` overrides the spec's grace.
- `hermitboxd` sends `stop.signal`, waits the grace, then kills.
- `200 PowerResponse`. `forced: true` means the grace ran out and the workload was killed
  without saving.
- The request returns once the workload has exited, so it can take up to grace + 30 s.
- A workload that isn't running (one waiting out a restart's backoff, or a resume after the host
  went down) stays down. The stop is recorded and nothing starts it on its own. `changed: false`.

### `POST /v1/workloads/{id}/kill`

SIGKILL now, with no grace: the control plane's `forceStop`. `200 PowerResponse`. Like a stop, it keeps a
workload that isn't running from being restarted or resumed.

### `DELETE /v1/workloads/{id}[?data=keep|delete]`

- **`keep`** (the default): `hermitboxd` removes the container (stopping it gracefully first if it
  runs) and releases its ports.
  - The data stays. The workload becomes `retained`, and a later PUT brings its compute back.
  - This is the control plane's `decommission`.
- **`delete`**: the same, and the whole workload directory (record and data) is **moved to the
  host's trash** in one rename.
  - It is purged after `trash_retention_hours`.
  - This is the control plane's `destroy` or `release`.
  - It requires `x-blockly-confirm-delete-data: {id}`, echoing the id; otherwise
    `428 confirmation_required`. Data is never deleted on a single mistake.

`200 DeleteResponse { existed, removedContainer, data: "kept" | "trashed" | "absent", trashPath }`.

### `POST /v1/workloads/{id}/exec`

The body is `{ "command": ["argv", …], "timeoutSeconds": 1–600 }`, with a 30 s default. Limits:
≤ 256 arguments of ≤ 128 KiB each (Linux's own limit), ≤ 1 MiB in all.
- It runs **inside the workload**, as the workload's user, with its limits. It never runs on the
  host.
- `hermitboxd` adds no shell. Send `["sh", "-c", script, name, args…]` for one: a control plane
  does.
- Output is capped at 1 MiB per stream (`stdoutTruncated`, `stderrTruncated`).
- **On timeout `hermitboxd` kills the command, and every process it started, by host pid.** Docker
  has no API to do that ([moby/moby#35703](https://github.com/moby/moby/issues/35703)).
  - Each pid is checked against the container's cgroup first, in case it was reused.
  - `timedOut: true`, `killed: true`.
- The workload must be running (`409 not_running`). `hermitboxd` checks that, and the epoch, under
  the workload's lock. Then it runs the command in the container it found, by id, without holding
  the lock, so a stop or a fence never waits for an exec. If the workload stops or is replaced in
  between, the command runs nowhere else: `409 not_running`.
- An optional `Idempotency-Key` header is covered above.

`200 ExecResponse { exitCode, stdout, stderr, stdoutTruncated, stderrTruncated, timedOut, killed, durationMs }`.

### `GET /v1/workloads/{id}/logs[?tail=<count>&since=<unix>&follow=true]`

`application/x-ndjson`, one JSON object per line:

```json
{"ts":"2026-09-28T02:16:32.123Z","stream":"stdout","line":"application ready"}
{"event":"end","reason":"complete"}
```

- `tail` is at most 10 000. Without `follow` it defaults to 200 and the stream ends with
  `{"event":"end","reason":"complete"}`.
- With `follow` the stream continues **across the workload's restarts**:
  - It emits `{"event":"restarted"}` and reads each new run from its start.
  - It ends with `{"event":"end","reason":"removed"}` when the container is removed.
  - It also ends when the client disconnects.
- Lines are capped at 16 KiB.

### `GET /v1/workloads/{id}/stats`

`200 StatsView`:
- `state`, `uptimeSeconds`
- `cpuCores`: cores in use since the previous sample. `cpuSecondsTotal`,
  `cpuThrottledPeriods`, `cpuLimitMillis`
- `memoryBytes`, `memoryWorkingSetBytes` (usage minus inactive page cache), `memoryLimitBytes`
- `pids`, `pidsLimit`
- `memoryLimitBytes` and `pidsLimit` are limits the kernel enforces. A process sandbox without
  `memory-limit` has no kernel memory limit and reports no `memoryLimitBytes`.
- `networkRxBytes`, `networkTxBytes`
- `dataUsedBytes`, measured every `disk_usage_seconds` by a walk of the data directory that never
  follows a link out of it and leaves out any filesystem mounted inside it
- Heartbeat `WorkloadReport.metrics` carries the same typed `WorkloadMetrics` counters (`at`,
  `cpuCores`, `cpuSecondsTotal`, `cpuThrottledPeriods`, `cpuLimitMillis`, `memoryBytes`,
  `memoryWorkingSetBytes`, `memoryLimitBytes`, `pids`, `pidsLimit`, `networkRxBytes`,
  `networkTxBytes`, `dataUsedBytes`), with `cpuLimitMillis` reported only where enforced.

### `POST /v1/workloads/{id}/fence`

Body: `{ "currentEpoch": N }`: the control plane says which epoch is current.
- A copy older than `N` is stopped (gracefully) if it runs, marked superseded by `N`, and kept: its
  data stays where it is, and its Docker restart policy stays `no`.
- A copy at or past `N` is left alone, so a late fence is harmless.
- One older than `N` that is already superseded is fenced again all the same: its Docker restart
  policy is set to `no` again, and it is stopped if it runs. The answer says `changed: false`, so a
  repeated fence is harmless too.
- A fence the runtime couldn't carry out (it didn't answer) is an error, but the mark stands.
  Nothing starts the copy again, and `hermitboxd` stops it itself once a resync finds it running.
- Needs no epoch header: it is itself the statement of which epoch is current.
- Heartbeat answers carry the same instruction (below); this endpoint is for fencing at once.

`200 FenceResponse { changed, stopped, workload }`.

### `POST /v1/workloads/{id}/export`

Body: `{ "url": "…", "headers": { … }, "quiesced": false, "exclude": ["libraries"] }`, with the
epoch header (exact).
- `hermitboxd` writes the workload's data directory as a **gzip tarball of `./`-relative paths**,
  the control plane's archive format. It writes to a spool file under its state directory while
  hashing it, then `PUT`s it to the presigned `url` with a known length. It uses gzip's fastest
  level, since application files may already be compressed.
- `exclude` names entries at the top of the data to leave out (at most 64 plain names). These are
  what the image makes again when they are missing, so a move carries the data and not
  application bundles.
- Only a stopped workload exports, unless `quiesced: true` says the caller quiesced its saving
  (for example, flushing and quiescing an application writer). A superseded copy never exports.
- The data belongs to the workload, which can rearrange it while it is read. `hermitboxd` reads it
  relative to directories it already holds open, with `O_NOFOLLOW` at every step:
  - a symlink is archived as a symlink and never followed;
  - an entry swapped mid-read is skipped;
  - a file that grows while it is read is cut at the size its header states.

  Nothing outside the data directory can reach the archive.
- The URL is used once and never logged or stored.

**In parts.** One PUT carries at most `transfer.max_put_mb` (default 5115, 5 GiB less 5 MiB:
Cloudflare R2's limit, the strictest of the S3-compatible stores). For a larger archive the body
can also carry `"parts": { "partSize": 67108864, "urls": ["…", "…"], "headers": { … } }`. That is
an S3 multipart upload the control plane has begun, with a presigned URL for each part, in order.
`hermitboxd` packs first, then decides:
- An archive no larger than one PUT goes to `url`, whether parts were offered or not; their URLs
  are never called, and the control plane drops the upload.
- A larger one, with enough parts offered (`ceil(size / partSize)` of the URLs, from the first),
  goes in parts. Every part is `partSize` bytes but the last, each read from the spool with its
  length declared, one after another.
  - A part whose PUT fails on the network, or answers 5xx, 408 or 429, is sent again, up to three
    times in all. Any other answer, or a part with no `ETag`, fails the export
    (`502 transfer_failed`).
  - The response then carries `parts: [{ number, etag }]`, from 1, which the control plane
    completes the upload with. `hermitboxd` holds no credentials for the store, so it never
    completes or aborts an upload itself.
- A larger one without parts, or with too few, is `422 archive_too_large`, with
  `details.sizeBytes` (the archive's size) and `details.limitBytes` (one PUT's limit, or what the
  parts offered carry). It is refused once packed, before anything is sent. Asked again with
  enough parts, it goes.

`partSize` is 5 MiB to 5 GiB less 5 MiB, and `urls` 1 to 10,000 of them, or the request is `422
invalid_request` (`parts.partSize`, `parts.urls`) before anything is packed. The body still has
to fit `max_body_bytes` (2 MiB by default, about 2,000 presigned URLs); the control plane
offers about 64, larger parts for a larger archive. A node that lists the `multipart-upload`
feature takes `parts`; an older one refuses the field as unknown.

`200 ExportResponse { sizeBytes, sha256, format: "tar.gz", entries, durationMs, parts? }`. Upload
failures are `502 transfer_failed`. Too little disk for the spool is `507 insufficient_disk`: up
front, or once free disk falls under the floor while the spool is written. `hermitboxd` looks
every 256 MiB, within a file too. Data whose files state more than 256 GiB in all, more than a restore
unpacks, gets the same answer before the file that takes it past is read. A sparse file counts at
the size it states.

### `POST /v1/workloads/{id}/restore`

Body: `{ "url": "…", "sha256": "…" }`, `{ "snapshot": "<snapshot-id>" }` or
`{ "fork": { "workload": "<id>", "snapshot": "<snapshot-id>" } }` (feature `local-forks`), with the
epoch header (exact). The workload must exist (PUT first) and be stopped.
- **From a URL**, `hermitboxd` downloads the archive to a spool file, and checks its sha256 when one
  is given, before anything changes: `422 checksum_mismatch` leaves the data alone. It unpacks into
  a fresh directory beside the data, by these rules:
  - regular files and directories only (links, devices and the like are skipped and counted);
  - no absolute paths or `..`;
  - files opened with `O_NOFOLLOW`;
  - modes masked to 0755, and a directory's owner keeps full access, so a private (0700)
    directory stays private;
  - owned by the workload's user;
  - at most 256 GiB and 2 million entries;
  - at most 1 MiB of any member's long name, long link and PAX records, or of a skipped entry's
    data.

  Anything else is `422 invalid_archive`. An archive of several gzip members is read whole, as
  `gzip -d` reads it.
- **From a snapshot** this node holds of the workload (`404 snapshot_not_found` otherwise), it
  copies the snapshot beside the data, sharing blocks where the filesystem can.
- **A fork** reads another workload's snapshot on this node in the same way. It takes the memory
  too when:
  - that snapshot was taken of a VM asleep with its memory (its `memory` is set);
  - the VM still sleeps with that memory;
  - the fork is on the same tier;
  - and its spec differs from its source's only in what is each sandbox's own.

  Then its data directory gets the disk, it is `suspended`, and its first start resumes the
  source's processes under its own identity (`resumed: true`). Otherwise it copies the snapshot's
  disk alone.
- **Disk.** A restore from a URL is refused up front (`507 insufficient_disk`) when free disk is
  already under `min_free_disk_mb`. It is also refused when the archive's announced length
  (`Content-Length`) wouldn't fit above it. It is stopped with the same answer if free disk falls
  under the floor while it downloads or unpacks (`hermitboxd` looks every 256 MiB). One from a
  snapshot needs the snapshot's full size free above the floor, shared blocks or not, and is
  stopped the same way while it copies. Either way the data is left as it was.
- Then it swaps the directories in one atomic exchange (`renameat2`), so a crash leaves the old
  data in place or the new, never neither. The data it replaced goes to the host's trash. On a
  filesystem that can't exchange, it renames twice instead. A restore cut short by a crash is
  settled when `hermitboxd` starts. One whose new data was complete is finished (issue
  `restore_finished`); any other is removed, and the data is as it was.

`200 RestoreResponse { sizeBytes, sha256, entries, skipped, unpackedBytes, previousData, durationMs }`
(`sha256` is null for a snapshot).

### `POST /v1/workloads/{id}/snapshots`

Body: `{ "id": "<snapshot-id>", "quiesced": false }`, with the epoch header (exact). The id is the
caller's (the control plane's archive id, a UUID; the workload-id rules apply).
- A copy of the data directory into `workloads/<id>/snapshots/<snapshot>/`, beside the data and
  never mounted into the workload. On a filesystem that shares blocks (XFS with reflink, btrfs)
  every file is a `FICLONE`: the snapshot takes moments and no space until the data changes. On
  one that can't (ext4), it is a full copy. Either way it needs the data's full size free above
  the floor (`507 insufficient_disk`). Once the data moves on, a copy that shares blocks takes as
  much as a plain one. It is stopped with the same answer, and removed, if free disk falls
  under the floor while it copies. The same happens if the data's files state more than 256 GiB,
  as for an export.
- The same rules as an export: a running workload only with `quiesced: true`, only the current
  copy, and the same walk that never leaves the data directory.
- A VM asleep with its memory (`suspended`) is copied as its sleep left its disk, and stays asleep
  with that memory. Its snapshot's `memory` names it, for a fork on this node.
- Asking again with the same id answers `200` with the snapshot already made (`created: false`).
  A snapshot interrupted by a crash has no `snapshot.json` and is redone; what it had copied is
  removed when `hermitboxd` starts, as are spool files a crash left.

`201 SnapshotResponse { created, snapshot: SnapshotView }`, where `SnapshotView` is `{ id,
workload, epoch, createdAt, sizeBytes, files, method: "reflink" | "copy", quiesced, specDigest,
durationMs }`.

### `GET /v1/workloads/{id}/snapshots`

`200 { snapshots: SnapshotView[] }`, oldest first.

### `POST /v1/workloads/{id}/snapshots/{snapshot}/upload`

Body: `{ "url": "…", "headers": { … }, "parts": { … } }`, `parts` optional. The snapshot is PUT
to the presigned URL as an archive, exactly as an export would write it. When it is larger than
one PUT carries and parts are offered, it goes in parts, as the export section describes. No
epoch: a snapshot doesn't change. It doesn't hold the workload's lock either, so a long upload
never delays a stop. `200 ExportResponse`. A snapshot packs for one upload at a time: another
asked for meanwhile is `409 snapshot_busy`, and goes once the first ends.

### `DELETE /v1/workloads/{id}/snapshots/{snapshot}`

`200 { existed }`. Deleting what isn't there (a workload deleted with its data takes its snapshots
along) is not an error. During an upload of it: `409 snapshot_busy`.

### Ops listener (plain HTTP, loopback by default)

It asks for no certificate, so `ops.listen` is loopback or a private address (10.0.0.0/8,
172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, fc00::/7, fe80::/10): `hermitboxd` refuses to start with
0.0.0.0, `::` or a public address.

| Path | |
|---|---|
| `GET /healthz` | `200 ok` while the process runs. For systemd and liveness checks. |
| `GET /readyz` | `200` once Docker answers and `hermitboxd` has reconciled; `503` otherwise. |
| `GET /metrics` | OpenMetrics text: operations, durations, HTTP, auth failures, reconciliations, runtime events, workloads by state, ports, issues, per-workload memory, CPU and disk, snapshot bytes, `hermitboxd`'s own RSS and CPU, and in fleet mode heartbeats, contact age, the execution lease left and certificate renewals. |

## Error codes

| Status | `code` |
|---|---|
| 400 | `invalid_request` (malformed JSON or query, both `If-Match` and `If-None-Match`), `invalid_workload_id`, `invalid_snapshot_id` |
| 403 | `forbidden`: a verified certificate for a name that isn't allowed |
| 404 | `not_found`, `snapshot_not_found`, `no_route` |
| 405 | No `code`: a method the path doesn't take is refused with an empty body. |
| 409 | `no_compute`, `not_created`, `container_missing`, `not_running`, `not_stopped`, `not_quiesced`, `insufficient_capacity`, `no_free_ports`, `port_conflict`, `name_taken`, `stale_epoch`, `epoch_ahead`, `superseded`, `snapshot_busy`, `memory_sleep_unavailable`, `exec_busy`, `store_lease_required` |
| 412 | `precondition_failed` |
| 413 | `payload_too_large` (bodies over `max_body_bytes`, 2 MiB by default); `POST …/stop` reads its optional body raw, so its 413 is plain text with no `code` |
| 415 | `invalid_request` (a request that takes a JSON body, sent without a JSON `content-type`) |
| 422 | `invalid_request` (spec or exec validation, unknown fields), `idempotency_key_reused`, `invalid_archive`, `checksum_mismatch`, `archive_too_large` (an export or snapshot upload larger than one PUT carries, with no parts or too few offered; `details.sizeBytes`, `details.limitBytes`) |
| 428 | `confirmation_required`, `epoch_required` |
| 500 | `internal` |
| 502 | `runtime_error` (Docker refused something unexpected), `transfer_failed` (an export or restore couldn't move the bytes) |
| 503 | `runtime_unavailable` |
| 504 | `timeout` |
| 507 | `insufficient_disk` |

## The control plane's endpoint (fleet mode)

A node in fleet mode also talks to the control plane. It enrolls once, then beats, and renews its
certificates before they end. All are HTTPS to `fleet.url`, TLS 1.3, trusting only the fleet CA's
certificate (`fleet.ca`). The control plane's side is
[`node-endpoint.ts`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/src/node-endpoint.ts) and
[`registry.ts`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/src/registry.ts); the wire types are in
[`src/protocol/wire.rs`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/src/protocol/wire.rs).

### What a joining host fetches

Before a host has anything, it fetches four things from the endpoint, with no authentication
([`join-routes.ts`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/src/join-routes.ts)). None is secret, and each is
checked before it is used:

- `GET /fleet/v1/ca.pem`: the fleet CA. Fetched without checking the connection, since nothing is
  trusted yet, and then checked against the join token's hash; nothing else is fetched until it
  matches.
- `GET /fleet/v1/join.sh`: [`control/src/join.sh`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/src/join.sh), with
  [`deploy/daemon.json`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/deploy/daemon.json) written into it. Fetched over TLS checked against
  that CA.
- `GET /fleet/v1/blocklyd` and `GET /fleet/v1/blocklyd.sha256`: the static `hermitboxd` the control
  plane's image carries, and `<sha256 hex>  hermitboxd`, which `sha256sum -c` reads. Without the
  binary both are `404`, in plain text saying why.

An enrolled node's `hermitboxd upgrade` also asks for `GET /fleet/v1/blocklyd.json`: the offer a
heartbeat's answer makes (below), `{ "version": "…", "sha256": "…", "signature": "…" }`, which it
checks the same way.

**The join token.** `bk1.` and base64url (no padding) of
`{"u": "<endpoint-url>", "h": "<ca-pem-sha256>", "d": "<deployment>", "s": "<secret>"}`,
plus `"n": "<node-id>"` in a token that re-enrolls a node. `hermitboxd join` and enrollment read it
([`src/fleet/token.rs`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/src/fleet/token.rs)). Only `s` is sent to `enroll`, once `d` is the
configuration's deployment and `h` matches `fleet.ca`. A bare token, the secret alone, is still
accepted everywhere a token is. The control plane keeps the region, labels and the node to
re-enroll with the token, and decides by them. `n` only lets `join` tell the host it is pasted on
from another node's.

### `POST /fleet/v1/enroll`

No client certificate yet: the one-time token is the authorization. It is a bare token, or a join
token's secret; the control plane takes a whole join token too, and looks up its secret.

```json
{ "token": "…", "csrPem": "-----BEGIN CERTIFICATE REQUEST-----…", "facts": NodeFacts }
```

- `NodeFacts`: hostname, boot id, sha256 of `/etc/machine-id`, daemon version, protocol and
  features, the API address to dial, edge and control addresses, capacity, labels.
- The key behind the CSR is made on the node and never leaves it. The CSR's subject and names are
  ignored: the control plane names the node.
- **One key until answered.** `hermitboxd` writes the key to `identity/enroll-key.pem` (0600) before
  its first attempt. Every attempt asks for that key until one is answered, after a restart too. A
  spent token presented again with a CSR for the key that spent it gets a fresh answer for the
  same node. So an answer lost on the way (a timeout, a connection reset once the control plane
  had answered) is asked for again.
- The answer: `{ nodeId, deploymentId, serverCertPem, clientCertPem, caPem, allowedClients,
  heartbeatSeconds }`. Two certificates for the node's one key: serverAuth for its API, clientAuth
  for its heartbeats. `hermitboxd` ignores this `heartbeatSeconds`: it beats every `heartbeat_seconds`
  of its own configuration until a heartbeat answer names another interval (1–60 seconds). Between beats it sends one
  as soon as a workload's state, epoch or ports change, at most once a second.
- `caPem` must be the certificate in `fleet.ca`, compared as DER rather than as PEM text. From then
  on the node trusts that CA for the control plane and for who can call its API. An answer naming
  another is refused, and no identity is written.
- `hermitboxd` writes `identity/` (the enrollment key becomes `node.key`, 0600), then deletes the
  enrollment key and the token file. `node.json`, which says "enrolled", goes last, once both
  certificates are known to be for the key: an answer the node can't use leaves it unenrolled, to
  ask again. An unknown or expired token, or a spent one presented with another key, is
  `403 invalid_token`, one answer for all three.

### `POST /fleet/v1/nodes/{nodeId}/heartbeat`

With the node's clientAuth certificate, every `heartbeat_seconds` (5).

```json
{
  "nodeId": "…", "sessionId": "…", "bootId": "…", "seq": 42,
  "daemonVersion": "0.2.0", "protocol": { "current": 1, "supported": [1] }, "features": ["…"],
  "runtimeUp": true, "reconciled": true, "capacity": NodeCapacity,
  "workloads": [{ "id": "…", "epoch": 3, "supersededBy": null, "state": "running", "specDigest": "…",
                  "generation": 2, "memoryMb": 3072, "restartCount": 0, "exit": null,
                  "lastFailureAt": null, "changedAt": "…", "ports": { "http": 42001 } }],
  "issues": [],
  "addresses": { "api": "10.0.0.5:7443", "edge": "10.0.0.5", "control": "10.0.0.5" },
  "upgradeFailed": { "version": "0.3.0", "reason": "hermitboxd 0.3.0 exited with status 1 before it came up" }
}
```

- **The whole state, every time**: every copy the node holds, whatever its epoch. The first beat
  after a restart or a partition is therefore a full resync.
- The session id is new for each daemon run, and `seq` counts from 1 within it. The control plane
  uses them to ignore delayed beats and to catch two hosts sharing one identity.
- `issues` beside a workload is what the node found wrong with it and can't mend itself, each
  `{ "code", "detail" }`. That is a restart refused for want of room (`insufficient_capacity`),
  or data over its spec's size (`over_storage`). Left out when there is none. The top-level `issues` are
  the host's.
- `addresses` is where the node is reached as its configuration says now. The control plane
  follows a change (and records `node.addresses_changed`): the node's identity is its certificate,
  not its IP.
- `upgradeFailed` is the last upgrade this node gave up on, putting back the binary it had. It is
  sent in every beat until the node tries another, and left out when there is none (below).
- `capacity` includes `snapshotBytes` (what local snapshots hold) and `reflink` (whether they share
  blocks with the data). `usedMemoryBytes` and `usedCpuCores` add up the latest samples of the
  workloads running now; they are null only while workloads run and none has been sampled yet.
- The answer:

  ```json
  { "lifecycle": "active", "fences": [{ "workload": "…", "currentEpoch": 4 }],
    "heartbeatSeconds": 5, "leaseSeconds": 120 }
  ```

  `hermitboxd` applies each fence as `POST …/fence` would, **then** takes the lease, so nothing the
  lease allows can be a copy the same answer superseded. Each fence is marked at once and carried
  out in the background: the next beats go out on time while a fenced copy's grace runs out.
- **The execution lease** (`leaseSeconds`, counted from when the node sent the beat) lets
  `hermitboxd` act on its own while it lasts. It can restart a workload that failed, per its spec's
  policy, and resume one the host went down under (below). Without a lease (no answer yet in this
  run, or none for longer than the lease) it does neither. A node the control plane holds `lost`
  gets `0`. Requests carry their own authority (the epoch) and don't need the lease. A control
  plane that names no lease grants `restart_requires_contact_seconds`.
- A control plane that doesn't answer changes nothing on the node: workloads carry on running. It
  only stops what the node would do unasked.
- `renew: true` says the node's certificates end within the control plane's renewal window. The
  answer leaves `renew` out otherwise.
- `upgrade: { "version": "0.3.0", "sha256": "…", "signature": "…" }` offers the node the
  `hermitboxd` the endpoint serves at `GET /fleet/v1/blocklyd`, if the node lists `self-upgrade`.
  The answer leaves it out otherwise, and a node without the feature ignores it. `signature` is the
  release's `hermitboxd.sig` in hex: release.yml's ML-DSA-65 (FIPS 204) signature of the version
  and sha256, by a key only that workflow holds
  ([`src/upgrade/trust.rs`](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/src/upgrade/trust.rs) says what is signed).
  - A node that lists `signed-upgrade` takes an offer only with a signature, made by a key
    compiled into it, for that version and sha256. It also takes only a version no older than its
    own. Otherwise it downloads nothing, and reports the offer failed. A control plane with no
    signature for its `hermitboxd` offers it to none of them.
  - `hermitboxd` downloads it over this same mutual TLS, and installs it only if its sha256 is the
    one offered and `--version` prints the version offered. It keeps the binary it ran as
    `hermitboxd.prev` and renames the new one into place under the state directory
    (`bin/hermitboxd`, which `/usr/local/bin/hermitboxd` links to). Then it exits cleanly so
    systemd starts it; workloads keep running.
  - The new binary is on trial (`upgrade/trial.json`) until it has reconciled and a heartbeat is
    accepted, within 120 seconds; otherwise it puts `hermitboxd.prev` back and exits. One that
    can't start at all is put back by the unit's `ExecStopPost` (`hermitboxd.prev upgrade --exited`).
    So is one still on trial 240 seconds after it started (a startup that hangs), which exits.
    The binary put back reports `upgradeFailed`.
  - A download that fails for want of the control plane is tried again a minute later, while the
    offer stands; any other failure is reported. The control plane offers it to one node per
    region at a time ([operations](https://docs.hermitbox.dev/v0.3.2/guides/operate.md#certificates-and-upgrades)).
- A workload can include a `hostnameGateway` sample. Control accepts samples only for the
  placement's enrolled node and epoch. Optional observations share at most 256 KiB of the
  heartbeat's 4 MiB body after core state and any upgrade failure. When copies share the
  budget, the next acknowledged heartbeat resumes with the next copy.
- Refusals:
  - `400 invalid_json`: the body isn't JSON;
  - `400 invalid_request`: a beat for another node;
  - `401 certificate_required`: no client certificate from the fleet CA;
  - `403 wrong_identity`: not this node's client certificate;
  - `403 certificate_not_current`: not the node's pinned certificate;
  - `403 retired`;
  - `404 unknown_node`;
  - `409 duplicate_identity`;
  - `409 session_replaced`: a beat from a daemon run that has been replaced;
  - `413 too_large`: a body over 4 MiB;
  - `500 internal`.

### `POST /fleet/v1/nodes/{nodeId}/renew`

With the node's current clientAuth certificate: `{ "nodeId": "…", "csrPem": "…" }` for a **new**
key made on the node. The answer is `{ serverCertPem, clientCertPem, caPem }`.
- `hermitboxd` writes the new key and certificates as the next generation (`node-N.key`,
  `node-N.pem`, `client-N.pem`). It checks they load and that both certificates are for the new
  key, then rewrites `node.json` to name generation N. That rename is the switch: a crash anywhere
  leaves one whole generation in use.
- The API's certificate is replaced in place for new connections, and the next heartbeat uses the
  new client certificate. The control plane accepts the old certificate or the new one until the
  first beat that presents the new one, and then only the new one.
- An answer naming another CA (compared as DER, as at enrollment) is refused: rotating the fleet CA
  re-provisions nodes.
- A failed renewal keeps the current certificates and is tried again after ten minutes while the
  control plane still asks. A node whose certificates ended can't renew: it enrolls again with a
  new token ([operations](https://docs.hermitbox.dev/v0.3.2/guides/operate.md#certificates-and-upgrades)).

## After the host restarts

`hermitboxd` records, for each workload, the host boot (the kernel's boot id) in which it last saw
the workload running. It clears the mark once it sees the workload stop in that same boot. After
the host restarts, a workload was running when the host went down if:

- it is still marked with an earlier boot;
- it was never asked to stop;
- it is not superseded;
- and its restart policy is `on-failure`.

Such a workload reads `restarting`, and is started again once `hermitboxd` holds a lease
(single-node: at once). A fence in the same answer wins; a node held `lost` gives the resume up,
and forgets it. A restart of `hermitboxd` alone, in the same boot, resumes nothing: what died
while it was down is reported, not restarted.

A `suspended` workload's suspended process is gone with the host. After the restart it reads
`stopped` and is never resumed. A start boots it afresh on its data, with a deferred spec put in
place first. A restart of `hermitboxd` alone leaves it suspended.

## How a control plane maps onto it

A control plane keeps the node, epoch and host ports in whatever handle it issues. Each of its
port methods maps onto the calls above:

| Port method | Protocol |
|---|---|
| `ensureProvisioned(key, placement, spec)` | Choose the node, record the placement, then `PUT` the spec with the epoch and `POST start`. `RuntimeSpec` maps field for field. |
| `apply(handle, spec)` | `PUT` with the handle's epoch. |
| `start` / `stop` / `forceStop` | `POST start` / `stop` / `kill`, with the epoch. |
| `waitRunning` | Poll `GET` until `running`. |
| `exec` | `POST exec`, with the epoch. |
| `snapshot` | `POST snapshots` on the sandbox's node, then `…/upload` to the archive store in the background. |
| `exportSnapshot` | `…/upload` from the node while it holds the copy, else a copy within the store. |
| `restore` | In place from the node's own snapshot (`{snapshot}`); elsewhere `PUT` with a new epoch on the chosen node, then `POST restore` from the archive, checked against its sha256. |
| `relocate` | `POST export` from the stopped source with `exclude` (what the image remakes), then as a restore elsewhere; the old copy gets `POST fence` and `DELETE ?data=delete`. |
| `goneSnapshots`, `deleteSnapshot` | The archive store and `DELETE …/snapshots/{snapshot}` on the node. |
| `decommission` | `DELETE ?data=keep`. |
| `destroy`, `release` | `DELETE ?data=delete`, confirmed, on every node that holds a copy. |
| `observe`, `observeChanged`, `inventory` | Heartbeats, stored per node and copy: no call per sandbox. |
| `endpoint(handle, port, audience)` | From the handle, which carries the node's addresses and the host ports. |
| `locate` | Node, region, epoch and container name, from the handle. |
| `tag` | A no-op; labels are fixed at creation. |
| `prices` | A share of the node's monthly cost (its `monthly_cost_cents` label), by memory. |
| `LogSource.recent` / `tail` | `GET logs?tail=<count>` / `?tail=0&follow=true`. |

## Format names

Format v1 was first published with these names:

- the `blocklyd-epoch` and `blocklyd-protocol` headers;
- `blocklyd.*` container labels (including `blocklyd.record`);
- `workload.json`;
- the `bk1.` token prefix;
- the fleet paths `/fleet/v1/enroll`, `/heartbeat`, `/renew`, `/blocklyd`, `/blocklyd.sha256`,
  `/blocklyd.json` and `/join.sh`.

Those names, the record fields, spec digest, features and Docker daemon configuration stay until
protocol v2.

## Optional store lease

A host configured with `store_lease.enabled` announces `store-lease` in health and heartbeats,
once its independent cgroup watchdog passes startup checks. Other hosts do not announce it.

Control first GETs `/v1/workloads/{id}/store-lease` for its fresh daemon-session identity. Then,
before starting the copy, it can POST that endpoint with the ordinary epoch header and the
additive `StoreLeaseGrant` schema. The grant's presigned URLs stay in memory; records and labels
keep format v1 unchanged.

A missing or expired grant refuses starts and exec with `409 store_lease_required`. Expiry
freezes (`cgroup.freeze`) and kills the leased cgroup, and reports the issue
`store_lease_expired`. This includes stopped and suspended placements that keep a grant for wake.

See [store-lease.md](https://docs.hermitbox.dev/v0.3.2/reference/store-lease.md) for conditional takeover, host prerequisites, the fault model
and maintenance behavior. The existing execution lease, and all feature-off behavior,
stay as described above.

## Live exec

A node advertising `exec-stream` accepts `POST /v1/workloads/{id}/exec-stream` with the same
ExecRequest, epoch header and Idempotency-Key as `/exec`. It answers in NDJSON, with these
ExecEvent variants:

- stdout/stderr (`data`, `truncated`);
- exit (`code`, `timedOut`, `killed`, `durationMs`);
- an error envelope, for a failure after headers.

Validation before attachment keeps its HTTP errors. The Rust schema owns these shapes. `/exec`
still returns its existing buffered JSON response.

Both endpoints share the same idempotency cache. A cached stream replays bounded output, and
concurrent callers wait for the original command. Active keys are never evicted for capacity;
new keys are refused with `exec_busy` until there is room.

Failure and retry semantics are unchanged: callers must inspect uncertain outcomes and never
retry a command blindly.

Docker output uses 16 KiB payloads with two queues of eight frames, per-stream UTF-8 decoding,
and backpressure. Output keeps the existing per-stream bound and truncation flags. The command
timeout includes waiting for a queue, and still kills the verified container process tree.
Disconnecting HTTP does not cancel command containment or authorize a second execution. The v1
wire keeps this endpoint. Control and SDK commands use the [sandbox agent](https://docs.hermitbox.dev/v0.3.2/reference/sandbox-agent.md).

## Isolation selection

The optional workload-spec field `isolation` accepts `container`, `gvisor`, `process`, `wasm`
and `vm` ([sandbox tiers](https://docs.hermitbox.dev/v0.3.2/reference/tiers.md)). When a caller omits it, the node uses its configured
default. It refuses an explicit tier it cannot serve. Both the persisted workload and its recovery
label record the selected tier, including when the original request used the default.

Nodes announce their configured default as `default-tier-<isolation>` and each ready tier as
`tier-<isolation>`. Control checks the ready tier and its advertised capabilities when placing
a workload.

The local host document keeps its capability fields and adds `tiers`, each with state,
evidence and action. `hermitboxd probe --config <file>` applies that configuration's tier
selection without starting compute. `hermitbox doctor` uses an owned managed configuration when
it finds one.

## Tier-scoped optional capabilities

A backend capability is advertised for the ready tier that provides it. For example,
`tier-container:network-policy` means a ready container backend can enforce the requested
network mode. Control checks the selected tier before placement and before changing the
sandbox's network. Node-wide protocol features are reported separately. The generated node
OpenAPI document lists which features use tier-qualified names.
