CLI reference
RaySpec ships two executables. After pnpm build they are the built entry files; in a published install they land on your PATH:
rayspec— the diagnostic/dev CLI documented here (packages/app/cli).rayspec-serve— the boot server, documented at the end of this page.
For the walkthrough that uses these commands in order, see getting-started; for the grammar the validating commands check against, see the spec reference.
Conventions#
Every rayspec subcommand emits exactly one JSON object on stdout — with one documented exception, --help, which prints plain text there instead (see below) — and uses this exit-code contract:
| Exit | Meaning |
|---|---|
0 | Success — the spec is valid / the plan passed / the action succeeded. |
1 | A not-ok result — an invalid spec, a blocked migration, a failed op. The JSON result explains why (in its errors / findings). |
2 | A usage/CLI error — an empty argument list, an unknown subcommand, or an unknown/invalid flag (including a missing or invalid required flag or path for gen-handler, tenant and dev). A short JSON error is written to stderr and the usage text is printed. The bundle verbs also use 2 for an archive, manifest or inventory they refuse, bundle sign for a signature file that exists, and pack for an application it cannot package or an output that exists. |
3 | Incompatible — a bundle pins another runtime, a target or a capability this runtime does not provide, or an application declares a @rayspec/* range that excludes the runtime it pins; for export, state a snapshot cannot carry (a second organization, an unknown table, no database write barrier); for import, a snapshot of another runtime or server major, or a dump with a second organization. Bundle verbs, pack, deploy <file.ray>, export and import only. |
4 | Policy refusal — a reserved binding name, a secret in a bundle, a signature that does not verify, a key file other users can read, a fence epoch that is not the held one, a dump the import allowlist refuses, an import target that is not empty. Bundle verbs, pack, deploy <file.ray>, export, import and resume only. |
5 | Retryable — a database that cannot be reached, a lock another operation holds, a source that did not drain before the deadline. deploy <file.ray>, export, import and resume only. |
6 | Interrupted by SIGINT or SIGTERM before the command finished, or blocked until reconciled (schema drift, a failed restore). Bundle verbs, pack, deploy <file.ray>, export and import only. |
7 | An unexpected internal failure (a defect, not a verdict). A short JSON error is written to stderr. |
The existing commands keep 0, 1 and 2 for every outcome they have; only an unexpected internal failure changed, from 2 to 7. A bundle verb or pack that fails several checks exits with the class that comes first in the order 7, 6, 4, 3, 2, 1, 5.
A bad, missing, or out-of-jail spec path given to doctor, plan, or openapi is not a usage error — it is caught and returned as an ok: false result on stdout (exit 1), the same channel as an invalid spec.
The commands split into these groups:
- A read-only diagnostic floor —
doctor,plan,openapi,gen-handler. These never mutate a real/target database and never print secret values. - The
bundlegroup —bundle inspect,bundle verify,bundle sign. They read a.raybundle and never extract, import or run anything from it.inspectandverifywrite nothing;signwrites one detached signature file and nothing else. They answer with the result envelope described under--json. packwrites one.rayapplication bundle from an application that is already built. It builds, imports and runs nothing, and writes nothing but its output file. It answers with the result envelope too.export,importandresumemove a self-hosted deployment:exportfences it and writes its complete snapshot, encrypted, as a migration bundle;importrestores that bundle into a new, empty target and leaves it fenced until its one-time cutover token releases it;resumereleases an export's fence. All three answer with the result envelope. See Exporting a deployment and Importing a deployment.- A production-mutating
tenantgroup —tenant ensure. It writes to the databaseDATABASE_URLnames (and applies the committed migration chain to it), so it is deliberately not underdev, which is local-only. It prints no secret value: a minted invite token goes to a file and nowhere else. - A clearly separated local-dev, mutating
devgroup —dev gen-secrets,dev db,dev bootstrap-tenant. These deliberately write a secrets file, create a database, or provision a tenant.
The --version flag#
One flag stands outside the subcommand grammar. rayspec --version (or -v) reports the CLI's own version on stdout and exits 0:
{ "ok": true, "version": "1.9.1" }The value is read from the CLI package's own manifest at run time, so it names the version you actually have installed. It takes no arguments: a token after it is refused as a usage error (exit 2) rather than ignored.
The --help flag#
--help (or -h) is a help request, not a usage error: it prints help on stdout and exits 0. It is the one exception to the single-JSON-object rule above — the help text is plain text, so a set -e script or a CI smoke step can run it and read it.
Named on its own it prints the full manual; named after a command it prints that command's help alone, which is how you ask what flags one command takes without scrolling the whole thing:
$ rayspec deploy --help
rayspec deploy — RaySpec CLI
PRODUCTION-MUTATING (boots + serves a real deployment; mutates the target DB):
rayspec deploy <spec.yaml> [--port <n>] [--host <addr>] [--apply-migration …]
…A group answers for its members: rayspec dev --help prints all three dev commands, rayspec dev db --help just that one.
The flag is honoured where a command name sits — rayspec --help, rayspec <command> --help, rayspec <group> <sub> --help — and, like --version, it takes no arguments: a token after it is refused as a usage error (exit 2) rather than ignored. Everything past the command path is that command's own argument grammar, which the top level hands over untouched, so a -h written further along is still that command's to interpret.
Every other leading --flag remains a usage error (the exit-2 row above): with no subcommand there is nothing to dispatch it to.
The --json flag#
--json is accepted by every command, anywhere before a -- terminator. It switches the answer to the result envelope, one JSON object on stdout:
{
"contractVersion": "1.0.0-rc.2",
"ok": false,
"operation": "doctor",
"operationId": "3f0c2a8e-9b1d-4c47-8e2a-5d7f6b1c9a04",
"data": { "ok": false, "errors": [{ "code": "unknown_field", "message": "…", "path": "bogus" }], "warnings": [] },
"errors": [{ "code": "SPEC_UNKNOWN_FIELD", "message": "…", "path": "bogus", "retryable": false }],
"warnings": [{ "code": "RAY_W_LEGACY_OUTPUT", "message": "this command reports its own result object in data" }]
}okistrueexactly whenerrorsis empty;errors[0]is the first check that failed.operationIdis a fresh random UUID for each invocation. It is also printed as the first line on stderr (operationId: <uuid>), so a saved envelope and the stderr log of the same run can be matched.- On an existing command,
datais the command's own result object, unchanged, and the warningRAY_W_LEGACY_OUTPUTsays so. A spec error appears inerrorsasSPEC_plus its code in upper case (unknown_fieldbecomesSPEC_UNKNOWN_FIELD); any other error of the result becomesRAY_CHECK_FAILEDwith its message. A usage error isRAY_USAGE(exit2) withdata: null, and the usage text is not printed. The exit code is the one the command has without the flag.--helpand--versionput their text or object indata. - A serving
deploywith--jsonprints its banners on stderr instead and writes its one envelope when it stops:ok: trueafter a SIGINT/SIGTERM shutdown (exit0),ok: falsewith the refusal asRAY_CHECK_FAILEDwhen the boot is refused (exit1). - With role separation on (
RAYSPEC_MIGRATION_DATABASE_URLset), a servingdeployorrayspec-servekeeps the migration role in the process you started — which never imports the application — and serves the application in a child process started without it, so two Node processes appear under the deploy. A SIGINT or SIGTERM to the process you started drains and stops both; a crash of the child makes it exit non-zero and say so. Signals, exit codes, readiness and the--jsonenvelope are otherwise unchanged, and single-role mode (no migration URL) runs one process exactly as before. - Without
--json, every existing command's output is what it has always been. - The bundle verbs and
packalways answer with the envelope; for them the flag only silences the short description (forpack, the inclusion summary) they otherwise print on stderr.
The spec-path jail#
Every command that reads a spec resolves the path against the current working directory and rejects a path that escapes it — a .. climb above the cwd, or an absolute path pointing outside the cwd, is refused. The check is re-applied after symlink resolution, so an in-cwd symlink pointing outside is also refused. The file must exist, be a regular file, and be within a 1 MiB cap.
Every one of those read-time refusals is reported through the same envelope as a malformed document: code is yaml_parse_error, and the message is what names the cause — spec path "…" escapes the working directory …, spec path is not a regular file: …, spec file not found: …, spec file is N bytes — exceeds the 1048576-byte cap. That flattening is deliberate: the envelope stays uniform across the closed code set below. So a tool that needs to tell a jail refusal from a syntax error must read the message, not the code.
The practical consequence: run the commands from the directory that contains your spec (typically the repo root), and pass a path inside it. An absolute path to a spec outside the working directory will be rejected — this is a deliberate, defence-in-depth jail, not a bug.
init#
rayspec init [dir] [--force]Scaffolds a new project: writes a minimal, valid starter rayspec.yaml (one items store and its CRUD routes, no agent and no custom code) into [dir], default the current directory. The starter needs no build step and no provider credential; validate it with rayspec doctor and preview a deploy with rayspec plan.
- Postgres: not needed.
- Flags:
--forceoverwrites an existingrayspec.yaml. Without it an existing file is never touched. - The directory is resolved against the current directory and must stay inside it, like every other path the CLI writes.
Output:
{ "ok": true, "command": "init", "created": ["demo/rayspec.yaml"], "path": "demo/rayspec.yaml", "nextSteps": ["rayspec doctor demo/rayspec.yaml", "rayspec plan demo/rayspec.yaml", "…"], "errors": [] }An existing file without
--forceisok:falsewith the codespec_exists.- Exit:
0written,1the file exists,2a usage error (an unknown flag, a second positional, a directory outside the current one).
doctor#
rayspec doctor <spec.yaml>Statically validates a spec against the grammar. No database, no network. It runs the strict parser plus the semantic linter and reports the full, fail-closed list of violations (not just the first). Validates either profile — it dispatches on the product: discriminant.
- Postgres: not needed.
- Flags: none (exactly one positional spec path; an unknown flag is a usage error).
Output:
{ "ok": true, "errors": [], "warnings": [] }warningsis part of every envelope, empty or not. It carries the non-fatal advisories the linter raised — each acode, amessageand apath— and never affectsokor the exit code.A fourth key,
suppressed, is present only when a node'slintSuppressacknowledged an advisory: the finding moves out ofwarningsinto it, carrying the finding'scode, the acknowledgement'sbecauseverbatim, and the finding'spath. It does not affectokeither, and a document that acknowledges nothing gets nosuppressedkey at all:{ "ok": true, "errors": [], "warnings": [], "suppressed": [{ "code": "cron_tenant_required", "because": "…", "path": "triggers[0].kind" }] }On failure, each entry carries a closed
code, amessage, and an optionalpath:{ "ok": false, "errors": [{ "code": "unknown_field", "message": "…", "path": "stores[0].colums" }], "warnings": [] }- Exit:
0if valid,1otherwise.
plan#
rayspec plan <spec.yaml> [--against <old-spec.yaml>] [--allowlist <file.json>]
[--reconcile-injected-columns]Runs the read-only front half of a deploy: it validates the spec, computes the migration SQL it would apply, and runs the destructive-change safety gate. It never applies a migration to your target database, never rolls out, and never introspects a live target.
- Postgres: not required for the validate/diff/gate work. If
SHADOW_DATABASE_URLis set (and there is SQL to apply),planadditionally applies the generated SQL to a throwaway shadow database whose name it generates and drops afterward — to prove the SQL is clean. It never mutates the target database. A fail-closed guard refuses to shadow-apply if the shadow URL resolves to the same host and database name asDATABASE_URL. That guard resolves its comparison target from aDATABASE_URL_FILEfile mount as well as the plainDATABASE_URL(the file form takes precedence when set), so it still fires when the connection string is supplied only through the mount. Becauseplanis read-only and never connects to the real database, a brokenDATABASE_URL_FILE(missing, unreadable, a directory, or empty) is not fatal here — unlike a server boot:planemits one stderr warning (naming the variable, the path, and the OS error code, never the file content) and proceeds with no comparison target rather than falling back to a possibly-stale plainDATABASE_URL. With neither form set there is nothing to compare and the guard does not fire. - Flags:
--against <old-spec.yaml>— optional. Switches to update mode: instead of a first materialization,plandiffs the prior spec file into a delta migration. The baseline is the old spec file, never a live-DB introspection. A destructive delta is blocked unless covered by an allowlist, and the machine-proposed allowlist is surfaced so a reviewer can copy the entries they approve. Must be the same profile as the new spec.--allowlist <file.json>— optional; requires--against. A reviewed JSON array of{ kind, match, reason }entries that let an approved destructive delta preview as would-pass. A bad allowlist aborts at validation (fail-closed) — it never silently clears a finding.--reconcile-injected-columns— optional; requires--against(update mode only). Forces the platform-injected-column reconcile: the delta then also carries an idempotentADD COLUMN IF NOT EXISTS "created_by"/"idempotency_key"plus the tenant-scoped idempotency unique index, for a database materialized before those injected columns existed. A spec never declares the injected columns, so a spec-vs-spec diff is otherwise blind to them;IF NOT EXISTSkeeps it a no-op on an already-current database. Passing it without--againstis refused fail-closed (a first materialization creates those columns fresh). Without the flag (the default) the diff never touches the injected columns, so the spec-vs-spec plan stays phantom-free.
Output (a stable envelope; update/product fields are additive):
{ "ok": true, "stores": [{ "name": "notes", "columns": 3, "foreignKeys": 0 }], "migrationSql": "CREATE TABLE …", "routes": [{ "method": "POST", "path": "/notes", "action": "store" }], "agents": [{ "id": "summarizer", "backend": "openai", "model": "gpt-4o-mini" }], "gateFindings": [], "gateSummary": "", "breakingChangeBlocked": false, "shadowApplied": false, "errors": [] }Key fields:
ok;phase(validate|gate|shadow, on failure);stores/routes/agents(projected summaries — never raw secrets);migrationSql(the reviewable SQL);gateFindingsandgateSummary(the per-statement destructive-scan verdict);breakingChangeBlocked(true when the gate would block the deploy);shadowApplied;errors. In update mode it also carriesupdateMode,proposedAllowlist, andnotes; for a product-profile document it carriesproductsection counts and, when a shadow ran,driftFindings. A backend-profile document that carries non-fatal advisories — the findings of the same document passdoctorruns, such as a handler module that needs a build step before deploy — also carriesspecWarnings(the structured list) andspecWarningSummary(one readable line each). These are the raw findings:plandoes not apply the document'slintSuppressacknowledgements, so a finding a node has acknowledged is moved out ofdoctor'swarningsand still listed here. An advisory never changesokand never blocks a plan; the fields are omitted when there are none. They are document findings, distinct from the operational stderr warning the read-only guard emits for a brokenDATABASE_URL_FILEmount.- Exit:
0if the spec validated, the gate did not block, and any shadow applied cleanly;1otherwise.
openapi#
rayspec openapi <spec.yaml>Emits an OpenAPI 3.1 document for a product-profile document's declared view surface — the read routes, their parameters, and their response contracts — as a deterministic client contract.
- Postgres: not needed.
- Flags: none (one positional spec path).
- Profile: product-profile only. A backend-profile document has no declarative
viewssection, so it is rejected fail-closed (unsupported_version) rather than emitting a misleading empty document. Output:
{ "ok": true, "openapi": { "openapi": "3.1.0", "info": { "title": "…", "version": "1.0" }, "paths": {}, "components": { "schemas": {} } } }The command reports
info.version: "1.0"(the authoring language version). Note that a running product deployment's served OpenAPI document reflects an internal engine compatibility target instead — see the spec reference version note.- Exit:
0on success,1on an invalid/non-product/unreadable spec.
gen-handler#
rayspec gen-handler --holes <holes.json> --out <dir> [--emit <ts|js>] [--file <name>]Renders one escape-hatch handler module from a bounded template, driven by a "holes" contract (a small JSON file). The emitted code imports the handler SDK type-only, takes zero npm dependencies, and reaches the database only through the injected tenant-bound handle — so a generated handler cannot escape tenancy.
- Postgres: not needed.
- Flags:
--holes <holes.json>— required. The typed holes contract (size-capped; path-jailed to the cwd).--out <dir>— required. The output directory (created if absent; path-jailed to the cwd).--emit <ts|js>— optional, defaultts. The emit target.tsrenders TypeScript source;jsrenders the same program as plain ESM JavaScript. Because the SDK import is type-only,jsdrops exactly what a compiler would erase — and nothing else.--file <name>— optional. A bare filename (no path separators, ending in the extension--emitselects) overriding the default filename. The default is the export name lower-kebab-cased plus.gen.<ts|js>(e.g.persistNote→persist-note.gen.ts).
Output:
{ "ok": true, "file": "handlers/persist-note.gen.ts", "exportName": "persistNote", "template": "persist", "emit": "ts", "nextSteps": ["…"], "errors": [] }A malformed holes set is
ok: falsewith anerrorsentry (exit1); a missing/invalid flag is a usage error (exit2).
The holes contract#
The holes file is one JSON object whose template field selects the shape: "persist" (a write handler) or "lookup" (a read handler). Both carry exportName and store. A persist set adds columns, successStatus, mode (update-by-id or upsert-by-natural-key) with the idArg or naturalKeyCol that mode needs, and the optional fkRevalidate, fixedValues and clampValues. A lookup set adds filterCols, projectCols, maxRows, and the optional fixedFilter and substringArg/substringCol pair. Every field is validated fail-closed, and every hole object whose shape is fixed carries a closed key set: the hole-set itself (per template), each columns[] entry, fkRevalidate, and each clampValues rule. A key that shape does not declare — a typo, or a key belonging to the other template — is rejected by name (naming the known key it is a near-miss of), never ignored, because an ignored key silently drops the mechanism it was meant to configure: fkRevalidate mistyped drops the whole FK re-check, and lookupFixedFilter mistyped inside it drops that re-check's fixed predicate. The map-valued holes (fixedValues, fixedFilter, lookupFixedFilter, clampValues) are keyed by column name instead, so their keys are fenced by the snake_case charset and the column rules — which leaves no tolerated annotation prefix at any level. So a malformed hole-set never reaches a renderer.
What each field means, and the coherence rules over combinations of them, is specified in the authoring skill — read that before writing a holes file. This reference deliberately does not restate the contract, so it has exactly one specification.
Which target to emit#
deploy loads every handlers[].module as compiled JavaScript only — it refuses a .ts module fail-closed (the failure and the fix are walked in getting-started → the backend profile). So a --emit ts render is not yet deployable: compile it first (the examples/acme-notes-backend/build.mjs wrapper transpiles the handlers and rewrites the spec's module: paths) and point handlers[].module at the built .js. A --emit js render skips that step — wire handlers[].module straight at the emitted file and deploy, provided the deployment directory resolves .js as ESM ("type": "module" in its nearest package.json, which the build wrapper also writes). The nextSteps field of the envelope states this for the target you actually asked for.
pack#
rayspec pack --spec <path> --output <file.ray> [--id <application-id>] [--version <semver>]
[--runtime <exact-version>] [--include <path>]... [--against <old-spec>
[--allowlist <file.json>]] [--source-maps] [--preview] [--force] [--json]Writes an application bundle (.ray) from an application that is already built: the spec, the compiled handler and extension modules with everything they import, the built frontend directories, the product configuration files, the third-party packages the modules need, the dependency lock, a CycloneDX SBOM (payload/sbom.cdx.json) and the license notices (payload/THIRD-PARTY-NOTICES.txt). What goes in, what never does and how to fix each refusal are in the packing guide.
It runs these steps in order and stops at the first failure:
- Arguments.
RAY_USAGE;--allowlistwithout--againsttoo. With--against <old-spec>, the product delta comes next: the previous spec must parse (RAY_SPEC_INVALID) and be of the same profile, the delta from its stores to the new spec's is generated asplan --againstgenerates it, a destructive statement the--allowlistfile does not clear is refused naming the store and column and the review step, and the product schema digests the delta migrates between are computed on a throwaway database on the serverSHADOW_DATABASE_URLnames (missing or unusable:RAY_USAGE, never naming the server). Each of these refusals isRAY_USAGE. - Spec. The spec (either profile) is parsed.
RAY_SPEC_INVALID, followed by each grammar error as aSPEC_code. - Identity.
metadata.idandmetadata.versionof a backend spec, orproduct.metadata.idandproduct.metadata.versionof a product spec;--idand--versionoverride them. Neither the name nor the runtime version is ever used instead.RAY_APPLICATION_IDENTITY_MISSINGwith reasonidorversion. - Closure. The inclusion list is built from what the spec names, never from the directory as a whole, and every path stays inside the directory of the spec.
@rayspec/*packages are never copied: the runtime provides them, and a declared range that excludes the pinned runtime isRAY_RUNTIME_UNSUPPORTED. A missing or uncompiled module (with the build instruction in the message), an unresolved or computed import, a shared peer dependency that would need two copies, a symbolic or hard link, an explicitly named excluded file, a native addon not built for linux/x64 and Node 22, a package binary oros/cpufield for another platform, or a source map (a file or inlined) without--source-mapsisRAY_CLOSURE_INVALIDwith reasonunresolved-import,escaping-link,excluded-file,native-moduleorsource-map-not-opted-in. - Secret scan. A private key or a secret file name in any file that would go in.
RAY_SECRET_DETECTED, naming the path and never the content. - Manifest. The bundle must stay within the entry, path and size limits (
RAY_LIMIT_EXCEEDED), and no binding name it declares may be reserved for the operator (RAY_BINDING_RESERVED). - Write. An existing output is
RAY_OUTPUT_EXISTSunless--forceis given; a directory as the output, or an output directory that does not exist, isRAY_USAGE. The archive is written to a temporary file in the directory of the output, synced, read back through the bundle reader, compared file by file with the digests the closure was checked under (a file rewritten in between isRAY_USAGE), and only then linked to the output path, or renamed over it with--force. A refused or interrupted pack leaves neither the output nor a temporary file.
- Postgres: not needed, except with
--against, which creates and drops one throwaway database on the serverSHADOW_DATABASE_URLnames. Environment:SHADOW_DATABASE_URLwith--against, nothing otherwise; no.envis loaded. - Runs nothing. Handlers, extensions and frontends must be built first; pack reads modules with a lexer and never imports, evaluates or installs anything.
--build, which would run the build in a disposable sandbox, is not available yet: it is refused withRAY_USAGEnaming the manual build step, and it is not listed in--help. - Product delta.
--against <old-spec>carries, underpayload/migrations/, the delta from the stores of the spec the environment runs to this spec's, the--allowlistfile byte for byte, and in the manifest'sproductMigrationthe product schema digests before and after it and whether it is destructive. The target regenerates the delta from its product migration ledger and refuses any difference; see the packing guide. - Deterministic. The same prepared files and flags give the same bytes, wherever and whenever they are packed. Bundle paths are relative to the directory of the spec, and the archive carries no timestamp, user, host or absolute path.
- Flags:
--spec <path>and--output <file.ray>, both required (with--previewtoo, although nothing is written then);--id <application-id>(a lowercase letter, then up to 62 lowercase letters, digits or hyphens);--version <semver>(exact, no build metadata);--runtime <exact-version>(default: this CLI's version);--include <path>, repeatable, a file or directory relative to the spec;--source-maps(carry*.mapfiles and scripts or style sheets that inline their source map);--against <old-spec>(the spec the target environment runs);--allowlist <file.json>(the reviewed allowlist, with--againstonly);--preview;--force;--json. Output: the result envelope on stdout (operation
pack), with or without--json:{ "contractVersion": "1.0.0-rc.2", "ok": true, "operation": "pack", "operationId": "…", "data": { "outputPath": "/home/me/notes-1.4.0.ray", "preview": false, "sha256": "…", "size": 3874, "applicationId": "notes", "applicationVersion": "1.4.0", "runtimeVersion": "1.9.1", "target": { "os": "linux", "arch": "x64", "nodeMajor": 22 }, "requires": ["declarative-api", "declarative-stores", "static-frontend"], "bindings": [], "execution": "none", "egressHosts": [], "inclusion": [ { "path": "payload/THIRD-PARTY-NOTICES.txt", "size": 192, "sha256": "…", "source": "generated" }, { "path": "payload/rayspec.yaml", "size": 431, "sha256": "…", "source": "rayspec.yaml" }, { "path": "payload/sbom.cdx.json", "size": 203, "sha256": "…", "source": "generated" }, { "path": "payload/web/dist/index.html", "size": 612, "sha256": "…", "source": "web/dist/index.html" } ] }, "errors": [], "warnings": [] }outputPathis the absolute path written. With--preview,previewistrueandoutputPath,sha256andsizearenull. On a refusalokisfalseanddataisnull.bindingslists names, kinds and requiredness, never values. A spec that uses an agent backend but declares no egress hosts gets the warningRAY_W_EGRESS_UNDECLARED. On stderr: the operation id and, without--json, the inclusion summary — application, runtime and target, capabilities, binding names, execution level, egress hosts, file count and bytes, what was left out and why, warnings, and the output path and SHA-256 (--previewalso lists every file). The summary says that nothing was deployed; check the bundle withbundle verify.- Exit:
0written (or previewed),1spec invalid,2usage, identity, closure, limit or an existing output,3a@rayspec/*range that excludes the pinned runtime,4a secret or a reserved binding name,6interrupted,7internal error.
bundle inspect#
rayspec bundle inspect <file.ray> [--json]Reads a .ray application or migration bundle and reports what it is. It runs the structural checks of the bundle reader, in order, and stops at the first failure: the archive size, the ZIP container (the strict profile: stored entries, fixed header values, no ZIP64, comments, extra fields or data descriptors, and names that cannot escape the payload or collide), the ray.json manifest (its bytes, schema and semantics), and every entry streamed against the manifest's inventory (size, CRC-32 and SHA-256, under the extracted-byte limit). It does not check the runtime, target, capabilities, spec or signature — that is bundle verify.
- Postgres: not needed. Environment: none read (no
.envis loaded). - Passive: nothing in the archive is extracted, imported, evaluated or run, and nothing is written anywhere. A read has a wall-time budget of five minutes.
- Flags:
--jsononly; exactly one positional archive path. A path that is missing or is not a regular file (a directory, a device, a FIFO) isRAY_USAGE; a FIFO is refused at once, never waited on. Output: the result envelope on stdout (operation
bundle.inspect), with or without--json:{ "contractVersion": "1.0.0-rc.2", "ok": true, "operation": "bundle.inspect", "operationId": "…", "data": { "sha256": "20331da54f5c5b0911e1d9fe6dc4732b6ebd28448930d845b6a84e0188a9d194", "size": 1807, "entries": 5, "kind": "application", "applicationId": "format-fixture", "applicationVersion": "0.0.0-contract-fixture", "runtimeVersion": "0.0.0-contract-fixture", "target": { "arch": "x64", "nodeMajor": 22, "os": "linux" }, "requires": ["static-frontend"], "bindings": [], "execution": "none", "egressHosts": [], "signature": { "present": false, "verified": false, "publicKeySha256": null }, "verdict": "structurally-valid" }, "errors": [], "warnings": [] }bindingslists names, kinds and requiredness, never a value or a description.signature.presentsays whether a<file.ray>.siglies next to the archive; inspect does not check it. On a refused archiveokisfalse,dataisnull, anderrors[0]carries the code and reason, for exampleRAY_INVALID_ARCHIVE/dot-segment. A message never repeats a name or any other content from the archive. On stderr: the operation id and, without--json, a short description of the bundle — what it is and which checks passed, never a claim that its code is safe to run.- Exit:
0structurally valid,2a refused archive, manifest or inventory (or a usage error),6interrupted,7internal error.
bundle verify#
rayspec bundle verify <file.ray> [--runtime <exact-version>] [--signature <file.ray.sig>]
[--trusted-key <ed25519-public-key.pem>]... [--require-signature] [--json]Everything bundle inspect checks, then whether this runtime can deploy the bundle, in this order, stopping at the first failure:
- Runtime. The version the bundle pins equals the runtime checked against exactly: this CLI's own version, or the one
--runtimenames (MAJOR.MINOR.PATCHwith an optional pre-release; a range,latestor build metadata is a usage error).RAY_RUNTIME_UNSUPPORTED. - Target. The runtime supports
linux/x64/ Node 22 only.RAY_TARGET_UNSUPPORTED. - Capabilities, in the order the bundle lists them: an id the capability vocabulary does not know (
unknown-id), an id this runtime does not provide (not-provided), then the execution level (execution-level; no runtime providessandboxed).RAY_CAPABILITY_UNSUPPORTED. - Reserved bindings. A binding name reserved for the operator.
RAY_BINDING_RESERVED. - Spec. The spec file the manifest names is parsed from the archive (never run).
RAY_SPEC_INVALID, followed by each grammar error as aSPEC_code with its path. The message of each names the rule and, for a YAML error, the line and column; it never quotes the spec, whose text may hold a secret. - Derived fields.
requires, the execution level and the egress hosts must be exactly what the spec derives: the capability ids its sections use, in code-point order;in-processwhen it declares handlers or extensions, elsenone; and the egress hosts it declares (backenddeployment.egressHosts, productdeployment_overrides.egress_hosts), compared as a set, so a manifest that lists one more or one fewer is refused.RAY_MANIFEST_INVALIDwith reasonrequires-mismatch,execution-mismatchorpermissions-mismatch. - Secret scan. A payload file named
.env,.env.*,id_rsa,id_ecdsa,id_ed25519or.pgpass, or one that contains a PEM private-key header (-----BEGIN, words of uppercase letters and digits such asRSAorX25519, thenPRIVATE KEY-----).RAY_SECRET_DETECTED, naming the path and never the content. - Signature. When
--signaturenames a file, or<file.ray>.siglies next to the archive: the file must be a signature document for this archive's SHA-256, name one of the--trusted-keypublic keys, and verify with it.RAY_SIGNATURE_INVALIDwith reasonmalformed,mismatchoruntrusted-key(a signed bundle checked with no trusted key isuntrusted-key). With no signature,--require-signaturerefuses the bundle (malformed); otherwise it passes with the warningRAY_W_UNSIGNED.
A migration bundle gets the runtime, target and signature checks after the structural checks (so --require-signature and RAY_W_UNSIGNED apply to it too), but no capability, binding, spec or secret checks: its contents are encrypted and are not read.
- Postgres: not needed. Environment:
PATH,RAYSPEC_FFMPEG_BINandRAYSPEC_FFPROBE_BIN, for the media-tools warning below; nothing else. - Passive: as for inspect — nothing is extracted, imported or run, and nothing is written.
- Media tools. A bundle that requires
audio_inputormedia_playbackstitches its recordings withffmpegand checks them withffprobe. When either cannot be found on the host that runsverify— as a file the user may execute in a directory ofPATH, or at the pathRAYSPEC_FFMPEG_BIN/RAYSPEC_FFPROBE_BINnames — one line starting withwarning: media tools missingis written to stderr, with or without--json. It names the capabilities and what was looked for. Nothing is started to find out, so a tool that is present but broken is not noticed here. The envelope, itswarnings, the verdict and the exit code are the same with and without the line: the envelope's warning codes are a closed list of the bundle contract, which has no code for a host tool. Verify on the host that will serve the bundle for the line to mean anything; the runtime image carries both tools from 1.9.1. - Flags:
--runtime <exact-version>(default: this CLI's version);--signature <file.ray.sig>(default:<file.ray>.sigwhen present);--trusted-key <ed25519-public-key.pem>, repeatable — a PEM public key; a private key, an unreadable file, one that is not a regular file, one over 16 KiB or a non-Ed25519 key is a usage error;--require-signature;--json.bundle signwrites the signature file this checks. Output: the result envelope (operation
bundle.verify):{ "contractVersion": "1.0.0-rc.2", "ok": true, "operation": "bundle.verify", "operationId": "…", "data": { "sha256": "20331da54f5c5b0911e1d9fe6dc4732b6ebd28448930d845b6a84e0188a9d194", "kind": "application", "applicationId": "format-fixture", "applicationVersion": "0.0.0-contract-fixture", "runtimeVersion": "0.0.0-contract-fixture", "checkedAgainstRuntime": "0.0.0-contract-fixture", "signature": { "present": false, "verified": false, "publicKeySha256": null }, "verdict": "deployable" }, "errors": [], "warnings": [{ "code": "RAY_W_UNSIGNED", "message": "the bundle has no detached signature, so its origin is not established" }] }A failure after the structural checks keeps
data, withverdictnot-deployable; a structural failure hasdata: null. A verified signature reports the SHA-256 of the trusted key it verified with.deployablemeans every check above passed for this runtime; it establishes where the bundle came from only when a trusted signature verified, and it never vouches for the code the bundle carries.- Exit:
0deployable,1spec invalid,2a refused archive, manifest or derived field (or a usage error),3runtime, target or capability,4reserved binding, secret or signature,6interrupted,7internal error.
bundle sign#
rayspec bundle sign <file.ray> --key-file <ed25519-private-key.pem>
[--output <file.ray.sig>] [--force] [--json]Writes the detached Ed25519 signature of a bundle: a canonical JSON file naming the archive's SHA-256 and the SHA-256 of the signer's public key (DER SubjectPublicKeyInfo), with the signature over rayspec-ray-v1\nsha256:<archive SHA-256>\n. This is the file bundle verify and deploy check against --trusted-key. How to make a key, hand out its public half and what a signature proves: Signing a bundle.
In order, stopping at the first failure:
- Arguments. One archive path;
--key-fileis required. The signature path is--output, else<file.ray>.sig; it may not name the bundle or the key file — through another path either, such as a linked directory or a second hard link, which is checked again just before placement — and is at most 4,096 characters.RAY_USAGE. - Key file. Opened once, without following a link, and judged through that open file: a symbolic link, a file that is not regular, one not owned by you, or one group or others can read or write (
chmod 600;0400also passes) isRAY_BINDINGS_FILE_INSECURE; when such a file holds a public key, the message says so. A FIFO or other special file is refused at once, never waited on. A path with no file isRAY_USAGE. - Key. At most 16 KiB holding exactly one unencrypted Ed25519 private key in PEM form (
openssl genpkey -algorithm ed25519). A public key, an RSA, EC or other key, or an encrypted key isRAY_USAGE. A message names the flag and the path, never the file's content. - Bundle. The structural checks of
bundle inspect— the archive size, the container, the manifest and every entry against the inventory — and its SHA-256. Nothing in the archive is extracted, imported or run, and a refused archive is refused before anything is written, with the codeinspectreports (RAY_INVALID_ARCHIVE,RAY_LIMIT_EXCEEDED,RAY_MANIFEST_INVALID,RAY_DIGEST_MISMATCH). The runtime, capability, spec, secret-scan and signature checks ofbundle verifyare not run: verify the bundle too. - Signature. Written to a temporary file in the directory of the signature path, read back and verified against the public half of the key. One that does not verify is never placed (
RAY_INTERNAL). A missing directory, or one you cannot write, isRAY_USAGE. - Placement. Moved into place in one step: without
--forceit is refused when anything is at the signature path (RAY_OUTPUT_EXISTS; a directory there is named as one, and--forcedoes not replace a directory); with--forceit replaces the file, or a link without writing through it. Placement without--forcemakes a hard link, so on a file system without hard links (FAT, exFAT, some network mounts) it isRAY_USAGE: write the signature on another file system, or pass--force. A name too long for the file system isRAY_USAGE. The temporary file is removed whatever happens.
- Postgres: not needed. Environment: none read (no
.envis loaded). - Writes: the signature file (mode
0644, whatever the umask) and nothing else. - Flags:
--key-file <ed25519-private-key.pem>(required);--output <file.ray.sig>(default<file.ray>.sig);--force;--json. Output: the result envelope (operation
bundle.sign):{ "contractVersion": "1.0.0-rc.2", "ok": true, "operation": "bundle.sign", "operationId": "…", "data": { "bundleSha256": "20331da54f5c5b0911e1d9fe6dc4732b6ebd28448930d845b6a84e0188a9d194", "signaturePath": "app.ray.sig", "publicKeySha256": "03d6111f60bf5fc57c9b17beeb0dc25f4e94b4fa064ffbdef1936aa6739901c2" }, "errors": [], "warnings": [] }publicKeySha256is the valuebundle verifyreports for a signature it verified with that key. On a refusaldataisnull. On stderr: the operation id and, without--json, a short description — the bundle, the signature path, the public key's SHA-256 and thebundle verifycommand that checks it, with--signaturewhen the signature is not at<file.ray>.sig(deployreads only that name). No output carries key material. A signature establishes who signed the archive for whoever trusts that key; it does not vouch for the code the bundle carries.- Exit:
0signed and verified,2a usage error, a refused archive or an existing signature file,4a key file that is a link, not a regular file, not yours or open to others,6interrupted before the file was placed (nothing written),7internal error.
tenant ensure#
rayspec tenant ensure --org-id <uuid> --name <n> [--owner-email <e>] [--owner-invite-out <path>]
[--invite-ttl-seconds <n>] [--reissue-owner-invite]Idempotently creates or resolves the organization named by --org-id, so a product deployment's RAYSPEC_PRODUCT_TENANT_ID can be settled before anything is deployed. It talks to DATABASE_URL directly — no running server, and no HTTP route exists for it in any posture.
Run it twice with the same --org-id and you get the same organization and no second row. The chosen id is the operation id: orgs.id is a primary key, so the database itself is the ledger and two concurrent runs of the command converge rather than race — one reports created, the other existing, and both name the same organization. That holds against a fresh database too: the migration step below is serialized by a Postgres advisory lock, because the migrator's own CREATE … IF NOT EXISTS bootstrap is not concurrency-safe and would otherwise fail the loser before it ever reached the reservation. So the command is safe to call unconditionally from a deploy script that cannot know whether an earlier attempt got through.
- Postgres: yes, directly. It applies the committed migration chain to that database — required on a first bootstrap and idempotent afterwards, but it means pointing the command at an unexpected
DATABASE_URLmigrates that database. - Secrets:
DATABASE_URLandRAYSPEC_API_KEY_PEPPER, each also honouring its<VAR>_FILEvariant with the usual precedence and fail-closed behaviour (see the server package README). The pepper must be the same value the target deployment runs with, because it is what the invite token is hashed under.RAYSPEC_JWT_SIGNING_KEYis deliberately not read — the command mints no JWT. - Single-tenant mode: with
RAYSPEC_SINGLE_TENANT=true(the setting the server reads) the command still resolves the one organization idempotently, but refuses to create a second one withSINGLE_TENANT_LIMITand writes nothing. See Hosting in the hardened posture. - Flags:
--org-id <uuid>— required. The organization id to create or resolve. A malformed uuid is a usage error, refused before the database is opened. Letter case does not matter: the id is bound and reported as the database stores it (lower case), which is what a deployment compares against.--name <n>— required. The display name; the slug is derived from it the same way every other path derives one.--owner-email <e>— optional. Mint an owner invite for this address so a human can claim the organization. Omitted, the command only reserves the organization and writes no invite.--owner-invite-out <path>— required with--owner-email. Where the minted token is written: an exclusively-created, mode-600 file holding the token and nothing else. An existing path is refused, never overwritten. There is deliberately no flag that takes a token value — a secret passed as an argument lands in shell history and inps.--invite-ttl-seconds <n>— optional. Overrides the 1-hour operator default, clamped to the shipped 5-minute/30-day bounds.--reissue-owner-invite— optional. Revoke the outstanding owner invite and mint a replacement, in one transaction (for a token that was lost). Without it, a run that finds a live invite reports it and mints nothing.
Output — one JSON object, containing no secret material:
{ "ok": true, "command": "tenant ensure", "orgId": "<ORG_ID>", "name": "Acme", "slug": "acme", "org": "created", "ownerHandoff": { "status": "issued", "inviteId": "<INVITE_ID>", "email": "founder@example.com", "expiresAt": "2026-08-02T13:00:00.000Z", "tokenFile": "/run/secrets/owner.token" }, "acceptPath": "/v1/invites/accept", "errors": [] }orgiscreatedon the run that made the organization andexistingon every later one.ownerHandoff.statusis one ofnot_requested(no--owner-email),already_owned(the organization already has an owner — the command does not displace one),pending(an earlier run's invite is still live) orissued(this run minted one). The one gap inalready_owned: an invite that is being redeemed at that exact moment is consumed a statement before the membership is written, so a run landing in between sees neither and mints. That produces an additional owner invite, never a displaced owner.On a run that resolves an existing organization,
--nameis not applied: the stored name and slug are what comes back. The command creates or resolves; it does not rename.- Exit:
0on success;1on an operational failure (a missing secret, a soft-deleted id, an invite-out path that is taken, a migration chain that could not be applied — that one reportsMIGRATION_FAILEDand creates nothing, and one that waited longer than 60 seconds for the shared schema lock a booting server or another migration held reportsSCHEMA_LOCK_TIMEOUT, creates nothing and can simply be run again; on an environment quiesced by the runtime's source fence it reportsENVIRONMENT_FENCEDand creates, resolves and migrates nothing until the fence is released; a migration chain the runtime refused for another reason reportsMIGRATION_REFUSED; a second organization under single-tenant mode reportsSINGLE_TENANT_LIMIT);2on a usage error.
The owner handoff, and why it creates no user#
The command creates no platform user and no membership. What it writes, in the same transaction as the organization row, is one owner invite authored by nobody (created_by IS NULL). A real person then redeems it at the ordinary public POST /v1/invites/accept — which provisions their account with their password and attaches the owner membership. Nothing temporary is left behind, which is the property the older bootstrap dance could not offer: a user cannot be removed once created (the last owner cannot be removed, and a user delete is a soft delete that leaves a row).
Between the two steps the organization has zero members. Nothing can act in that window, but the product boot gate checks only that the organization exists and is not soft-deleted, so a reserved organization is bootable before it is claimed.
# noteThe token in
--owner-invite-outis a tenant-takeover credential until it is consumed or expires.POST /v1/invites/acceptlets any holder provision the target account with a password of their choosing when that address has no account yet — so whoever can read that file owns the organization. The exclusive-create mode-600 write and the short default lifetime bound the exposure; they do not remove it. Delete the file once the invite is redeemed.
Note also what the command does not check. The data-integrity rules are the same code the HTTP surface runs — the tenant predicate, email normalization, the role, the TTL clamp, the single-flight on orgs.id. The authorization check is absent, because there is no principal: the command's authority is possession of DATABASE_URL and RAYSPEC_API_KEY_PEPPER.
The one-step production order#
# 0. Settle the id first — this one does not exist yet; step 1 creates it.
ORG_ID=$(uuidgen)
# 1. Create the organization and mint the owner handoff. No server needed.
rayspec tenant ensure --org-id "$ORG_ID" --name "Acme" \
--owner-email founder@example.com --owner-invite-out ./owner.token
# 2. Hand ./owner.token to the founder, who redeems it:
# POST /v1/invites/accept {"token": "<contents>", "password": "…"}
# …then delete the file.
# 3. Deploy the product against the id.
RAYSPEC_PRODUCT_TENANT_ID="$ORG_ID" rayspec deploy path/to/product.yamlSteps 1 and 3 can run against the same DATABASE_URL with no server in between, and step 1 is safe to re-run. RAYSPEC_TENANT_BOOTSTRAP_ENABLED stays unset throughout — POST /v1/auth/bootstrap-tenant is never registered on the deployment at all.
tenant recover-owner#
rayspec tenant recover-owner --email <address> [--org-id <uuid>] [--ttl-seconds <n>]Issues a one-time owner-recovery token for an active owner who holds no password — an owner whose only credential was an API key, which a new API-key pepper breaks (after an import, for example). The owner redeems it once over HTTP, sets a password and is signed in. The operator's authority is the database and the deployment's pepper; no running server is needed to issue, and the command mounts no route.
- Postgres: yes, directly —
RAYSPEC_MIGRATION_DATABASE_URLwhen set, elseDATABASE_URL. It runs no migration. - Secrets:
DATABASE_URLandRAYSPEC_API_KEY_PEPPER, each also honouring its<VAR>_FILEvariant. The pepper must be the one the deployment runs with: the token is stored as its HMAC under it, and a token hashed under another pepper never redeems. - What it writes, in one transaction: one
owner_recovery_tokensrow (the HMAC, the owner, the expiry), the replacement of any token still outstanding for that owner, and anowner_recovery_issuedrow inauth_audit(who and until when, not the token). - Refusals (
ok: false, exit 1, nothing written):NO_SUCH_OWNER(no active owner with that address),AMBIGUOUS_ORGANIZATION(the account owns more than one; pass--org-id),PASSWORD_PRESENT(the owner signs in with their password),ENVIRONMENT_FENCED(an exported source, or an import target before its cutover),INVALID_EMAIL,SECRETS_MISSING,RECOVERY_FAILED(the database could not be reached). - Flags:
--email <address>— required. The owner to recover.--org-id <uuid>— the organization, when the account owns more than one.--ttl-seconds <n>— the token's lifetime; default 1800 (30 minutes), clamped to 5 minutes – 24 hours.
Output: ONE JSON object on stdout, the only place the token ever appears:
{ "ok": true, "command": "tenant recover-owner", "orgId": "…", "userId": "…", "recoveryId": "…", "expiresAt": "2026-10-01T10:30:00.000Z", "replaced": 0, "recoveryToken": "…", "redeemPath": "/v1/auth/owner-recovery", "errors": [] }Do not capture it in a log; hand the token to the owner over a channel you trust.
--jsonis not available for this command (the result envelope has no operation for it): with--jsonit refuses with exit 2 and prints nothing on stdout.- Redeeming:
POST /v1/auth/owner-recoverywith{"token": "…", "password": "…"}(anddeliverRefreshTokenInBodyas for login). Unauthenticated and rate-limited per source (owner-recovery, 10 a minute). One transaction checks the token is unexpired, unused and not replaced and that the account is still an active owner without a password, consumes it, sets the password and ends any session the account had; the answer is a signed-in owner ({accessToken, tokenType, expiresIn, activeOrgId, userId, role: "owner"}, the refresh secret in the cookie). Every token that does not redeem — unknown, expired, used, replaced — answers the same400. The redemption is audited asowner_recovery_redeemedand the session'slogin. - Exit:
0issued,1refused,2usage.
dev gen-secrets#
rayspec dev gen-secrets [--out <path>]Mints the three platform boot secrets into a .env file and chmod 600s it. Mutating, local-dev only.
The three secrets are minted on distinct cryptographic chains: an RS256 JWT/OIDC signing key (a PKCS#8 PEM), an API-key pepper, and a distinct media-signing key. It is idempotent: a key already present in the target file is left untouched (only missing keys are appended), and it never echoes a secret value — the output reports only which keys were written vs. already present.
- Postgres: not needed.
- Flags:
--out <path>— optional target file, default./.env. Output:
{ "ok": true, "command": "dev gen-secrets", "out": ".env", "mode": "600", "keys": { "RAYSPEC_JWT_SIGNING_KEY": "written", "RAYSPEC_API_KEY_PEPPER": "written", "RAYSPEC_MEDIA_SIGNING_KEY": "already-present" }, "errors": [] }
dev db#
rayspec dev db [--database-url <url>] [--name <db>]
rayspec dev db --reset --yes [--database-url <url>] [--name <db>]By default, creates the local dev database if it is absent — idempotent and never destructive (a second run is a no-op; it never drops or alters an existing database). It connects to the maintenance database on the same host and issues a single CREATE DATABASE. The database name is validated against a strict identifier pattern before use, since CREATE DATABASE cannot be parameterized.
With --reset --yes it instead DROPs and re-CREATEs a clean, empty database (and drops the sibling <name>_dbos_sys durable-worker system database), so you can wipe a corrupt or stale dev DB in one command. Because it destroys data it is gated on an explicit --yes: --reset without --yes refuses and touches nothing (the guard fires before any DB connection). Local-dev only.
- Postgres: required (reachable on the host in the base URL).
- Flags:
--database-url <url>— optional base URL; defaults toDATABASE_URL.--name <db>— optional target name; defaults to the database named in the base URL.--reset— DROP + re-CREATE a clean database (destructive). Requires--yes.--yes— confirm the destructive--reset.
Output (value-free — the connection string is never echoed; any stray URL in an error message is redacted):
{ "ok": true, "command": "dev db", "db": "rayspec", "created": true, "errors": [] }createdistruewhen freshly created,falseon the idempotent no-op path; a--reset --yesrun reports"created": true, "reset": true.
dev bootstrap-tenant#
rayspec dev bootstrap-tenant --base-url <url> [--email <e>] [--password <p>] [--org-name <n>]
[--org-id <uuid>]Creates the first tenant and owner against a running RaySpec backend — it is a pure HTTP client of the shipped auth API. It registers a user (which auto-creates the organization and owner membership), then switches into that org to obtain an org-scoped token.
- Postgres: not directly — it talks to a running server (which needs its own database).
- Flags:
--base-url <url>— required. The running backend's base URL.--email— optional; defaults toowner-<epoch-ms>@rayspec.local, a fresh address on every run, so a repeat never collides with the user the previous run registered. Pin it only if you want a predictable owner — a second run with the same address is a409and the command reportsREGISTER_FAILED.--password— optional; defaults to the literalcorrect-horse-battery-staple-9. It is a development default, not a secret: it is the same on every machine, so pass--passwordyourself whenever the account is meant to outlive the walkthrough. Whatever value is used is the onePOST /v1/auth/loginwill want later — this command never prints it back.--org-name— optional; defaults toMy Workspace.--org-id <uuid>— optional. Create the organization under this id instead of a server-generated one, so you can put the id inRAYSPEC_PRODUCT_TENANT_IDbefore the product deployment exists. Requires the target server to be running withRAYSPEC_TENANT_BOOTSTRAP_ENABLED=true(see below); against a server without it the request is a plain404and the command reportsREGISTER_FAILED. A malformed uuid is a usage error, refused before any request is made. An id that is already taken is a409.
Output (the
orgTokenis the command's deliberate credential output — an org-scoped token you need for tenant routes):{ "ok": true, "command": "dev bootstrap-tenant", "orgId": "<ORG_ID>", "orgToken": "<ORG_TOKEN>", "email": "owner@example.com", "errors": [] }- Exit:
0on success;1on an HTTP/network failure or unexpected response.
Choosing the org id: the operator gate, and why it exists#
POST /v1/auth/register is public and unauthenticated, and it will never accept a client-chosen org id: ids stay server-generated and unguessable there. That unguessability is load-bearing, because a product deployment binds itself to one org id. If any public caller could name the id, somebody who learned the id you intend to deploy against could create that organization first, with themselves as owner, and your deployment would come up bound to an organization they control.
So the chosen-id path is a separate route (POST /v1/auth/bootstrap-tenant) that a server only registers when it was started with RAYSPEC_TENANT_BOOTSTRAP_ENABLED=true. On any other deployment that path does not exist at all — there is no gate to guess at and no collision reply to read as an existence oracle. Turn the variable on for the bootstrap boot, and off again for the deployment.
The local-dev order for a product deployment#
A product deployment refuses to boot when RAYSPEC_PRODUCT_TENANT_ID is malformed or names no live organization, and — because deploy serves the auth surface itself — it therefore cannot create its own tenant. Bootstrap first, deploy second.
In production, use tenant ensure: it does the same thing in one step, against DATABASE_URL directly, without a server and without ever registering POST /v1/auth/bootstrap-tenant. The walkthrough below is the local-dev route through a running server, and stays fully supported:
# 0. Settle the id first — this one does not exist yet; step 2 creates it.
ORG_ID=$(uuidgen)
# 1. Boot the auth surface alone, with the bootstrap gate on. No spec, no product.
# This runs in the foreground, so give steps 2-3 a second shell.
RAYSPEC_TENANT_BOOTSTRAP_ENABLED=true rayspec-serve
# 2. Create the tenant under the id you chose.
rayspec dev bootstrap-tenant --base-url http://127.0.0.1:8080 --org-id "$ORG_ID"
# 3. Stop that server. Deploy the product against the id — gate off.
RAYSPEC_PRODUCT_TENANT_ID="$ORG_ID" rayspec deploy path/to/product.yamlStep 0 is the one case where generating a fresh UUID is right: the id is created in step 2. Everywhere else RAYSPEC_PRODUCT_TENANT_ID must name an organization that already exists — a random id names none, and the boot check refuses it.
Against an existing organization, skip steps 1–2 entirely and set RAYSPEC_PRODUCT_TENANT_ID to that organization's id.
deploy — boot and serve a declared product#
rayspec deploy <spec.yaml> [--port <n>] [--host <addr>]
rayspec deploy <spec.yaml> --apply-migration <delta.sql> [--allowlist <file.json>]
[--port <n>] [--host <addr>]
rayspec deploy --dry-run <spec.yaml>
rayspec deploy --check-env <spec.yaml>A file that starts with a ZIP signature or whose name ends in .ray is an application bundle and takes the bundle path instead — see Deploying a bundle below. The check reads at most four bytes, before any configuration is loaded; every other file is a spec and is deployed exactly as described here.
Production-mutating. deploy boots the platform from the ambient environment, mounts the declared product's routes, and serves it on PORT (default 8080) until SIGINT / SIGTERM — the GitOps-from-one-file path. It reads the same fail-closed environment as rayspec-serve (it sets RAYSPEC_SPEC_PATH from the positional for you) and registers the product's stores through the sanctioned, validating registration path (every store's tenant predicate is checked before it joins the deny-by-default chokepoint).
deploy is mount-only against an existing schema. On a clean database it materializes the declared stores; on an up-to-date one it mounts them unchanged. It does not derive and apply a schema change on its own: if the live schema has drifted from the spec, the boot fails closed rather than altering it. A schema change is applied by the explicit --apply-migration flag below.
--dry-runis a one-shot, DB-free, network-free check: it validates the document with the grammar of the profile it boots, and — for a product document — composes it against the wired runtime, emitting a JSON verdict. It does not prove the migration, boot-env sufficiency, any provider credential, live-schema drift, or that the app serves. Exit0if the document passes its profile's check,1otherwise.rayspec deploy --dry-run examples/acme-notes/acme-notes.product.yamlEach of the three profiles
deployboots is answered on its own terms, so the verdict never reports one profile's document in another's vocabulary and a caller gating onokneeds to know nothing about which ruleset applied:Document ok: truepayloadJudged by product (carries product:)composed— the product id and the store / view-route / trigger-event / workflow names it composes tothe product grammar + a stubbed compose backend ( rayspec, noproduct:)backendProfile— the profile named, plus the declaredstores,routes(METHOD /path),agents,handlersand (when the document declares any)frontendMountsthe same parser doctorandplanusefrontend-only (static) staticProfile— the profile named, thefrontendMountsthat boot would serve, and the statement that no database is touched, no migration applies, and there is nothing to composethe same detection the static boot branches on A backend document declares its routes and handlers rather than lowering to them, so there is nothing to compose: the check is the validation
doctorruns, and the payload is declared names only — no SQL, nothing derived. It covers the sectionsplanalso projects (stores,routes,agents) plus the declared handler ids, but it is notplan's payload:planpublishes no handlers, and its stores and routes are richer objects (column and FK counts,{method, path, action}).ok: truemeans the document validates, not that it boots:notProvencarries the shared boundary plus this profile's boot refusals — astreamroute with no blob backend configured, a declared handler module that does not resolve as compiled JavaScript under the jailed root, theSTT_PROVIDER/TTS_PROVIDERcredentials demanded at boot, and any declared frontend mount whose directory does not hold servable built assets (this profile boots the full platform, which refuses an unservable mount fail-closed — see spec-reference →frontend; the mounts themselves are echoed infrontendMounts, so the verdict names what boot will check). A document the backend grammar rejects reports its own violations (adangling_ref, an unknown key) — the same errorsdoctorreports for it.A frontend-only document has nothing to compose either, and what its check does not prove narrows instead: it reads only the document, so it says nothing about whether the declared directories hold built assets, or that the app serves.
--check-envis the other one-shot, DB-free, network-free check: the environment variables this document's boot will require, each with its<VAR>_FILEequivalent where it has one, why it is required, and whether it is currently set. Exit0when every demand is met and no refusal is already visible,1otherwise —missinglists the unmet demands, anderrorsnames a refusal that is not an unset variable (a document that does not validate, an agent selecting a backend that is not wired, anstt.*step declared without the audio capability, an unrecognisedRAYSPEC_ANTHROPIC_REUSE_LOGINon a document that selects theanthropicbackend). It is the answer a refuseddeployused to be the only way to get, and that answer is not cheap: the demands a declaredstreamroute, playback route orcrontrigger raise are reached only after the boot has opened the database and applied the whole committed migration chain.rayspec deploy --check-env ./rayspec.yamlIt reads the document and the environment, and it needs both — some demands have no document signal at all. On a backend document, setting
STT_PROVIDER=deepgrammakesDEEPGRAM_API_KEYrequired andTTS_PROVIDER=openaimakesOPENAI_API_KEYrequired, whatever that document declares — the two speech capabilities are wired from the environment alone. (It is a backend-document law: a product document readsSTT_PROVIDERon its own terms below and never readsTTS_PROVIDERat all, and a frontend-only one reads neither.) A provider selector is never itself an unconditional demand: on a backend document, leaving either unset means that capability is simply absent, which is not a boot error, so both are reported underoptionalsaying exactly that; on a product documentSTT_PROVIDERis demanded, but only when the document declares anstt.*step alongside the audio capability — a document that declaresstt.*without audio is refused on its shape, before the boot reads the selector at all, and the verdict reports that refusal instead of a demand no value would satisfy. In neither case does a credential become a demand before a provider has been selected. Each profile is answered on its own terms — a frontend-only (static) document is told it needs none of the three platform secrets, and a product document getsRAYSPEC_PRODUCT_TENANT_IDplus the capability-conditional demands its own declarations raise.A product document also lists, under
optional, the settings of a run without provider keys, each where the boot reads it:RAYSPEC_STT_FAKE_FIXTURESandRAYSPEC_STT_FAKE_FALLBACKwhen the document declares anstt.*step alongside the audio capability, andRAYSPEC_EXTRACTION_DETERMINISTIC_STAND_INwhen it declares extractors. They are never demands, sorequiredandmissingdo not move with them, and they are reported by presence alone: a fixture directory that is not one, an unsupported value, a fake-adapter setting besideSTT_PROVIDER=deepgramor the stand-in underRAYSPEC_EXTRACTION_MODE=livestill refuses the boot. See fixtures for the fake speech-to-text adapter and standing in for a configured backend.The demands are not re-derived by the CLI: they come from the same records
@rayspec/servercomposes its boot refusals from, so a demand the boot raises is a demand this prints.It generalizes a surface that already existed for exactly one variable.
doctorraises acron_tenant_requiredadvisory for every declaredcron/manualtrigger, namingRAYSPEC_CRON_TENANT_ID— and it can only be an advisory, because the lint pass is pure over the document and cannot read an environment.--check-envsays the same thing about the same trigger and reports whether the variable is set; both statements stay true, and the advisory is unchanged.What it deliberately does not do is in the verdict's
notChecked, not left to inference. It opens no socket, no database and no credential, and it loads no extension — running extension code is what would break that promise — so every demand an extension changes is invisible here. It runs in both directions: an extension-supplied blob backend removes theRAYSPEC_BLOB_ROOTdemand, while an extension-contributedapiroute adds theRAYSPEC_BLOB_ROOTdemand (anykind: stream) and theRAYSPEC_MEDIA_SIGNING_KEYdemand (mode: playback), and a extension-contributed agent adds its backend's credential demand. The boot guards ask their questions of the post-merge document; this reads the base one — so a document whose whole route surface arrives from an extension (thestream-backendexample is exactly that shape) reports the three unconditional secrets and nothing more. To keep that from reading as a clean bill of health, the verdict names the extensions the document declares — parsed offextensions[], never loaded. A set<VAR>_FILEmount counts as set from the variable alone: the file is never opened, so a missing, unreadable or empty secret file still refuses the boot. And no value is validated — a malformed PKCS#8 PEM, a non-UUIDRAYSPEC_CRON_TENANT_IDor a media key under 32 bytes is reported as set and still refuses. A value is read only where it decides which demands apply: a selectedSTT_PROVIDER/TTS_PROVIDER, andRAYSPEC_ANTHROPIC_REUSE_LOGIN, whose unrecognised value is reported because it decides whether the anthropic token demand exists at all. No environment value is ever printed; every variable is asetboolean and the one refusal about a value names the variable without quoting it. The verdict also names the.envfiles the CLI's loader searched (searchedDotenv), which is usually the answer to a disputed "unset". It is rejected with--dry-run(each emits its own verdict) and with--apply-migration/--allowlist(it opens no database, so a delta handed to it would be dropped).--apply-migration <delta.sql>applies a reviewed forward migration in place before serving — the supported path for evolving an existing deployment's schema (author the delta withplan --against). It reaches the same gated migration engineplanpreviews: a destructive statement without a covering reviewed--allowlist <file.json>entry is blocked. It is reboot-safe — the boot classifies the live schema first and mounts a present-matching schema instead of re-applying a non-idempotent delta, so aRestart=alwaysunit applies the delta once and mounts thereafter (still, drop the flag once it lands to keep intent explicit). It is rejected with--dry-run(a dry-run touches no database) and against a frontend-only spec (the static profile below touches no database either), and a bare--allowlistwithout--apply-migrationis refused (it would be silently ignored). Both file paths are jailed exactly like the spec path.--host <addr>sets the interface the serve path binds, by writingRAYSPEC_HOST— a value passed here overrides an ambient one, exactly as--portoverridesPORT. Unset, blank or whitespace-only means loopback (127.0.0.1), so a deployment is not reachable off-box until an operator names another interface (--host 0.0.0.0binds all of them); the boot banner reports the address actually bound rather than a fixed loopback string. It is a serve-path flag:--dry-runand--check-envanswer without binding anything, so a--hostpassed alongside either is accepted and ignored — unlike--apply-migration/--allowlist, which those two modes refuse outright. It moves the listen address only. The OIDC issuer still defaults tohttp://127.0.0.1:<port>/oidc, so a deployment bound to0.0.0.0keeps emitting loopback OIDC URLs untilOIDC_ISSUERnames the address its clients reach it on.- Postgres: required for the serve path (it applies the committed platform migration chain and materializes/mounts stores).
--dry-runtouches no database, and neither does a frontend-only spec — see the static-profile bullet below. - Frontend-only (static profile). A document that declares only a
frontendboots the static profile, the same branchrayspec-servetakes and entered before any secret is read: no database, none of the three boot secrets, and no auth / OIDC / run route mounted (/healthcarries nodbfield — it reports the mounts' readiness asfrontend), with theContent-Security-PolicyandPermissions-Policydefaults emitted by the app itself. Because it touches no database it applies no migration, so--apply-migration/--allowlistagainst such a document are refused as a usage error (exit2) rather than silently ignored.--dry-runreports this profile and the mounts it would serve (ok: true, exit0) instead of a compose verdict — the same detection the boot branches on, so the check and the boot cannot disagree. See getting-started → a frontend-only (static) deployment. - Flags:
--port <n>overridesPORT(serve path);--host <addr>overridesRAYSPEC_HOSTand moves the bind off the loopback default (serve path);--dry-runselects the one-shot compose check;--check-envselects the one-shot boot-environment check;--apply-migration <delta.sql>applies a reviewed forward migration;--allowlist <file.json>(requires--apply-migration) covers reviewed destructive statements in that delta. - Exit: the serve path stays up until a signal; a fail-closed boot error (a missing secret, an unreviewed destructive migration) prints an actionable message and exits
1. Every schema change the boot makes runs as aruntime.applyoperation with receipts, and a refusal of one exits with its contract class:3a plan made stale by a concurrent change,4a fenced environment,5another operation holding the lease past the wait,6an interrupted earlier apply that needs manual reconciliation. See Runtime operations. Profiles — declaration vs. custom code.
deployruns a product-profile document (likeexamples/acme-notes/acme-notes.product.yaml) directly — it is pure declaration with no custom code and no build step. A backend-profile document may ship custom escape-hatch handler modules (and an extension is authored the same way); the runtime loads them as compiled JavaScript only — it fail-closed-rejects a.tsmodule path at roll-out, deterministically (this does not rely on the Node version, even where Node transparently type-strips.ts):handler '…': module '…/handlers/….ts' is TypeScript source ('.ts') — production loads compiled JavaScript only. Compile it to JavaScript first …Compile such handlers to
.jsfirst and deploy the compiled artifact — the deploy runtime ships no turnkey.tsloader. The bundled examples ship a build step (build.mjs):examples/acme-notes-backendemits a deploy-readydist/rayspec.yaml, andexamples/stream-backendcompiles its extension. An extension additionally resolves@rayspec/platformat load starting from its own compiled entry's location, so ship the extension directory to the deploy target with its installednode_modules— that is what pins the platform build it runs against. An application bundle written bypackis the exception: it leaves@rayspec/*out of the extension's files, because the runtime that deploys the bundle provides them. See spec-reference →extensionsfor the section grammar and getting-started → the backend profile for the walkthrough. (gen-handlerscaffolds a handler;doctorvalidates the spec.)- Database state. The serve path applies the committed platform migration chain to
DATABASE_URL(idempotent — it bootstraps a clean database and no-ops on an up-to-date one), then materializes the declared stores on a clean database or mounts them when they already match — so it expects a clean or fully-migrated database. A half-provisioned database — for example one where the migration bookkeeping exists but the chain was only partly applied — makes boot fail with a raw migration error. If boot fails this way, deploy against a fresh, empty database:rayspec dev db --reset --yesDROPs and re-CREATEs a clean one, orrayspec dev db --name <fresh>creates a separate empty database; then pointDATABASE_URLat it. A store schema change against an already-materialized database is not applied by a plaindeploy— a drifted schema fails closed; apply the change with--apply-migrationabove.
Deploying a bundle#
rayspec deploy <file.ray> --dry-run [--bindings-file <file>] [--state-dir <dir>]
[--trusted-key <ed25519-public-key.pem>]... [--require-signature] [--json]
rayspec deploy <file.ray> [--bindings-file <file>] [--plan-digest <sha256>] [--state-dir <dir>]
[--port <n>] [--host <addr>] [--trusted-key <ed25519-public-key.pem>]...
[--require-signature] [--json]Production-mutating (without --dry-run). Deploys an application bundle written by pack on an explicitly configured self-hosted target and serves it. The walkthrough — inspect, bind, review, apply, readiness, update, recovery — is Deploying a bundle on your own server.
- Configuration comes from the explicit process environment only. No
.envfile is loaded on this path, whateverRAYSPEC_SKIP_DOTENVsays.DATABASE_URLandRAYSPEC_API_KEY_PEPPER(or their_FILEvariants) are required for a dry-run; a deploy also needs everything the boot needs (RAYSPEC_JWT_SIGNING_KEY, …).SHADOW_DATABASE_URLnames the server where a plan with a schema change computes the head after it, on a throwaway database. A missing variable is refused withRAY_USAGE, naming it. --bindings-file <file>— the application's binding values, JSON{"bindingsFormatVersion": 1, "bindings": [{"name", "value"}]}. A regular file, not a link, owned by you, mode 0600 or stricter (RAY_BINDINGS_FILE_INSECUREotherwise); a reserved operator name (DATABASE_URL,RAYSPEC_…,NODE_…, a provider key's_FILEvariant, …) is refused withRAY_BINDING_RESERVED. A name the bundle does not declare is refused withRAY_USAGE, except the key of the speech provider the operator selected (DEEPGRAM_API_KEYwithSTT_PROVIDER=deepgram,OPENAI_API_KEYwithTTS_PROVIDER=openai); so is a provider key the environment also names a_FILEfor. Bindings come only from this file and the process environment (a provider key also from its<NAME>_FILE). No value is put into the process environment: provider keys go to the adapters that use them, the application's own names to its handlers asinit.bindings. Values never appear in output, logs, plans or receipts; plans carry revision ids. A bundle whose extraction config names a model backend declares that backend's key as a required binding, and the plan blocks without it (RAY_BINDING_MISSING). That holds for a run without provider keys too (RAYSPEC_EXTRACTION_DETERMINISTIC_STAND_IN=true, see standing in for a configured backend): give the binding any placeholder value there, since nothing reads it.--dry-run— plan only: the bundle is read and verified by the one bundle reader (nothing is extracted or run), then planned against the live database. Prints the plan — required bindings, schema impact, permission changes, storage, blockers, warnings — withplanDigest,preparedAtandexpiresAt(30 minutes later), and writes the plan record<state-dir>/plans/<planDigest>.json. No SQL changes anything. A plan with blockers is stillok: true; the deploy refuses it. When the bundle requiresaudio_inputormedia_playbackandffmpegorffprobecannot be found on this host, the dry-run writes thewarning: media tools missingline ofbundle verifyto stderr as soon as the bundle is read, with or without--jsonand whatever the plan then says; the plan, its warnings and the exit code do not change. The deploy itself does not refuse over it: it serves, and stitching a recording then fails closed, so the recording is neither transcribed nor playable.--plan-digest <sha256>— the plan to deploy, as a dry-run printed it. Required when the plan changes the schema or the grants (a first deploy always does). The plan is recomputed at its ownpreparedAt; a missing record, another bundle, an expired plan or any covered input that changed since (a binding value, the schema, the environment revision) isRAY_PLAN_STALE.--state-dir <dir>— the deployment state directory (default.rayspec-state): mode 0700, owned by you, holding one deployment —deployment.json,active.json, the read-only version directoriesversions/<bundleSha256>/and the plan records.--trusted-key,--require-signature— as forbundle verify: an unsigned bundle is accepted withRAY_W_UNSIGNEDunless a signature is required.--port,--host— where the deployment serves, as for a spec deploy.
Order. Nothing opens the database until the arguments, the bindings file, the trusted keys, the state directory, the bundle (every reader check) and the bindings file's names have been checked. Nothing changes the database until the plan is accepted and the boot has validated the signing key, the spec and the rest of its preflight. The bundle is extracted into its version directory and verified before the boot; the apply then runs the platform chain, the product change and the switch of active.json, each with a receipt, under the operation lease and the shared schema lock. A deploy that fails leaves the previous version active and reverses no schema change; the refusal says how to finish it. The application is served from the active version directory, with @rayspec/* resolved from the installed runtime and every other package from the bundle.
Output. One result envelope on stdout, with or without --json: deploy.dry-run with {bundleSha256, plan, planDigest, environmentRevision, preparedAt, expiresAt, planRecordPath}, or deploy with {bundleSha256, deploymentId, planDigest, environmentRevision, status} — written when the deploy refuses (status: refused) or, once it serves, when it stops (status: stopped). The operation id, the boot banner and, without --json, a summary of the plan go to stderr, and so does anything else printed while the deploy runs (the durable runtime's startup lines, a handler's console.log), so stdout holds the one envelope. After a deploy that changed the product schema the banner's Product DB line names the product migration ledger row that change wrote. A .ray path that cannot be opened is refused as RAY_USAGE, in the words rayspec bundle verify uses.
Exit codes. 0 a dry-run that planned, or a deployment that stopped on SIGINT/SIGTERM · 1 the boot refused its configuration after the plan was accepted (RAY_CHECK_FAILED, with the boot's message; nothing was applied) · 2 usage, an invalid archive, a digest mismatch or a missing binding · 3 runtime, target or capability not supported, a stale plan, a schema change the plan does not approve · 4 a signature, reserved binding, insecure file or policy refusal · 5 the environment is busy (RAY_LOCK_TIMEOUT) or the database is unavailable (both retryable) · 6 drift, an interrupted deploy, or reconciliation required · 7 an internal error.
export#
rayspec export --deployment <id> --recipient <age1...> --output <migration.ray>
--run-history <included|excluded> [--confirm-quiesce] [--source-stopped]
[--quiesce-deadline <seconds>] [--state-dir <dir>] [--json]Writes the deployment's complete snapshot — the deployed application, the application database, the workflow system database (whole, when it exists) and every blob — as one migration bundle encrypted with age to the X25519 recipient, and leaves the source fenced. The operator guide is Exporting a deployment.
- Order. A read-only precheck of the source; the operator's confirmation of the downtime; the fence (
quiesce: writes, uploads, triggers and the run queue stopped, runs drained) with a database write barrier; the capture of both databases and the blobs under that one fence epoch, counts and digests verified; encryption in a private scratch directory under the state directory; the bundle written to--output, read back and linked into place; the scratch directory removed. Each step is a transition recorded in the receipts (below). - Flags.
--deployment <id>(required): thedeploymentIdof the state directory; it must also be the one the database records, elseRAY_USAGE.--recipient <age1...>(required): the age X25519 recipient. A passphrase, an identity and the post-quantum or tag recipients are refused (RAY_USAGE).--output <file>(required): refused if it exists (RAY_OUTPUT_EXISTS). Written with mode 0600. Plaintext is never written there or anywhere outside the scratch directory.--run-history <included|excluded>(required, no default): whether runs, run events, journals, conversation items and workflow runs leave the source.--confirm-quiesce: confirms the downtime. Required with--jsonor without a terminal; otherwise the plan is printed on the terminal andyesis asked for.--source-stopped: the operator attests that every runtime process is stopped. The database barrier without role separation; the export checks that no other session is connected.--quiesce-deadline <seconds>: how long runs in flight are drained (default 300, at most 86400).--state-dir <dir>: the deployment state directory (default.rayspec-state).
- Environment (explicit, never a
.envfile):DATABASE_URL(or_FILE),RAYSPEC_MIGRATION_DATABASE_URL(or_FILE; role separation),RAYSPEC_SNAPSHOT_DATABASE_URL(or_FILE; the read-only snapshot role),DBOS_SYSTEM_DATABASE_URL,RAYSPEC_BLOB_ROOT,RAYSPEC_PG_DUMP(an absolute path; default the firstpg_dumponPATH, which must be of the server's major). No output carries a value. - Database barrier. With role separation the runtime role's writes are revoked until
resume(database-write-role); without it, only a stopped source attested with--source-stopped(database-stopped-source). With neither, no barrier can hold, and the export refuses at the precheck, before the fence, withRAY_EXTERNAL_STATE_UNSUPPORTED/database-barrier-unavailable; nothing at the source changes (see Export → Compatibility notes). A barrier that could hold and does not (the role's writes not revoked, a session still connected to an attested stopped source) is refused after the fence, and the source stays fenced. - Blobs. The fs blob store under
RAYSPEC_BLOB_ROOT. For an application that loads extensions, the blob backend its boot recorded decides, read from the database and never by loading the extensions: a backend an extension provides, or no record for the active version, is refused before the fence (RAY_EXTERNAL_STATE_UNSUPPORTED/unsupported-blob-adapter, naming the extension); see Applications with extensions. - A second export while fenced reuses the fence at its epoch.
Output: the result envelope on stdout (operation
export), with or without--json:{ "contractVersion": "1.0.0-rc.2", "ok": true, "operation": "export", "operationId": "…", "data": { "deploymentId": "3f9c0a1b2c3d4e5f", "outputPath": "/srv/handover/app-migration.ray", "sha256": "…", "ciphertextSha256": "…", "ciphertextSize": 48213374, "fenceEpoch": 4, "sourceState": "fenced", "excludedDataCategories": ["credential-state", "request-replay-state", "runtime-control-state", "security-audit-log"], "recovery": "The source stays fenced at epoch 4 (database barrier database-write-role held, database-stopped-source not-applied, object-writes held; snapshot read as snapshot-role). …" }, "errors": [], "warnings": [] }recoverynames the barriers that held and did not apply, who the snapshot read as (snapshot-roleorsingle-role), and therayspec resumecommand. On a refusaldataisnull; after the fence was taken,errors[0].messageends with the resume command. On stderr: the operation id, progress lines and, without--json, a summary with the counts and the path of the local receipt.- Receipts.
<state-dir>/receipts/export-<operationId>.json(mode 0600, shareable: no secret, path, record or table name) and, once the downtime is confirmed (thePRECHECKtransition is written then, before the fence is taken), rows ofruntime_control_receiptsof kindexport— one per transitionPRECHECK,QUIESCING,FROZEN,EXPORTING,EXPORTEDorBLOCKED, each with the fence epoch, time, digests and recovery action. - Interruption. SIGINT or SIGTERM stops the export at its next safe point, ends a running
pg_dump, removes the scratch directory, keeps the fence and reportsRAY_INTERRUPTED(exit 6). A process killed outright leaves its scratch directory, plaintext included, until the nextexportorresumeof the deployment removes it first. - Codes. The contract's list for the verb —
RAY_USAGE,RAY_BINDINGS_FILE_INSECURE,RAY_OUTPUT_EXISTS,RAY_MULTI_TENANT_UNSUPPORTED,RAY_OWNER_RECOVERY_REQUIRED,RAY_EXTERNAL_STATE_UNSUPPORTED,RAY_SCHEMA_DRIFT,RAY_SOURCE_NOT_QUIESCENT,RAY_LIMIT_EXCEEDED,RAY_LOCK_TIMEOUT,RAY_INFRA_UNAVAILABLE,RAY_INTERRUPTED,RAY_INTERNAL— and, from the precheck and the capture,RAY_POLICY_DENIED(unsupported-extension),RAY_DIGEST_MISMATCH(bundle-sha256,object-sha256),RAY_RUNTIME_UNSUPPORTED,RAY_TARGET_UNSUPPORTEDandRAY_FENCE_MISMATCH. - Exit:
0exported,2usage, an existing output, a limit or a digest,3external state, tenants, runtime or target,4owner recovery, an insecure state directory, policy or another epoch,5retryable (database, lock, drain deadline),6interrupted or schema drift,7internal error.
import#
rayspec import <migration.ray> --target <state-dir> --identity-file <file> --dry-run [--json]
rayspec import <migration.ray> --target <state-dir> --identity-file <file>
--secrets-out <new-dir> [--bindings-file <file>] [--json]
rayspec import --target <state-dir> --discard-failed [--json]
rayspec import --target <state-dir> --cutover-token <token> [--json]
rayspec import --target <state-dir> --renew-cutover-token [--json]Restores a migration bundle into a new, empty target — two databases and a blob root — as the target's migration role, verifies it, and leaves it fenced until the cutover. The source stays authoritative throughout. The operator guide is Importing a deployment.
- Order. The bundle through the reader (the ciphertext's size and SHA-256 before anything is decrypted); decryption with the identity file into a private scratch directory under
<target>/scratch/, within the migration plaintext limit; the inner snapshot through the same reader; every clear hint of the bundle (application, runtime, target) against the authenticated metadata; the embedded application through the full reader pipeline for this runtime, which must be the runtime the snapshot was taken with; each dump's table of contents, read from its bytes, compared withpg_restore --list, and judged by the restore allowlist; then the target. The dry run stops there. The import goes on throughIMPORTING(the runtime role's default write privileges withheld, then both databases restored under the shared schema lock, workflow system database first, then the objects),VERIFYINGandREADY_FOR_CUTOVER, orBLOCKED; the cutover (--cutover-token) throughCUTOVERandCOMPLETE. - The restore allowlist. Restored: schemas (
drizzlein the application database,dbosin the workflow system database), tables, sequences, defaults, constraints, foreign keys, indexes, triggers, row-level policies, functions insqlorplpgsql, table data, sequence values. Each entry must be exactly the statements its kind consists of. Refused (RAY_POLICY_DENIED): any extension in the application database and any butuuid-osspin the workflow system database (unsupported-extension); an object of another owner, or a grant to a role the dump's default privileges do not name (unmapped-owner); everything else — a role, an event trigger, a view, a type, a language, a large object, a function in another language orSECURITY DEFINER(beyond the platform's two lookups, unchanged),LEAKPROOF, a setting other than the search path, data loaded by anything butCOPY … FROM stdin, a call into the dump or a server function (SQL from text, files, large objects, advisory locks, notifications) from an expression the restore evaluates, an entry outside the sectionpg_dumpputs its kind in, a Unicode-escape name or string (U&"…",U&'…',UESCAPE), a function search path not written as quoted names (privileged-statement). The restore list runs pre-data, data and post-data in that order whatever the archive's order, so no trigger of the dump exists while rows are copied in. Privileges, comments and the dump's owner are not restored: every object belongs to the target's migration role, and the target's runtime and snapshot roles get the grants the database roles setup gives — the runtime role's writes only at the cutover. - The catalogs. After each restore, after the import's own writes and before the cutover, both databases must hold exactly what the restore plan creates: the plan's extensions, schemas, functions and triggers (plus the ones the import adds), each function with the language, security mode, search path and body its dump entry gives it, no view, type, rule, operator, text search object, publication or large object, no privilege for a role the target does not grant to, and default privileges and role settings unchanged (
RAY_POLICY_DENIEDprivileged-statement). - The target must be empty — no table, sequence, function, type, schema besides
public, extension or large object in either database, nothing in the blob root, no deployment or import in the state directory (RAY_TARGET_NOT_EMPTY) — on the snapshot's server major (RAY_TARGET_UNSUPPORTED), with its roles prepared by the database roles setup and a workflow system database when the snapshot carries one (RAY_USAGE). The restoring role may not be a superuser or create roles (RAY_POLICY_DENIEDposture-refused). - Verification. The bytes restored hash to the inventory; the tables and their row counts are the snapshot's; every foreign key is there and validated; the schema head is the snapshot's; exactly one organization owns every tenant row and object (
RAY_MULTI_TENANT_UNSUPPORTEDotherwise, and a dump restoring two organizations is discarded at once); sessions, API keys, invites, OIDC artifacts and owner-recovery tokens are empty; the runtime role holds the isolated posture, reads every table, is owed its writes and can write none of them; every object read back has the index's size, header and both digests. The row counts are checked again after the import's own writes. - Identity. After the verification each account's carried identity — user id, and password hash when it has one — is recorded in the target's
auth_audit(eventidentity_imported, with the operation id and the bundle's digest). The target's own boot secrets are then minted into--secrets-out:jwt-signing-key.pem(RS256 PKCS#8),api-key-pepperandmedia-signing-key, directory 0700, files 0600, never printed. The source's secrets are never carried, so every API key, refresh session, invite, access token and playback URL of the source is refused by the target; passwords keep working. - Flags.
<migration.ray>: the bundlerayspec exportwrote.--target <state-dir>(required): the target's state directory, created (mode 0700) when it does not exist. It must hold no deployment.--identity-file <file>(required): the age identity file (age-keygen), with exactly one X25519 identity. A protected file: a regular file of yours, mode 0600 (RAY_BINDINGS_FILE_INSECURE).--secrets-out <new-dir>(import only, required): a new directory, under an existing one, for the target's own boot secrets. An existing path is refused (RAY_USAGE) before anything is decrypted.--bindings-file <file>(import only): the target application's bindings, in the deploy's format. Reserved names are refused (RAY_BINDING_RESERVED), undeclared namesRAY_USAGE, and a required binding neither the file nor the environment supplies isRAY_BINDING_MISSING. The values are checked, not kept: give them again when you deploy at the cutover.--dry-run: the eligibility plan only.--discard-failed: with--targetalone. Removes what a failed or killed import restored — every object the migration role owns in both target databases, everything in the blob root, and the state directory's deployment and import records (its receipts stay) — and gives back the default privileges the import withheld. A target that is ready for its cutover, cut over, or that holds a deployment, is never discarded.--cutover-token <token>: with--targetalone. The cutover (below).--renew-cutover-token: with--targetalone. Replaces the cutover token of an import ready for its cutover with a new one of the same binding, valid 15 minutes; the old token stops working. Refused when the fence or the catalogs are no longer what the import left.
- Environment (explicit, never a
.envfile):DATABASE_URL(or_FILE; the target's runtime role),RAYSPEC_MIGRATION_DATABASE_URL(or_FILE; required: the restore runs as this role),DBOS_SYSTEM_DATABASE_URL,RAYSPEC_BLOB_ROOT(required when the snapshot carries objects; empty or absent),RAYSPEC_PG_RESTORE(an absolute path; default the firstpg_restoreonPATH, which must be of the server's major). No output carries a value. Output: the result envelope on stdout (operation
import.dry-runorimport), with or without--json. The dry run'sdata:{ bundleSha256, eligible, applicationId, applicationVersion, sourceRuntime, schemaHead, fenceEpoch, workflowSystemDatabase, blockers }(fenceEpochis the source's, the snapshot was taken under it). A target finding is an error and also a blocker indata, witheligible: false. The import'sdata:{ "bundleSha256": "…", "deploymentId": "8c1f0a2b3c4d5e6f", "status": "ready-for-cutover", "applicationDigest": "…", "schemaHead": { "platform": "0015_tenant_row_security", "product": "…" }, "verification": { "checksums": "match", "tableCounts": "match", "objects": "match", "referenceIntegrity": "match" }, "credentialReset": { "sessions": "reset", "apiKeys": "reset", "invites": "reset", "oidcArtifacts": "reset", "passwordHashes": "preserved", "forcedLogin": true } }On stderr: the operation id, progress lines and, without
--json, a summary with the counts, who signs in again with their password, which owner needs owner recovery (no password; seetenant recover-owner) and which account has no way in, that every API key is reissued, the target's fence epoch, the cutover instruction naming the secret files and the cutover token (below). The receipt's summary keeps only the counts (identity) andbootSecrets: "reissued".- Cutover. The import holds the target's fence (epoch 1): the runtime role never held a write on what was restored, and the writes it is owed are recorded with the fence. The cutover token — the SHA-256 of
{migrationBundleSha256, applicationDigest, targetDeploymentId, sourceFenceEpoch, targetFenceEpoch, targetEnvironmentRevision, catalogSha256, issuedAt, expiresAt}and a random value — is shown once in the summary; the fence and the receipts keep only its SHA-256. It works once, for 15 minutes. To cut over: keep the source fenced, runrayspec import --target <target> --cutover-token <token>in the target's environment, then deploy the application the source ran there (rayspec deploy <file.ray> --state-dir <target>), with the target's own boot secrets (RAYSPEC_JWT_SIGNING_KEY_FILE=<new-dir>/jwt-signing-key.pem,RAYSPEC_API_KEY_PEPPER_FILE=<new-dir>/api-key-pepper, andRAYSPEC_MEDIA_SIGNING_KEYfrom<new-dir>/media-signing-keywhen the application has a playback route). The cutover refuses another token, a used one, an expired one and one whose binding no longer holds (another bundle, deployment or source fence thanimport.json, or a moved target fence or environment revision) withRAY_POLICY_DENIED, and a target whose catalogs changed withRAY_RECONCILIATION_REQUIRED; otherwise it marks the token used (CUTOVER), releases the fence, grants the runtime role its writes and recordsCOMPLETE(data: null, exit 0).rayspec resumenever releases a fence an import holds. - Receipts.
<target>/receipts/import-<operationId>.json(mode 0600, shareable: no secret, path, record or table name) and, once the target is verified, rows ofruntime_control_receiptsof kindimportin the target — one per transitionIMPORTING,VERIFYING,READY_FOR_CUTOVER(again for a renewed token),CUTOVER,COMPLETEorBLOCKED, each with both fence epochs, the time, the digests and the recovery action.<target>/import.jsonsays which import left the target in which state. - Interruption and failure. SIGINT or SIGTERM stops the import at its next safe point and ends a running
pg_restore, whose transaction rolls back (RAY_INTERRUPTED, exit 6). A failure after the target changed isRAY_RECONCILIATION_REQUIRED(exit 6) or the refusal that found it; the target is marked failed (import.jsonBLOCKED, and fenced as failed once its application database was restored: that fence is never resumed) until--discard-failed; so is a verified target whose--secrets-outcould not be written. A process killed outright leaves its scratch data andimport.jsonatIMPORTING; the nextimportof the target removes the scratch data (so doesresume), closes the killed run's receipt and marks the target failed. - Codes. The contract's lists for the two forms —
RAY_USAGE,RAY_INVALID_ARCHIVE,RAY_LIMIT_EXCEEDED,RAY_MANIFEST_INVALID,RAY_DIGEST_MISMATCH,RAY_DECRYPTION_FAILED,RAY_BINDINGS_FILE_INSECURE,RAY_RUNTIME_UNSUPPORTED,RAY_TARGET_UNSUPPORTED,RAY_TARGET_NOT_EMPTY,RAY_MULTI_TENANT_UNSUPPORTED,RAY_INFRA_UNAVAILABLE,RAY_INTERNAL, and for the import alsoRAY_BINDING_RESERVED,RAY_BINDING_MISSING,RAY_POLICY_DENIED,RAY_LOCK_TIMEOUT,RAY_RECONCILIATION_REQUIREDandRAY_INTERRUPTED— and, from the embedded application's reader pipeline, its codes (RAY_CAPABILITY_UNSUPPORTED,RAY_SPEC_INVALID, …); the dry run also reportsRAY_POLICY_DENIEDfor a dump the allowlist refuses. - Exit:
0eligible or ready for cutover,2usage, archive, manifest, digest, decryption or a limit,3runtime, target or tenants,4not empty, policy or an insecure file,5retryable (database, lock),6interrupted or a failed restore,7internal error.
resume#
rayspec resume --deployment <id> --fence-epoch <n> [--state-dir <dir>] [--json]Releases the source fence an export took, only at the epoch it is held at, and grants the runtime role back exactly the writes the barrier revoked. Every runtime process restarts its producers within a second. It never releases a fence an import holds (RAY_USAGE): an imported target is released by its cutover (rayspec import --target <dir> --cutover-token <token>), a failed one is discarded.
- Flags:
--deployment <id>(required; checked against the state directory and the database, elseRAY_USAGE),--fence-epoch <n>(required; the epoch the export reported),--state-dir. - Environment: as for
export; only the database connections are used. - After a killed export. Before anything else,
resumeremoves what an export killed outright left in<state-dir>/scratch/(its plaintext capture), by the ruleexportapplies: only when no live process holds the scratch lock, so a running export is left alone. It closes the killed export's receipt as interrupted, with the fence as the environment records it, and says on stderr what it removed. This happens even when the resume itself is refused. - Output: the result envelope (operation
resume) withdata: { deploymentId, fenceEpoch, released, environmentRevision }.releasedisfalsewhen the fence was already open at that epoch; nothing changes then. - Exit:
0released or already open,2usage,4another epoch (RAY_FENCE_MISMATCH),5the database cannot be reached,7internal error.
rayspec-serve — the boot server#
rayspec-serveThe local boot entrypoint. It is entirely environment-driven — a real deployment sets its configuration through its orchestrator or secret manager.
- It reads its configuration from the ambient environment and fails closed on a missing or unsafe value: it refuses to boot unless
DATABASE_URL,RAYSPEC_JWT_SIGNING_KEY(the RS256 PKCS#8 PEM), andRAYSPEC_API_KEY_PEPPERare set — secrets live in the environment or a secret manager, never in the database or in git. - Each of those three also accepts a
<VAR>_FILEvariant (DATABASE_URL_FILE,RAYSPEC_JWT_SIGNING_KEY_FILE,RAYSPEC_API_KEY_PEPPER_FILE) naming a file to read the value from, which takes precedence over the plain variable; a<VAR>_FILEpointing at a missing, unreadable, or empty file aborts the boot rather than falling back to the plain variable. - Leading and trailing whitespace (a trailing newline, a leading byte-order mark) is stripped from a resolved secret regardless of source — a
<VAR>_FILEmount and the plain variable are byte-equivalent — while interior bytes are preserved (a multi-line PEM is safe). A secret whose real bytes need edge whitespace must be base64-encoded. - When that normalization actually changes a resolved secret, the boot prints one warning per changed secret on stderr, naming the variable it was resolved from (
<VAR>, or<VAR>_FILEwhen the mount won) and the kind of change —a leading byte-order mark removed,leading whitespace removed,trailing whitespace removed. It never prints the value or any part of it, and the boot continues with the normalized value. A secret the trim leaves untouched is silent. The stripped trailing newline of a key file created with a>redirect is the expected, harmless case; the signal matters when a secret that carried edge whitespace suddenly stops being accepted. - Ahead of that resolution it loads a local
.envif one exists — a local-development convenience; a real deployment has none. It searches$PWD/.env, the directoryrayspec-servewas started in, first and the RaySpec install root's.envsecond — the install root being the directory four segments above the loader's own module: your checkout root when you run from a checkout, and from a registry install the consuming project's own root under npm's flat layout or a directory insidenode_modules/.pnpm/under pnpm's. It is a position rather than a named package — whatever sits four segments up, including the unscopednode_modules/rayspeclauncher directory itself under npm's nested layout — deduplicated to one read when they are the same file. Neither file overrides a variable the environment already sets, and the second never overwrites a key the first supplied, so the precedence per key is: environment >$PWD/.env> install-root.env.RAYSPEC_SKIP_DOTENV=1skips both.rayspec deployapplies the same two rules in the same order, so the two entrypoints started in the same directory read the same./.env. The first path is$PWD-relative, so that directory is what they have to share: arayspec-servestarted elsewhere — a unit file'sWorkingDirectory=, a container'sWORKDIR— reads that directory's./.envinstead. The install-root candidate is resolved per package, from each loader's own module, so it is the same file only where the two packages sit under one root: in a checkout, and under npm's flat layout. Under pnpm each resolves inside its ownnode_modules/.pnpm/@rayspec+cli@<version>/and…/@rayspec+server@<version>/directory, so an install-root.envplaced for one entrypoint is not read by the other. Where both entrypoints must agree regardless, set the variables in the environment: an already-set value beats either file. - On boot it applies the committed platform migration chain to the target database (idempotent — it bootstraps a clean database and no-ops on an up-to-date one), then materializes a spec's declared stores on a clean database or mounts them when they already match. It does not auto-apply a store schema change: a live product schema that has drifted from the spec fails closed — reconcile it with a reviewed forward migration (
rayspec deploy --apply-migration, or the equivalentRAYSPEC_UPDATE_MIGRATIONenvironment variable). - It prints a loud banner stating that this is a local, single-node, not-yet-hardened deployment and must not be placed behind a public address. See Architecture → Security model and SECURITY.
- With no spec configured it is an auth-only boot — accounts, authentication, OIDC, and a
/healthprobe, with no product routes. PointRAYSPEC_SPEC_PATHat a spec to deploy the declared product on top. A backend-profile spec that declares agents boots directly this way: the entrypoint builds each declared agent's backend instance from the ambient environment (for example theopenaibackend fromOPENAI_API_KEY) — no hand-writtenAgentBackendsFactorywrapper, and a missing credential fails the boot fast, naming the backend and the agent(s) that select it. (rayspec deploy <spec>is the same boot withRAYSPEC_SPEC_PATHset for you, except thatdeployseals the product-store registrar once its boot returns and defaults the agent trace export off, neither of whichrayspec-servedoes; see getting-started.) - A frontend-only spec — one that declares only a
frontend(nostores,api,agents,tooling,triggers,handlers, orextensions, no durable worker and no enabled event bus) — boots as a static profile: it requires none of the three boot secrets and mounts no auth / OIDC / run route (/healthruns no database probe; it reports the declared mounts' readiness asfrontend). It emits its ownContent-Security-PolicyandPermissions-Policyresponse headers, read fromRAYSPEC_FRONTEND_CSPandRAYSPEC_PERMISSIONS_POLICY(each with a secure default when unset), so a built single-page app can be served directly with no reverse proxy in front — the same two headers a full-backend boot stamps on the responses its ownfrontendmounts serve, from the same two variables. The CSP default isdefault-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'— it names nostyle-srcand noscript-src, so a served page's CSS and JS belong in files, not inline, and an override replaces that whole baseline verbatim rather than adding to it — see getting-started → a frontend-only (static) deployment.
It listens on PORT (default 8080) and shuts down gracefully on SIGINT / SIGTERM. The full set of environment variables is documented in .env.example.
See also#
- Packing an application — what
packputs in a bundle, what it leaves out, and how to fix each refusal. - Deploying a bundle on your own server — inspect, bind, review, apply, readiness, update and recovery of a
.raydeployment. - Runtime operations — what a deploy records, and how to recover from an interrupted one.
- Exporting a deployment — planning the downtime, what an export carries and resets, and recovery when it is interrupted.
- Importing a deployment — preparing an empty target, what a dump may contain, the cutover, and recovery when an import fails.
- Getting started — these commands in sequence.
- Spec reference — the grammar
doctor/plan/openapicheck. - Architecture — how a deploy turns a spec into a running backend.