# CLI

**Last updated:** 2026-11-27T14:16:11-03:00 (UTC-3)

The `gateway` binary is the server, and it also ships helper commands. The server, `validate` and `migrate` read an explicit `GATEWAY_CONFIG`, or the embedded edition-selected profile when unset. They do not inspect an implicit file in the current directory. `keygen` needs no configuration. The standalone healthcheck has the selection rules below.

| Command | What it does |
|---|---|
| `gateway` | Starts the server. Validates the configuration, applies the pending PostgreSQL migrations (or, with `storage.database.auto_migrate: false`, only verifies the schema) and starts serving on `listen` (default `:8080`) |
| `gateway validate` | Checks the configuration and the secret references without starting the server. Prints `configuration valid` or the error, and exits with a non-zero code if there is an error |
| `gateway edition` | Prints the embedded edition manifest without reading environment variables, resolving credentials or starting services |
| `gateway keygen` | Generates a token of 32 random bytes (`gw_...`) and its SHA-256. The token goes to whoever will use it; the SHA-256 goes into the configuration or the Secret |
| `gateway version` | Prints the build as one JSON line: `product` (`m7gtw`), `version`, `revision` (the source commit, or `unknown`), `modified` (`true` when the Git working tree the build ran in had uncommitted changes; absent when the build carries no Git information), `go` and `platform` (`os/arch`). Reads no environment or configuration |
| `gateway migrate` | Applies the pending PostgreSQL migrations and exits without opening the listener. Exit 0 when the schema is current, 1 on any error. See [below](#migrate) |
| `gateway migrate --check` | Reports whether migrations are pending and changes nothing. Exit 0 when current, 3 when migrations are pending, 1 when it cannot tell |
| `gateway reencrypt --check` | Authenticates the complete provider-key ciphertext inventory without writes or automatic schema migration. Exit 0 current, 3 valid migration pending, 1 failure |
| `gateway reencrypt --apply --offline` | Explicit quiesced-writer atomic provider-key migration; no listener, no automatic schema migration, aggregate audit. Exit 0 committed, 1 failure or uncertain commit |
| `gateway content-rewrap --check` | With `content_key_rotation`, authenticates every content-capture record not on the current content key without writes or schema migration. Exit 0 none left, 3 records to rewrap, 1 failure or records naming an unconfigured key or not authenticating |
| `gateway content-rewrap --apply [--unused-current-key]` | Rewraps content-capture data keys under the current content key beside serving replicas, one committed and audited batch at a time, skipping locked records; rerun resumes. Refuses a current key no stored record uses yet unless acknowledged. Exit 0 none left, 3 records skipped or written meanwhile remain, 1 failure or uncertain commit. See [content capture](/docs/features/content-capture/#rotating-the-content-key) |
| `gateway topics <command>` | A client of a running gateway's [Topics](/docs/features/topics/#commands) API: lists, creates, estimates, refreshes, pauses, resumes and deletes maps, reads topics and summaries, renames a topic. Reads `GATEWAY_URL` and `GATEWAY_ADMIN_TOKEN` from the environment (never a token in an argument), no configuration and no database. Exit 0 done, 1 refused or unreachable, 2 usage |
| `gateway healthcheck` | Probes the selected HTTP(S) target; exact 200 exits 0 silently, any other result exits 1 with a safe structured failure. It is the Docker image's healthcheck |

Each command takes no further argument, except `migrate --check` and the exact `reencrypt` and `content-rewrap` forms above. Anything else — an unknown command such as `gateway --help` or `gateway serve`, or an extra argument such as `gateway validate now` or `gateway migrate --dry-run` — prints the usage line to stderr and exits with code 2, before reading the environment or the configuration. It never starts the server.

```bash
gateway version
# {"product":"m7gtw","version":"0.0.1-rc.2","revision":"589d521a…","modified":false,"go":"go1.27.3","platform":"linux/arm64"}
```

The version is the one in `deploy/npx/package.json` (`0.0.1-rc.2`, the second private release candidate; the executable's built-in default says the same, which a test enforces): `scripts/build-gateway.sh` and `scripts/package-npx.sh` link it in, so the executable and the NPX package report the same version. A release build can set both values at link time: `go build -ldflags "-X main.version=1.2.3 -X main.revision=$(git rev-parse HEAD)" ./cmd/gateway`. Without `-X main.revision`, the revision comes from the Go toolchain's VCS stamp, present when the build runs inside a Git checkout; the Docker build has no `.git`, so the image reports revision `unknown` and no `modified`. [`scripts/build-image.sh`](/docs/operate/deployment-modes/#building-the-image) passes both to the build.

## Provider-key re-encryption

Use the [complete keyring maintenance procedure](/docs/security/keyring-rotation/#check-and-apply). It requires the explicit boot flag and externally supplied current/previous keys; no key is passed in command arguments. `--offline` acknowledges that every writer is stopped. Check does not publish audit or run DDL; apply preserves metadata and changes the twelve ciphertext columns atomically. A commit transport failure has an unknown outcome: retain both keys and check after recovery. A successful scan reports only its database snapshot, never permission to discard backups or restart an old writer.

## Migrate

`gateway migrate` is the schema step on its own. It reads the same `GATEWAY_CONFIG`, database URL (`storage.database_url_env`, or its `_FILE` with `secret_files`) and `storage.database` settings as the server, takes the same PostgreSQL advisory lock, applies each pending migration in its own transaction, logs one `migration_applied` line per step and the same `database_ready` summary as a booting gateway, and exits. It never opens the HTTP listener, and it applies migrations whatever `storage.database.auto_migrate` says: it is the step that setting expects someone to run.

Why a separate command: by default every gateway process migrates at boot, which is simple and safe (the lock serializes replicas). Some operators want the schema to change only at a moment they choose, once, under their deploy tooling: a Kubernetes Job before the rollout, a CI stage, a change window with a fresh backup. With `storage.database.auto_migrate: false` the serving processes never change the schema, and this command does.

```bash
GATEWAY_CONFIG=gateway.yaml gateway migrate --check
# {"level":"INFO","msg":"schema_status","schema_current":0,"schema_required":108,"migrations_pending":107,"up_to_date":false}
# exit code 3

GATEWAY_CONFIG=gateway.yaml gateway migrate
# {"level":"INFO","msg":"migration_applied","version":1,"duration_ms":8}
# ... one line per step ...
# {"level":"INFO","msg":"database_ready","connect_ms":2,"migration_lock_wait_ms":0,"schema_from":0,"schema_to":108,"migrations_applied":107,"migrations_ms":968,"migration_mode":"apply"}
# exit code 0
```

| Exit code | `migrate` | `migrate --check` |
| --- | --- | --- |
| `0` | Every migration this binary has is applied (including when nothing was pending) | Schema current: nothing pending |
| `1` | Error: invalid configuration, no database URL, database unreachable, lock timeout, schema newer than the binary, a failed step | Error: it could not tell (same causes, except the lock: the check takes none) |
| `2` | Usage error (unknown argument) | Usage error |
| `3` | — | Migrations are pending; nothing was changed |

The fields of `database_ready` are described in [managed PostgreSQL](/docs/operate/managed-postgres/#startup-and-migrations-in-the-log). The command logs JSON to stdout at `logging.level`; it does not export OTLP. Each `migration_applied` line is written when its step commits, so a run that fails or is stopped later has already shown what it applied. Errors are one `migration_failed` (or `migration_check_failed`) line; when a step fails, the line also carries `failed_step` and `schema_reached` (the newest version now recorded), and the message says the same:

```json
{"level":"ERROR","msg":"migration_failed","failed_step":93,"schema_reached":92,"error":"postgres migration failed (SQLSTATE 42P07) at step 93; the schema is at version 92 and the next run resumes there"}
```


| Cause | Message (`error`) |
| --- | --- |
| No database URL | `PostgreSQL is required: set GATEWAY_DATABASE_URL (storage.database_url_env), or GATEWAY_DATABASE_URL_FILE with secret_files, ...` |
| `GATEWAY_DATABASE_AUTO_MIGRATE` set to anything but `true` or `false` | `GATEWAY_DATABASE_AUTO_MIGRATE must be true or false` (the same check as the server, before connecting) |
| `GATEWAY_POSTGRES_AUTO_MIGRATE` set (the 0.0.1-rc.2 name) | `GATEWAY_POSTGRES_AUTO_MIGRATE was renamed to GATEWAY_DATABASE_AUTO_MIGRATE; set GATEWAY_DATABASE_AUTO_MIGRATE instead and remove the old variable` (also from `validate` and the server) |
| A `storage.postgres` block (the 0.0.1-rc.2 name) | On stderr, before any log line: `invalid configuration: configuration key storage.postgres was renamed to storage.database; rename it in the YAML (the keys inside keep their names)` (also from `validate` and the server) |
| Database unreachable or credentials refused | `postgres startup failed; check connectivity, TLS and credentials` (after retrying a refused or starting database for `startup_timeout`), or the server's SQLSTATE |
| Another process holds the migration lock past `migration_timeout` | postgres migration: timed out waiting for the migration lock, which another gateway or `gateway migrate` holds; let it finish or raise `storage.database.migration_timeout` (waited 2000 ms) |
| The database was migrated by a newer release | `postgres migration: database schema has migration 109, newer than this binary supports (108): ...` |

`--check` reads `gateway_schema_migrations` without the lock and without creating the table, so it is safe against a live database and while a migration runs elsewhere (a migration in progress reads as pending). SIGINT or SIGTERM cancels a running `migrate`: PostgreSQL rolls back the step in flight, the steps already committed stay, and the next run resumes after them. Each run is bounded by `startup_timeout` + `migration_timeout`.

## Healthcheck

```yaml
server:
  healthcheck_url: "" # default: derive http://<listen-host>:<listen-port>/health/ready
```

The standalone command selects its target in this order:

1. A nonempty `GATEWAY_HEALTHCHECK_URL` is validated and used without opening any configuration file. An invalid override fails before sending; it never falls back. This supports a portable probe and does not certify the local YAML.
2. Otherwise, structurally decode the explicit nonempty `GATEWAY_CONFIG`, or the embedded edition-selected profile when unset. An explicit missing/unreadable file, or an empty, null, non-mapping, multiple-document, unknown-field or structurally mistyped selected YAML fails before sending. Structural decoding does not expand provider presets, resolve credentials or validate unrelated provider semantics; use `gateway validate` for full configuration validation.
3. A nonempty `server.healthcheck_url` wins over derivation from `listen`. An omitted/empty listen defaults to `:8080`. Empty/IPv4 wildcard hosts become `127.0.0.1`; the IPv6 wildcard becomes `::1`; concrete hosts retain their family. Local TCP service names are resolved to numeric ports, without DNS lookup or TLS inference: a listen port named `https` still derives an HTTP URL. Invalid/unknown ports and any numeric spelling of zero cannot produce a standalone target; configure an explicit target instead. There is no malformed-listen fallback to port 8080.

An explicit target must be an absolute lowercase `http://` or `https://` URL of at most 2,048 bytes, with a valid host and optional numeric port from 1 to 65,535. IPv6 literals require brackets; paths are allowed. Credentials, query delimiters, fragments, opaque URLs and control characters are rejected. This is syntax validation, not DNS resolution or destination health verification. Targets are local operator configuration, never client request input.

The command keeps its two-second HTTP client deadline. Only status 200 succeeds; redirects are **not followed**, including redirects to another local path. On upgrade, configure the final readiness URL if the old target redirected. No provider credential, database or OTLP exporter is needed. The command sends a fresh `X-Request-Id` (also the correlation ID) and W3C `traceparent` so the target's request logs can identify the probe.

Failure emits one JSON `healthcheck_failed` event with a fixed code (`configuration`, `refused`, `timeout`, `unavailable` or `status`), request/trace/span IDs and, for HTTP failures, numeric status and standard status text. It never prints the URL, host, path, configuration filename or raw transport error. Success remains quiet.

Normal server startup still validates the complete configuration, including a latent YAML target even when an environment target wins. Startup captures the selected source once for the [console summary](/docs/features/console/#startup-healthcheck-selection). If automatic derivation fails, that summary is unavailable; it does not introduce a new listener failure or remove support for ephemeral listen ports. Explicit invalid targets still fail startup. The standalone command resolves its own current file/environment at each invocation; the captured summary is not its future configuration and is not a health result.

## Examples

```bash
gateway keygen
# token: gw_9f2c...    → give it to the app or the administrator
# sha256: 4b1d...      → GATEWAY_CLIENT_KEY_SHA256 or GATEWAY_UI_ADMIN_SHA256

GATEWAY_CONFIG=config/gateway.yaml gateway validate
```

## Process variables

| Variable | Purpose |
|---|---|
| `GATEWAY_CONFIG` | Path to the YAML |
| `GATEWAY_HTTP_READ_TIMEOUT` | Request read timeout (default 30 s, from 5 s to 5 min) |
| `GATEWAY_DRAIN_DELAY`, `GATEWAY_SHUTDOWN_TIMEOUT` | Overrides for [lifecycle YAML](/docs/operate/shutdown/): drain delay and HTTP shutdown budget; both checked by validate |
| `GATEWAY_PARENT_LIFELINE_FD` | Set by the NPX launcher on macOS and Linux, never by default and not for you to set: the number of an inherited pipe whose end, when the launcher dies (even by SIGKILL), starts the [drain](/docs/operate/shutdown/#stop-it-from-a-terminal-or-a-process-manager). The gateway reads it once at start, removes it from its environment and keeps the pipe from the processes it starts (a secret manager's CLI). A value that is not the readable end of a pipe or of a connected socket, 3 or above, fails the start and validate |
| `GOGC`, `GOMEMLIMIT` | Go runtime variables, initialized before every command reaches `main`; [precedence and diagnostics](/docs/operate/runtime-configuration/#environment-precedence-and-go-startup) |
| `GATEWAY_HEALTHCHECK_URL` | Nonempty explicit HTTP(S) target override; also captured as startup selection metadata |
| `GATEWAY_DATABASE_AUTO_MIGRATE` | `true` or `false`, exactly: overrides `storage.database.auto_migrate` for the server. An empty value counts as not set. Anything else (`True`, `1`, `no`) fails startup, `validate`, `migrate` and `migrate --check`, so a typo never decides whether a process migrates. The Helm migration Job sets it to `false` on the Deployment; the console reports the source as Environment. Its 0.0.1-rc.2 name, `GATEWAY_POSTGRES_AUTO_MIGRATE`, is refused, not read ([upgrading from 0.0.1-rc.2](/docs/operate/operations/#upgrading-from-001-rc2-infrastructure-names)) |

Secrets (provider keys, token hashes, session key, encryption key, database URL) come in through the variables the YAML references, through `<NAME>_FILE` files or through secret stores. See [operations](/docs/operate/operations/).

## GitOps and identity import

- `gateway source-of-truth --plan` prints the GitOps dry run; `gateway source-of-truth --apply <digest>` applies it (T168). See [GitOps source of truth](/docs/reference/gitops/).
- `gateway import-identities --file <path> --dry-run|--apply` creates teams and invitations once from a file; it is not a sync. See [GitOps source of truth](/docs/reference/gitops/#one-off-user-and-team-import).
