@lunora/cli is the standalone alternative to the Vite plugin. It powers
the lunora binary you got when you ran npx lunorash@alpha init. The
plugin and the CLI share the same @lunora/codegen core, so the generated
files are identical regardless of how they were produced.
Commands
# Project
lunora init [name] [-t <template>] # scaffold a new project (default: react)
[-i | --yes] # offer (or skip) adding auth + email
[--auth <lunora|clerk|workos|auth0|none>] # choose the auth up front
lunora add <auth|email> # add a feature to the current project
lunora view # open the Lunora studio in your browser
lunora docs [section] # open the docs site in your browser
lunora info [--format json] [--bindings] # versions + wrangler summary; --bindings for the manifest
lunora doctor [--format <pretty|json>] # preflight the project (bindings, placeholders, secrets)
lunora registry <add|list|view|build> # component registry (add/list: --format json)
lunora rules <install|check> # install the AI agent skills into .agents/skills/
# Develop
lunora mcp install [client…] # wire Lunora's MCP servers into your editor
[--list] [--print] [--force]
[--docs-only] [--local-only]
[--global | --project]
lunora mcp uninstall [client…] # remove them again
lunora mcp serve [--allow-writes] # the stdio MCP server your editor spawns
[--no-docs] [--url u] [--token t]
lunora dev [--port n] [--worker-port n] # wrangler worker + studio + codegen watch
[--inspector-port n]
[--remote | --local]
[--no-studio] [--no-codegen] [--lazy-functions]
[--tunnel [--allow-mail <email>…]]
lunora codegen [--api-spec <spec>] # one-shot codegen
[--format <pretty|json>] [--lazy-functions]
lunora run <fn> [--args <json>] # send a single RPC to a running worker
[--shard <key>] [--url <u>] [--format json]
[--as <userId>] [--claims <json>] # run as an identity (identity-gated apps)
lunora insights [--shard <key>] # write-conflict / error / latency hot-spots
[--limit n] [--format json] [--prod --url <u>]
lunora profile --target node --url <u> # on-demand CPU / heap profile (pprof) of a Node app
[--type cpu|heap] [--duration-ms n] [--out <file>] [--token <t>]
lunora reset [--all] [--yes] # clear local Miniflare state
# Deploy
lunora prepare [--api-spec <spec>] # every pre-deploy gate, without deploying — for CI
[--lazy-functions] [--no-smoke-load]
lunora build [--out-dir <dir>] [--no-framework-build] # bundle the worker to disk without deploying
[--lazy-functions] [--no-smoke-load] [--no-startup-check]
lunora deploy [--env <name>] # codegen, validate wrangler, then wrangler deploy
[--migrate --migrate-yes] # --migrate also needs --migrate-url unless linked
[--lazy-functions] [--no-smoke-load] [--no-framework-build]
[--prebuilt] [--dry-run] # --dry-run validates + bundles, never publishes
[--temporary] # --temporary deploys with no account (~60min, then claim)
[--health-check] # --health-check probes /_lunora/health/ready after deploying
lunora preview deploy <name> # isolated copy: own Worker, Durable Objects, D1, KV, R2
[--seed] [--secret <KEY>] [--var <KEY=VALUE>] [--dry-run]
lunora preview list | delete <name> [--env <name>] # previews on record (--env: that environment's account)
lunora link --url <url> [--env <name>] # link this checkout to its deployed worker
lunora verify [--api-spec <spec>] # dry-run codegen + tsc --noEmit (no files written)
[--no-typecheck] [--lazy-functions]
lunora analyze [--format json] # wrangler dry-run: bundle size + top modules
# Cloudflare only (refused on a celld or Node project)
lunora cloudflare # list the tools
lunora cloudflare alerts [status|setup|test] # usage alerts that catch a runaway bill
lunora cloudflare deployments <list|inspect|rollback|promote> # history + traffic control
[--env <name>] [--yes] [--format json] # json: `list` only
lunora cloudflare profile [worker] # on-demand CPU / heap profile (pprof) of the live Worker
lunora cloudflare containers <build|push|images|list|info|delete> [args…]
[--tag <name:tag>] [--push] [--env <n>]
[--format json] # json: list | info | images list
lunora cloudflare ai-gateway [--id <id>] [--env <name>] # create/reuse an AI Gateway, write its id to vars
[--no-logs] [--dry-run] [--format json]
# Data
lunora logs [worker] # stream live Worker logs via wrangler tail
[--format <pretty|json>] # [--status <s>] [--search <q>] [--env <n>]
lunora migrate <generate|create|up|down|status> [name|id] [--format json]
lunora env <list|get|set|unset|push|diff|doctor> [--format json]
lunora export [--out <file>] [--tables <t1,t2>] [--url <u>] [--token <tok>]
[--format json] # json needs --out <file>
lunora import <file> [--table <name>] [--batch-size n] [--mode <m>] [--dry-run] [--format json]
lunora backup <create|list|restore|pitr> [--dir <d>] [--bucket <b>] [--at <iso>]
[--format json]
lunora seed [--table <t>] [--count n] # deterministic fake data from schema.ts
[--seed n] [--dry-run] [--reset] [--format json]
lunora shards prune [--tables <a,b>] # drop empty shards from the shard registry
[--dry-run] [--format json]
lunora pause [status] [--reason <text>] # incident switch: refuse calls, hold jobs/crons/queues
lunora resume # undo `lunora pause`; held jobs run at once
lunora admin-token create|list|revoke # named, revocable admin tokens (root token only)
[--expires-days n] [--format json]
lunora workflow <create|send-event> ... # start a workflow instance / send it an event
[--id <id>] [--params <json>] [--payload <json>] [--format json]
lunora introspect [--url <u>] [--tables <t1,t2>] # scaffold schema.ts from an
[--schema <s>] [--no-procedures] # existing Postgres/MySQL DB
[--format json]Machine-readable output
Every command that produces a result document takes --format pretty|json
(pretty is the default). In json mode stdout carries exactly one JSON
document and every human/progress line moves to stderr, so lunora <cmd> --format json | jq always parses.
The document is the same envelope for every command:
{
"code": 0, // the exit code the process terminates with
"data": {}, // the command's own payload — per-command, absent when it produced none
"error": "…", // why it failed; present whenever `code` is non-zero and a reason is known
}One shape to parse, whichever command produced it — and a failure answers in the same shape a success does, so the reason never has to be scraped out of English prose on stderr:
lunora doctor --format json | jq '.data.findings[] | select(.level == "fail")'
lunora migrate status backfill-names --format json | jq '.data.result'
lunora env diff --format json | jq -r '.data.localOnly[]'
# The failure path is parseable too.
lunora verify --format json | jq -r 'if .code == 0 then "ok" else .error end'code is the only key present on every document — data is absent when the run
failed before producing one, and error is absent on success. Read code (or
the process exit status, which is the same number — see
CLI exit codes) before reaching for either.
Commands with the flag: add, advisor, analyze, backup, build,
cloudflare (every tool), codegen, deploy, doctor, env, eval,
export, import, info, insights, introspect, logs, migrate,
registry, run, seed, verify.
Three carry a documented restriction, because the payload already owns stdout or
the underlying tool has no JSON rendering: export --format json requires
--out <file> (with --out - the NDJSON stream is stdout); cloudflare deployments --format json applies to list and status only; cloudflare containers --format json applies to list, info and images list. Each refuses with a usage error rather than
emitting a fabricated document.
Where the flag is forwarded to a tool that writes the document itself —
cloudflare deployments list and status, the cloudflare containers read subcommands, and
logs (a stream, not a result) — stdout carries that tool's output and no envelope is added, since
a second document on the same stream would make neither parseable.
lunora dev --json is deliberately not part of this: it selects a streaming
JSON log-line format for a long-running process, not a single result
document. See CLI exit codes for the other half of the
automation contract.
lunora init
Scaffolds a new Lunora project by fetching a template from
gh:anolilab/lunora/templates/<type>#<ref>. The ref is a branch, derived
from the running CLI's own version: a pre-release resolves to its channel
(alpha, beta, next), a stable release to main. --ref overrides it with
any branch, tag or commit. init (and add) then resolve that ref to the
immutable commit SHA it currently points at (logged as pinned … → <sha>), so
the fetch is reproducible and tamper-evident; if the SHA can't be resolved
(offline / rate-limited) it falls back to the ref itself with a one-line
UNPINNED warning. Pass -t / --template to choose the starting point:
| Value | Description |
|---|---|
react | React SPA — official create-vite base + the Lunora layer (the default) |
vue | Vue SPA — create-vite base + Lunora |
solid | Solid SPA — create-vite base + Lunora |
solid-v2 | Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3) |
svelte | Svelte SPA — create-vite base + Lunora |
rspack-react | React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server |
next | Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker |
tanstack-start-react | TanStack Start (React) — SSR with live-loader routes |
tanstack-start-react-rspack | TanStack Start (React) on Rsbuild — SSR composed into the Lunora worker |
saas | SaaS kit — multi-tenant app on TanStack Start: organizations, projects, activity, admin |
tanstack-start-solid | TanStack Start (Solid) |
vinext | Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental) |
vinext-pages | Next.js Pages Router on Vite (vinext) — composed into one worker (experimental) |
astro | Astro (islands) — single-worker, Lunora composed into the adapter worker |
analog | AnalogJS (Angular) — single-worker, Lunora mounted in Nitro |
nuxt | Nuxt (Vue) — single-worker, Lunora mounted in Nitro |
sveltekit | SvelteKit — single-worker, Lunora composed into the adapter worker |
expo | React Native (Expo) — an iOS/Android/web app + a Lunora worker backend |
standalone | Worker only — no frontend |
The create-vite frameworks (react, vue, solid, svelte, plus
vanilla via --vite) scaffold through the overlay engine (the official
create-vite base plus the Lunora layer), while the rest are bespoke Lunora
templates — solid-v2 included, because create-vite's Solid base is still
1.x. Run lunora init with no -t to pick from the same list interactively.
Additional flags:
-
--vite <framework>: scaffold via the create-vite overlay forreact|vue|solid|svelte|vanilla. Equivalent to passing the same value to-t. -
--from <dir>: copy from a local templates root instead of fetching remotely (offline-friendly; expects<type>/subdirs) -
--source <ref>: override the remote template source (e.g.gh:owner/repo/sub#ref) -
--ref <ref>: fetch templates from a git branch, tag or commit (e.g.--ref alpha), overriding the version-derived default above -
--allow-unsafe-source: permit--sourcevalues outsidegh:/github:/https:// -
--here: add Lunora to an existing project (detect the framework, patch the config, scaffoldlunora/, print per-framework wiring steps) -
-i/--interactive: after scaffolding, offer to add authentication and transactional email. Defaults on when stdin is a TTY; never prompts in CI. -
-y/--yes: scaffold only — skip every post-scaffold prompt (the auth/email offer, the dependency-install offer, andgit init). The project is complete; run the printed install command yourself. -
--auth <lunora|clerk|workos|auth0|none>: choose the auth. The interactive offer asks the same question first (defaultnone).lunorais@lunora/auth(better-auth): users and sessions in your own D1, the same as--add auth. Interactively it asks for the provider (email & password, or Clerk / Auth0 as an OAuth login) and the D1 database name.clerk,workosandauth0let the provider own the session: init applies theauth-clerk-jwt/auth-workos-jwt/auth-auth0-jwtregistry item (@lunora/jwt-auth,lunora/identity/<provider>.ts, the env vars in.dev.vars), wires the resolver asresolveIdentity(chained onto the entry'sdefineApp()builder, or a newlunora.config.tsapphook for a Vite-first app), turns onauthTokenOnUpgradewhere the app builds itsLunoraClient, and prints the client snippet that hands the provider's token tosetAuthTokenProvider. See External auth.noneadds nothing.
Without a TTY (or with
--yes),--authis applied with its shipped defaults, like--add. -
--add <list>: add features non-interactively after scaffolding — a comma-separated list of the values in thelunora addtable, each applied with its shipped defaults. Bypasses the interactive picker and its sub-prompts. -
--dry-run: walk every step (prompts and output included) without writing files, installing, or running git. -
--ci <github\|gitlab>: also scaffold a CI deploy pipeline (.github/workflows/deploy.ymlfor GitHub Actions,.gitlab-ci.ymlfor GitLab CI), with a productionlunora deployon the default branch, alunora preview deploy <number>on every pull / merge request, and alunora preview delete <number>once it is closed or merged (a fork's or Dependabot's pull request, and a fork's merge request, gets alunora deploy --dry-runcheck instead, since it receives no secrets). SetCLOUDFLARE_API_TOKENandCLOUDFLARE_ACCOUNT_IDas the provider's secrets / CI-CD variables, and on GitHub a separateCLOUDFLARE_PREVIEW_API_TOKENthat only thelunora previewsteps receive (on GitLab mark every production one,LUNORA_DEPLOY_URLandLUNORA_ADMIN_TOKENincluded, Masked and Protected with Environment scopeproduction: protected variables reach only protected branches and tags, so a merge-request pipeline, which runs your project's code, gets none of them, and only thedeployjob declaresenvironment: production). On GitLab, previews need their ownCLOUDFLARE_API_TOKEN(Workers Scripts, D1, KV and R2 edit; never the production token) andCLOUDFLARE_ACCOUNT_ID, Masked but not Protected, with Environment scopepreview/*, which only the preview jobs receive. After the first deploy setLUNORA_DEPLOY_URLandLUNORA_ADMIN_TOKEN, which let the production deploy's drift gate read the stored rows. That read only happens for a custom domain on a declared route: a*.workers.devURL needs a project link, and.lunora/is not committed, so on*.workers.deva tightening in CI still needs a migration or--allow-schema-drift.
lunora add
Adds a feature to the current Lunora project (you must be inside one: a lunora/ directory and a wrangler.jsonc). A thin front door over lunora registry add: it maps a feature to its registry item(s), applies them, and prints the next steps.
lunora add auth # authentication (asks which provider)
lunora add auth --provider clerk # Clerk, without prompting (also: auth0, auth)
lunora add auth --yes # default provider (email & password), no prompt
lunora add email # transactional email (Cloudflare Email Workers + dev mail catcher)These are the features the interactive picker offers and lunora init --add
accepts. Each is the registry item of the same name, applied with its shipped
defaults — except email, which maps to the mail item, and auth, which
picks between auth, auth-clerk and auth-auth0:
| Feature | Installs |
|---|---|
ai | LLMs via Workers AI (summarize, generate, stream) |
auth | Sign-up / sign-in (asks which provider) |
auth-ui | Copy-in auth screens for your framework (sign in/up, reset, 2FA) |
backup | Snapshot + restore your Durable Object data |
browser | Headless browser screenshots + PDFs |
cloudflare-access | Zero Trust identity via Cloudflare Access |
crons | Scheduled jobs via Cron Triggers (@lunora/scheduler) |
email | Cloudflare Email Workers + a dev mail catcher |
flags | OpenFeature feature flags (ctx.flags) |
hyperdrive | External Postgres/MySQL via Hyperdrive |
payment | Stripe-first payments (checkout, subscription, webhooks) |
presence | Live presence / who's-online over hibernated WebSockets |
queue | Async message queues (push/pull consumers) |
storage | Typed R2 buckets + signed URLs (@lunora/storage) |
workflow | Durable long-running workflows (step.do, sleep, branch) |
auth adds @lunora/auth plus a D1 DB binding, and its verification / reset
mail is captured into the studio Mail tab in dev. Any other registry item
name works here too (auth-clerk, …) — this table is the curated shortlist, not
the whole registry; lunora registry list enumerates that.
Flags: --provider <auth\|clerk\|auth0>, --db <name>, --bucket <name>, --mail-to <address>, --yes, --from <dir> (local registry root), --source <ref>, --ref <ref>, --allow-unsafe-source.
lunora view
Opens the Lunora studio in your browser. The studio is always local: the
running dev server records where it is serving it in .lunora/dev.json, so
view opens that — the embedded studio server for the wrangler flavor, or
Vite's /__lunora route when @lunora/vite owns the dev server. With no dev
server running it falls back to the studio server's default,
http://127.0.0.1:6173.
lunora view # the running dev server's studioA deployed worker serves no studio — its /_lunora/* routes are RPC, WebSocket, status, migrate and admin only — so there is no remote URL to open. The
--remote flag this command used to take opened a 404 and has been removed.
lunora docs
Opens the documentation site in your browser. Pass an optional section path to jump straight to a page.
lunora docs # the docs home
lunora docs addons/studio # a specific sectionlunora info
Prints the resolved project configuration: the installed @lunora/* versions, a
wrangler.jsonc summary, and an overview of the tables declared in
lunora/schema.ts. --format json emits the same snapshot machine-readably,
useful in bug reports and CI diagnostics.
lunora info
lunora info --format json--bindings: what this Worker needs provisioned
--bindings narrows the command to one question a machine asks — the binding
manifest. It is the same document lunora build --emit-bindings hands a deployer
and lunora dev writes for a task runner, from the same derivation, so those
consumers cannot be told different things.
lunora info --bindings # bindings, crons and var NAMES
lunora info --bindings --format json # the manifest itself
lunora info --bindings --out reqs.json # write itThe manifest is a pure function of the project, so this answers without starting a dev server or producing a bundle — which is what a supervisor planning a multi-worker graph needs before it starts anything. It never carries variable values, only their names.
A project with no readable wrangler.jsonc exits non-zero rather than reporting
an empty manifest: "this Worker needs nothing" is a claim a deployer acts on by
provisioning nothing. --out without --bindings is an error.
lunora doctor
A read-only preflight over the current project. It reports pass / warn / fail for:
wrangler.jsonc: that it exists, parses as JSONC, and declares theSHARDDurable Object binding.- D1 placeholders: a
database_idstill left at the scaffold placeholder. - Email destination: a
send_emailbinding whosedestination_addressis still a placeholder. .dev.vars: secrets present but left with unfilled values.LUNORA_ADMIN_TOKEN: whether it is set.- Containers: every container declared in your config is actually exported by the worker entry.
- Version skew:
@lunora/*packages spanning different versions, or mixing release channels (e.g. stable + alpha). - CLI shadowing: a globally-installed
lunorarunning instead of the project's own, so the report describes a project this CLI is not pinned to. - AI: a project using
ctx.aiwith noaibinding, aLUNORA_AI_GATEWAY_TOKENwith no gateway id to send it to, and (info) noLUNORA_AI_GATEWAY_ID, which leaves<provider>/<model>slugs on the account'sdefaultgateway.
lunora doctor
lunora doctor --format json # machine-readable; one JSON document on stdout
lunora doctor --fix # create placeholder D1 databases and mint missing .dev.vars secretsWithout --fix it writes nothing. With --fix it writes only the two things named
above, and --fix --dry-run shows them first. It exits non-zero when any hard check
fails, so it works as a CI gate. See Debugging for how to act on each finding.
Machine-readable output
--format json prints exactly one JSON document on stdout; the human report is
still rendered, but on stderr, so the document stays pipeable. The exit code is
identical in both formats.
{
"code": 1,
"findings": [
{
"code": "d1-placeholder-id",
"fix": "Run `wrangler d1 create <name>` …",
"level": "fail",
"message": "D1 binding \"DB\" has a placeholder database_id …",
},
// …the info- and pass-level findings the summary counts
],
"ok": false,
"summary": { "fail": 1, "info": 1, "pass": 1, "warn": 0 },
}ok is redundant with code on purpose: it is the field a consumer without a
shell reaches for first. pass-level findings are included, so the document
describes everything that was checked, not only what went wrong.
Finding codes
Branch on finding.code, never on message: the codes are the contract, the
prose is not. New codes are added over time; treat an unknown one as advisory.
| Code | Level | Meaning |
|---|---|---|
admin-token-missing | info | LUNORA_ADMIN_TOKEN is not set (studio / admin RPCs stay disabled). |
admin-token-set | pass | LUNORA_ADMIN_TOKEN is set. |
ai-binding-missing | warn | ctx.ai is used with no ai binding and no LUNORA_AI_PROXY_URL. |
ai-gateway-default | info | No LUNORA_AI_GATEWAY_ID or proxy; slugs route through the default AI Gateway. |
ai-gateway-token-unused | warn | LUNORA_AI_GATEWAY_TOKEN is set, but ctx.ai's binding path cannot send it. |
artifacts-jurisdiction-mismatch | fail | A bound Artifacts namespace sits in another jurisdiction than the schema's .jurisdiction(). |
artifacts-jurisdiction-ok | pass | A bound Artifacts namespace is in the schema's jurisdiction. |
artifacts-jurisdiction-unchecked | warn | No CLOUDFLARE_API_TOKEN / account id, or the API refused, so a namespace's jurisdiction was not read. |
artifacts-namespace-missing | fail | Not reported by doctor: a missing namespace passes, since lunora deploy creates it. |
celld-toolchain-missing | fail | celld target: celld or esbuild is not on PATH, or exits nonzero, so the deploy cannot run. |
celld-toolchain-ok | pass | celld target: celld, esbuild and CELLD_BUCKET are in place for a deploy. |
celld-toolchain-warn | warn | celld target: CELLD_BUCKET is unset (a live deploy needs it), or celld is older than rated or its version unreadable. |
cf-config-present | warn | A Cloudflare CLI cloudflare.config.* is in the project root (Lunora never updates it). |
cimd-fetch-not-strictly-public | warn | @lunora/auth/cimd/workers is imported without the global_fetch_strictly_public flag. |
cli-shadowed | warn | The running lunora is not the project's own install. |
cloudflare-token-ok | pass | The Cloudflare API token is active for the account. |
cloudflare-token-rejected | fail | The Cloudflare API token is rejected or not active, so deploys with it fail. |
cloudflare-token-unchecked | info | No token / account id, or the API could not verify the token, so it was not checked. |
cpu-limit-missing | info | No limits.cpu_ms caps a runaway handler's CPU burn. |
d1-placeholder-id | fail | A D1 binding still carries a scaffold database_id. |
declared-export-missing | fail | A declared container / workflow / agent is not exported by the worker entry. |
declared-export-ok | pass | A declared container / workflow / agent is exported by the worker entry. |
declared-export-unchecked | warn | Binding inference failed, so the worker-entry export check could not run. |
dev-vars-missing-secret | warn | .dev.vars has secret-looking keys left at placeholder values. |
do-class-budget-full | warn | The account is at the Workers Paid cap of 500 classes (warns: an account fact). |
do-class-budget-near | warn | The account is within 10 classes of a Durable Object class cap (100 Free, 500 Paid). |
do-class-budget-ok | pass | The account has room under the Durable Object class caps. |
do-class-budget-unchecked | info | No CLOUDFLARE_API_TOKEN / account id, or the API refused, so the class count was not read. |
email-destination-placeholder | warn | A send_email binding has a placeholder destination_address. |
observability-full-sampling | info | Logs or traces sample every request; Workers Observability is billed from 2026-12-01. |
observability-query-unredacted | warn | Request logs or traces keep query strings, which carry auth-link tokens. Set redact_query_string. |
paid-product-bound | info | A metered product (Workers AI, Browser Rendering, Images) is bound; only an account budget alert caps it. |
paid-product-unknown | info | Argo Smart Routing and Log Explorer enablement is a dashboard setting, which lunora cannot read. |
r2-lifecycle-unset | info | An R2 bucket may lack an abort-incomplete-multipart lifecycle rule. |
scheduler-origin-missing | warn | A SchedulerDO is declared but LUNORA_ORIGIN_URL is missing from wrangler. |
schema-unreadable | fail | lunora/schema.ts could not be parsed, so schema-derived checks were skipped. |
service-workers-dev | warn | A lunora.config service is still public on workers.dev with no route. |
stale-lunora-json | warn | lunora.json is present but no longer read (lunora.config.* replaced it). |
vector-metadata-index-required | info | A declared Vectorize metadata filter needs its metadata index created. |
vector-metadata-unfilterable | warn | A metadata property has a type Vectorize cannot filter on. |
version-counter-spread | info | Same-channel @lunora/* pre-release counters differ (normal, worth noting). |
version-skew-channels | warn | @lunora/* packages mix release channels (stable + alpha). |
version-skew-cores | warn | @lunora/* packages span different major.minor.patch versions. |
wrangler-advisory | warn | A wrangler.jsonc warning no more specific check claimed. |
wrangler-class-unexported | fail | A durable_objects / workflows class_name is not exported by the worker entry. |
wrangler-invalid | fail | A wrangler.jsonc validation error no more specific check claimed. |
wrangler-missing | fail | No wrangler.jsonc was found. |
wrangler-shard-binding-missing | fail | wrangler.jsonc is missing the SHARD durable-object binding. |
wrangler-shard-binding-ok | pass | wrangler.jsonc declares the SHARD durable-object binding. |
wrangler-unparseable | fail | wrangler.jsonc was found but is not valid JSONC. |
lunora dev
Pass --lazy-functions to generate per-module lazy imports at startup and on
regeneration, including Studio edits. The default is eager generation unless
codegen.lazyFunctions in lunora.config.ts enables it.
Starts three concurrent processes: wrangler dev (Worker), the embedded
Lunora studio, and codegen in watch mode. All three reload on file changes.
In a project on @lunora/vite it spawns vite dev instead: the Vite plugin
already runs the worker, studio, and codegen inside the Vite dev server.
lunora dev # default ports: studio 6173, worker 8787
lunora dev --port 7000 # custom studio port
lunora dev --worker-port 8790 # custom wrangler dev port
lunora dev --inspector-port 9235 # pin wrangler's devtools inspector port
lunora dev --no-studio # Worker + codegen only
lunora dev --local # no remote proxy session (CI without Cloudflare credentials)A binding with no local mode (ai), in the app or in a lunora.config
service, makes wrangler dev open a remote proxy session, and in a shell with
no Cloudflare credentials that session fails and takes the whole dev session
with it. --local starts it without the proxy; a call to such a binding then
fails instead. It cannot be combined with --remote, and it overrides a remote
default from LUNORA_REMOTE or lunora.config.
When 8787 is taken, the worker lands on the next free port so two projects can
run side by side. That silent move is refused when .dev.vars pins the worker
origin to 8787 — an AUTH_URL/BETTER_AUTH_URL (or any other loopback origin
on that port) would be left pointing at nothing. Free 8787, or pass
--worker-port and update the pinned values to match.
The two ports wrangler takes
wrangler dev binds the worker and a devtools inspector, and both are
configurable from lunora dev. Each resolves the same way — the flag first,
then the project's wrangler.jsonc:
| Port | Flag | wrangler.jsonc key | Neither |
|---|---|---|---|
| Worker | --worker-port | dev.port | the first free port at or above 8787 |
| Inspector | --inspector-port | dev.inspector_port | wrangler's own default: 9229, probing upward |
// wrangler.jsonc — the project-level equivalent of the two flags
{
"dev": {
"inspector_port": 9235,
"port": 8788,
},
}Pin the inspector in a repo that runs several Workers side by side. Left unset it starts at 9229 and climbs while ports are busy, so it eventually lands on a port a sibling worker pinned — and the worker that dies is whichever bound second, which makes the failure non-deterministic and the port in the error message impossible to grep for.
--inspector-port is wrangler dev only. On the Vite flavors the inspector
belongs to @cloudflare/vite-plugin: pass it through the plugin instead —
lunora({ cloudflare: { inspectorPort: 9235 } }) — and for the SvelteKit /
Nuxt worker sidecar pin dev.inspector_port in wrangler.dev.jsonc, the
config that sidecar runs. lunora dev says so rather than dropping the flag.
Sharing the dev server: --tunnel
--tunnel puts the Worker on a public https://<random>.trycloudflare.com URL
through a Cloudflare Quick Tunnel
— for a webhook provider, a phone on another network, or a colleague. It needs
cloudflared
2026.9.3 or newer on your PATH; no Cloudflare account is needed on either
side. The URL is new on every run.
lunora dev --tunnel # PUBLIC: anyone with the URL gets in
lunora dev --tunnel --allow-mail you@example.com # only you, after a one-time PIN
lunora dev --tunnel --allow-mail a@example.com --allow-mail b@example.com
lunora dev --tunnel --allow-mail 'a@example.com,b@example.com'
lunora dev --tunnel --allow-mail '*@example.com' # anyone at that domainProtection is your call, and it is off unless you ask for it. Without
--allow-mail the tunnel is public and lunora dev prints a warning saying so.
With it, each --allow-mail value is passed to cloudflared as
--allowed-mail (a single address, a comma-separated list, or *@domain, and
the flag repeats). Values are trimmed and empty ones dropped, so
--allow-mail "" does not count as protection; an entry without an @ is
refused. A visitor then proves one of those addresses with a one-time
PIN sent to the inbox before any request reaches the dev server. Access ends
for everyone when lunora dev stops.
PIN sign-in needs a browser, so a webhook sender or other non-interactive
client cannot get through a protected tunnel. Use a public one for that, and
stop it when you are done.
What gets tunneled:
- The Worker, never Studio. On the wrangler flavor Studio has its own port,
and that port is not tunneled. On the Vite flavors Studio sits on the same
origin at
/__lunora, and its transport guard refuses forwarded requests, which is every request through a tunnel. LeaveLUNORA_STUDIO_ALLOW_FORWARDEDunset. - On the Vite flavors, the URL Vite actually listens on. Vite blocks hosts
it does not know. If the tunnel URL answers 403 ("Blocked request"), add
server: { allowedHosts: [".trycloudflare.com"] }tovite.config.
The tunnel is best-effort. If cloudflared is missing or older than 2026.9.3,
lunora dev prints the install link and runs without a tunnel. It does the
same if cloudflared exits before assigning a URL. cloudflared runs with
--output json, and the URL is read from its log lines. cloudflared is
started directly, without a shell wrapper, so stopping dev stops cloudflared
itself on every platform, Windows included. Quick tunnels are for development: Cloudflare caps each one at
200 in-flight requests, and they do not support Server-Sent Events.
The URL is also recorded in .lunora/dev.json as tunnelUrl.
lunora dev status shows it (and --json carries it), and
lunora dev --background --tunnel prints it once cloudflared reports it. That
includes a Vite project, which then runs through the lunora dev daemon, so
there is a process that owns cloudflared.
lunora doctor does not check the cloudflared version. lunora dev --tunnel
checks it when it starts.
Background mode (AI agents)
--background starts the dev server as a managed detached process: the
command blocks until the server accepts requests, prints the URL + PID, then
returns. A state record at .lunora/dev.json acts as a lockfile: starting
again while a server runs reports the existing instance instead of spawning a
conflict, and stop / status / logs resolve the running instance from it.
Every subcommand is idempotent: stopping when nothing runs succeeds silently.
lunora dev --background # detach; blocks until ready, prints URL + PID
lunora dev status # URL, PID, uptime (add --json for a machine-readable doc)
lunora dev logs # captured output of a background run (--lines n, 0 = all)
lunora dev stop # SIGTERM, SIGKILL escalation after 10s; clears the recordFiles a supervisor reads
lunora dev writes into the gitignored .lunora/, and names in its startup
banner, whichever of these it produced:
| File | Carries |
|---|---|
.lunora/dev.json | live state — URL, PID, and readyAt once the server first answers |
.lunora/dev-bindings.json (default) | the binding manifest, plus the origin it serves on |
The manifest path is a default, not a fixed location — --emit-bindings <file>
writes it elsewhere. And it is skipped entirely for a project with no readable
wrangler.jsonc, since there is nothing to derive it from. So poll for it with
your own timeout rather than blocking forever on a file this project may never
produce; the banner names the path that was actually written.
readyAt is what separates "the process exists" from "it is accepting
requests" — the rest of the record is written before anything is listening.
lunora dev status reports it as ready or starting, and --json carries
ready / readyAt, so a task runner can gate a dependent step on a fact rather
than a guessed sleep. A missing readyAt means not ready yet, never never.
Naming a path with --emit-bindings also makes a derivation failure fatal, where
the default write skips quietly: a named path means something is waiting on it.
See Monorepos and external IaC for the full
supervisor workflow.
When an AI coding agent is detected (Claude Code, Cursor, Codex, Gemini CLI,
Cline, …) background mode and JSON logging turn on automatically, so agent
workflows need no flags. Set LUNORA_AGENT_MODE=0 to opt out (or =1 to
force it). Agents can also poll GET /_lunora/status on the running worker, a
public, secret-free health probe answering {"ok":true}.
JSON log lines are available to everyone via lunora dev --json or
LUNORA_LOG_JSON=1.
lunora deploy
Pass --lazy-functions to regenerate and deploy a lazy function registry.
Without it or codegen.lazyFunctions in lunora.config.ts, codegen emits an
eager registry even if an earlier dev or codegen run used lazy mode. --prebuilt
skips regeneration and keeps the existing output.
lunora deploy and lunora build evaluate every module the Worker loads on demand
in workerd (wrangler dev --local) before anything ships, so a module that throws on
load fails the command instead of the first request. That covers every lazy function
module with --lazy-functions, and in every build the modules the generated app loads
on its first event: _generated/authModule.ts (@lunora/auth), the OpenAPI, OpenRPC
and architecture documents, and live-stream and workflow-event modules. An app with
none of them skips the check. lunora prepare runs the same check, so a CI gate sees
it too. The check reports how many functions and modules it covered and names each
failing module with its file. It blocks in three cases:
a module that fails to load; a Worker that does not start, whether the entry is broken
or local wrangler dev cannot run the project (a remote-only binding); and a Worker that starts and then fails, or answers with something other than
the check's result, which usually means a route sends /_lunora/* to the assets instead
of the Worker. It warns and continues when the check cannot run at all (a virtual main,
a target that is not workerd, declared containers, which wrangler dev would build locally,
an assets directory the client build has not written yet, or a Hyperdrive binding with no
local database). It catches what evaluation raises: a
top-level throw, or a call on an import that is undefined. A circular import that never
throws during evaluation is not caught, because the bundler hoists it. Pass --no-smoke-load
to skip it.
The same check, in eager builds too, evaluates every installed package the Worker
loads with a literal import(). Those are mostly the integration SDKs handed over as
loaders (playwright: () => import("@cloudflare/playwright"), or a payment client or
Hyperdrive driver that imports stripe, postgres or mysql2/promise inside it), which
load on first use, so an SDK that throws while evaluating in workerd would otherwise fail
its first request. It finds them in the files the Worker loads, starting from the entry;
an eager app with no such import() is not checked. An SDK a package loads for itself
(the MCP SDK inside @lunora/mcp) is not covered, and a project the check skips (see
above) is not checked at all.
The check evaluates one step per request, so one that never settles is named in the error
(did not finish evaluating import("stripe")), and a Worker whose runtime never starts
fails at once with wrangler's error lines. A project built by the Cloudflare Vite plugin
(TanStack Start, React Router and the like) leaves .wrangler/deploy/config.json behind,
and its entry only builds inside Vite. For such a project the check runs against the
source wrangler.jsonc and stubs the Durable Object and Workflow classes, so the modules
are evaluated but the entry itself is not; that entry is the Vite build's output.
Runs codegen, validates wrangler.jsonc, then invokes wrangler deploy.
Pass --migrate to apply pending data migrations against the live worker
immediately after a successful deploy. It also requires --migrate-yes (an
explicit confirmation; there is no environment variable for it), an admin token
(--migrate-token or LUNORA_ADMIN_TOKEN), and --migrate-url unless this
checkout is linked for the same --env. All three are checked before
wrangler deploy, so a missing one aborts the deploy rather than skipping the
migration.
lunora deploy
lunora deploy --env staging
lunora deploy --migrate --migrate-yes --migrate-url https://app.example.com --migrate-token $LUNORA_ADMIN_TOKEN
lunora deploy --temporary # no Cloudflare account needed
lunora deploy --dry-run # run every pre-deploy gate, publish nothing
lunora deploy --health-check # …then prove the new version answersYou don't need a Cloudflare account to try a deploy. --temporary ships to a
temporary account (wrangler deploy --temporary): the Worker is live for about
60 minutes, then you either claim it into an account or it's deleted. An account
is only required to keep a deployment. (Wrangler errors if you're already
authenticated, so drop --temporary once you've signed in.)
--dry-run runs the full pre-deploy pipeline (codegen, the schema-drift gate,
wrangler.jsonc validation, and the wrangler bundle) without publishing.
A successful deploy auto-writes .lunora/project.json (see lunora link) from
the deployed URL, so follow-up commands don't need --url. Every real deploy
re-checks it: if the URL you just published to disagrees with the recorded one
(a custom domain added, the worker renamed), the deploy warns and keeps the
recorded value rather than rewriting an explicit lunora link. Run
lunora link --url <new> to accept the change. --temporary never writes a
link, since that account is gone in an hour.
--preview is refused. Cloudflare gives a Worker that implements a Durable
Object no version preview URL, and a version shares production's Durable
Objects, D1 and R2. Deploy an isolated copy with
lunora preview deploy <name> instead.
Cloudflare CLI (cf)
Lunora manages wrangler.jsonc and deploys with Wrangler. It does not support
Cloudflare's beta cf CLI yet (#964).
cf resource commands (zones, DNS, KV, …) are fine next to a Lunora project, but
don't run cf dev, cf build or cf deploy on one: they read
cloudflare.config.ts, which Lunora never updates, so the bindings, Durable
Object classes and migrations Lunora adds would be silently missing. When a
cloudflare.config.{ts,mts,js,mjs} sits in the project root, lunora deploy,
lunora codegen, lunora dev (including --background) and the Vite and
Rspack plugins (on dev and build alike) warn once per process tree, and
lunora doctor reports cf-config-present on every run. The warning never
blocks: nothing lunora deploy runs reads the file.
--health-check
After a live deploy, probe the new version's health route
(/_lunora/health/ready, falling back to /_lunora/health on deployments
without a readiness gate) and fail the command when it never answers. Five
attempts, two seconds apart. A fresh version takes a moment to propagate, and a
fixed ceiling is what a CI timeout can be set against.
It is opt-in on purpose: a worker whose health route is admin-gated or unreachable from the runner must still be deployable, and a default-on network step would turn a good deploy into a red build for an unrelated reason.
A red probe exits non-zero and says which half failed: the deploy succeeded,
the probe did not. The probe runs before --migrate, so a worker that can't
serve is never migrated.
For a host behind Cloudflare Access, set CF_ACCESS_CLIENT_ID and
CF_ACCESS_CLIENT_SECRET to a service token that a Service Auth policy on the
Access application allows. The probe sends them as CF-Access-Client-Id /
CF-Access-Client-Secret on each https:// request, and
lunora verify --health-url does the same. The token goes only to the probed
host and never over plain http://. The one redirect the probe follows is an
http:// URL redirected to the same URL over https:// (Cloudflare's "Always
Use HTTPS"), and the token is sent on that hop. Any other redirect fails the
probe. A redirect to the Access login page is reported as Access, with what to
set, rather than as a deployment that did not answer. A token value with a line
break or another character a header cannot carry stops the probe before any
request, naming the variable but not its value.
Machine-readable output
--format json writes exactly one JSON document to stdout (every human line,
including wrangler's own output, goes to stderr). It carries a deployment
object describing what this run put where:
{
"code": 0,
"deployment": {
"deployedAt": "2026-08-08T09:12:33.417Z",
"dryRun": false,
"env": "production",
"preview": false,
"url": "https://my-app.acme.workers.dev",
"workerName": "my-app",
},
"healthCheck": { "ok": true, "url": "https://my-app.acme.workers.dev/_lunora/health/ready" },
// …validation, schemaDrift, mintedSecretsFile
}dryRun and preview are always present, so a consumer can tell "nothing went
live" from "went live" without inferring it from a missing url. There is no
version id: the pinned wrangler has no structured deploy output, and
lunora cloudflare deployments list is the supported way to read one.
A release pipeline reads the URL out of the same document it already checks the exit code of:
set -euo pipefail
result=$(lunora deploy --env production --format json --health-check)
url=$(echo "$result" | jq -r '.deployment.url')
# The document is printed on failure too, and a failed deploy carries no URL —
# without this guard `jq` yields "null" and the smoke test requests null/api/smoke,
# so the pipeline fails at the wrong step.
if [ -z "$url" ] || [ "$url" = "null" ]; then
echo "deploy reported no URL" >&2
exit 1
fi
curl -fsS "$url/api/smoke"Deploying to Node (--target node)
The Node target has no hosted control plane, so lunora deploy --target node
deploys to a container build context instead of publishing anything. It runs
codegen for the target (into the configured schemaDir), bundles a generated
server entry together with the worker entry wrangler's main names into one
server.mjs with the project's own esbuild (applying the worker's wrangler define and alias to the app's
own code, but not to the generated server or to dependencies, unlike wrangler, so
a process.env define cannot rewrite the server's environment checks), and writes .lunora/deploy/node/:
| File | What it is |
|---|---|
server.mjs | The app on @lunora/platform-node: the app's own Durable Object bindings, the declared crons, ctx.secrets and Hyperdrive wired |
package.json | Only better-sqlite3, the one native module the bundle leaves out, at the version the project's platform-node runs (plus ws's optional bufferutil / utf-8-validate when the project installs them) |
package-lock.json | Resolved at deploy time with npm install --package-lock-only, so the image's npm ci installs the same tree on every rebuild; the deploy needs npm and registry access for it |
Dockerfile | Two stages on a Node LTS image pinned by digest: compiles better-sqlite3 from source, then runs as the image's node user |
.dockerignore | An allowlist: only package.json and server.mjs reach the builder, whatever else the reused directory holds |
README.md | The run command, the data volume and its permissions, the shutdown behaviour, and every environment variable the server reads |
Install esbuild and @lunora/platform-node in the project; the CLI resolves
both from there. --image <name> also runs docker build -t <name> on the
context when a Docker engine answers. Without one, or without the flag, the
command prints the build command and stops. Nothing is pushed to a registry.
--dry-run writes the context and builds no image. --image is refused for
any other target.
Refused before codegen writes anything:
- Framework projects. A worker produced by a framework build, either
main: "virtual:lunora/worker"composed by@lunora/viteor a Cloudflare adapter's output thatsrc/worker.tswraps, cannot be bundled, because this deploy runs no framework build. Pointmainat a hand-written worker entry that default-exports the fetch handler and exportsShardDO(the standalone template's shape), or deploy the app to Cloudflare. An entry that exports no default fetch handler or not every Durable Object class wrangler binds (an adapter's output with no composed wrapper) fails the bundle with the same advice. - Flags with nothing to act on:
--env,--migrateand its--migrate-url,--migrate-token,--migrate-yesand--migrate-allow-destructive,--health-check,--preview,--temporary,--emit-bindings, and--prebuilt, sincelunora buildandlunora preparenever generate for this target. - A malformed
secrets: anything but{ "required": [...] }listing environment variable names (a misspelled key such asrequireincluded), which would otherwise deploy a server missing those secrets. - A name declared twice on
env: a var, asecrets.requiredname, asecrets_store_secretsbinding, the Hyperdrive binding and the Durable Object bindings all share one namespace, so a repeat (a var namedSHARD) would silently replace another; the error names both sources. - A malformed binding entry: a
durable_objects.bindings,hyperdriveorsecrets_store_secretsentry without a valid name, orvarsthat is not an object of environment variable names. The error names the section and index; such an entry used to be dropped, leaving the worker anundefinedbinding. - A Durable Object binding whose name is not an identifier (
..,a/b): each binding's shards live in a directory of that name underLUNORA_DATA_DIR. - An app import of
bufferutilorutf-8-validatethe project does not install.wsloads them optionally and falls back without them. - A
secrets_store_secrets[]binding namedLUNORA_*, which the runtime reads as a plain string and which could therefore never start.
The server reads LUNORA_ORIGIN_URL (the public URL; required, because the
image binds 0.0.0.0), PORT (default 8787), HOST and LUNORA_DATA_DIR
(/data in the image), plus DATABASE_URL when the app declares a Hyperdrive
binding and one variable per secrets_store_secrets[] binding and
secrets.required name. It refuses to start while a secrets.required name or
DATABASE_URL is unset. Only declared names reach the worker's env, as on
Cloudflare: the wrangler vars, the secrets.required names, the
secrets_store_secrets[] bindings, and the runtime's own LUNORA_*, PORT and
DATABASE_URL. No other variable a container host injects (cloud credentials,
another service's token) is passed through env, so list every secret the app
reads in secrets.required. That is not a sandbox: process.env stays readable
to the app and every dependency in the same process, so inject only the
variables the app needs. A name that is both a secrets.required entry and a
secrets_store_secrets binding is refused, since the binding would replace the
plain secret. No secret value is written into the generated
files: secrets appear by name only. The wrangler vars are the exception by
design, bundled into server.mjs as defaults, so keep secrets out of vars.
Before it listens, the server re-arms every persisted alarm, so a restart does
not leave alarms unfired on shards nobody calls. Crons and scheduled jobs are delivered to the shard binding, the one whose class
is ShardDO (or LunoraDO), whatever it is named. The worker's scheduled()
export is never called, so a wrangler triggers.crons expression meant only for
it (a createWorker backupCron or crons job) does not fire; the deploy names
any it finds. A project whose @lunora/platform-node predates deadline-bounded
drains is refused, since every shutdown would fail on it. Wrangler vars are bundled as declared (a JSON object
stays an object) and a set environment variable overrides one as a string.
Every shard, the scheduler and the crons live in SQLite files under
LUNORA_DATA_DIR, so mount a persistent volume there (a bind mount must be
writable by uid 1000) and run one container per volume.
On SIGTERM or SIGINT the server stops accepting connections, waits for the
responses in flight at that moment to be written (a request still arriving on an
open connection gets a 503 and Connection: close), closes the listener (ending
event streams and WebSockets), then drains waitUntil work, alarms and cron runs
before closing the databases (each registry and the platform drained together
until all are idle, and each closed as its own step). The whole drain shares one deadline,
LUNORA_SHUTDOWN_TIMEOUT_MS (default 8000, under docker stop's 10 s grace; a
value that is not a whole number of milliseconds from 0 to 2147483647, the
longest delay a Node timer honours, is refused at startup);
work still running when it passes is logged by name and the exit code is 1. A
failed step is logged and the rest still run, and any fatal error during the
shutdown also makes the exit code 1. A second signal exits at once. waitUntil
failures, alarm and scheduled-job failures, a throwing fetch handler (logged by
method and path, never its query string), unhandled rejections and uncaught
exceptions are logged with their stack and cause; the last two also shut the
server down with exit code 1. If the process ends before the shutdown finished,
for any reason, it exits 1 and logs the step it was in.
The deploy warns, by name, about every declared binding the server does not
compose: static assets, queues, workflows, .global() tables, object
storage, mail, version_metadata, a Durable Object bound from another worker
(script_name), and any other binding section. The schema-drift gate does not
run.
lunora preview
An isolated copy of the app per pull request, and the way to remove it.
lunora preview deploy 123 # deploy, migrate, print the URL
lunora preview deploy 123 --seed # …then fill it with `lunora seed` data
lunora preview deploy 123 --secret RESEND_API_KEY # give it a secret from the environment
lunora preview deploy 123 --var AUTH_URL=https://my-app-preview-123.acme.workers.dev
lunora preview deploy 123 --dry-run # show the Worker, resources and env block, no API call
lunora preview delete 123 --dry-run # read the record, show what would go, change nothing
lunora preview list
lunora preview delete 123deploy <name> deploys a separate Worker, <worker>-preview-<name> (the name
is lowercased to letters, digits and dashes, and shortened with a hash past 63
characters), so it gets its own Durable Object namespace. Every D1 database,
KV namespace and R2 bucket the app binds gets a preview-owned one, named
<preview-worker>-<binding>. The deploy is the normal lunora deploy
pipeline under a transient env.preview-<name> block that clears production's
routes, custom domains and cron triggers and turns on workers_dev. The block is removed
from wrangler.jsonc when the command ends. The pipeline's data migrations run
against the preview, and --seed runs lunora seed against it afterwards. The
preview never touches the project link, the schema baseline, or the
architecture baseline.
Vars: production's vars and define are copied as they are. A value that
must differ in the preview, such as an auth base URL or a CORS origin, is set
with --var KEY=VALUE (repeatable). The preview's URL is known before the
deploy: https://<preview-worker>.<your-subdomain>.workers.dev.
Secrets: the preview gets a minted value for every secret Lunora can generate
(its own LUNORA_ADMIN_TOKEN, AUTH_SECRET, …), uploaded with the deploy.
Cloudflare secrets cannot be read back, so each deploy mints new values, which
signs out a preview's sessions. Set LUNORA_PREVIEW_SECRET_SEED to any long
random string and the values are derived from it, the preview Worker and the
key instead, so they stay the same across deploys. A provider key is copied
only when you name it with --secret KEY, and the value is read from the
environment variable of the same name. Production's values are never read.
The scaffolded GitHub job passes the seed to the step that builds a pull
request's code. That job already holds CLOUDFLARE_API_TOKEN, which can
redeploy any preview with any secrets, and it runs only for pull requests from
the same repository (never forks), so the seed gives that code no access it
lacks. Do not run previews for untrusted pull requests: anyone whose code runs
in the job controls the account's previews.
What a preview owns is recorded in the account, in a KV namespace called
lunora-preview-registry, one record per preview, written as soon as each
resource exists. That way a fresh CI runner can delete it. A deploy and a
delete of one preview never overlap, wherever they run: each takes a hold,
a row in a small D1 database called lunora-preview-locks that the preview
commands create on first use and use for nothing else. The row is inserted
atomically (a second taker gets a constraint error), a hold older than 30
minutes is taken over by an update that only one taker can win, and a run lets
go by deleting its own row. Any other failure while taking the hold refuses the
run. The record names each resource before it is created and confirms it after,
so a resource whose confirming write failed is taken back at once by the id its create returned. delete removes only what the record proves it made: a confirmed entry whose id still names a resource of the recorded name. An entry that is only claimed (a deploy was killed between creating it and confirming it) is never deleted by name, since whatever carries the name may be another actor's; it is reported and stays on record until you look. delete also refuses to
report "no record" while the preview's Worker or a resource under its names is
still in the account (a record this location has not seen yet, or an app id that
differs from the one that deployed it), and exits 1 instead. A record is keyed by
the project's id, lunora.appId in package.json, not by the Worker's
name: the first local lunora preview deploy writes the id (commit it), a CI run refuses to
mint one because its checkout is discarded, and two apps that share a Worker
name never see each other's previews. Renaming the Worker leaves existing
previews findable, and delete removes them under the name they were made
with. A preview recorded under the Worker name, from before projects had an id,
is re-keyed the next time you deploy or delete it (not by delete --dry-run, which changes nothing) (list shows it with a
note); without an id in package.json that is refused with the line to add. delete <name>
deletes the preview Worker (with its Durable Objects) and then each recorded
resource. It refuses a preview with no record, a record whose Worker is not the
derived preview name, a record that names any id or name production's config
(any environment) uses, and a record whose ids no longer name the resources it
lists. A deploy never adopts an existing resource that
has a preview name but no record. The preview Worker carries a LUNORA_PREVIEW
var (<worker>/<name>): a deploy refuses to replace a Worker with the preview's
name that lacks it, and delete refuses to remove one. An R2 bucket is emptied before it is
deleted. A resource that cannot be deleted stays on record for the next
delete.
An app that binds anything a preview cannot isolate yet is refused with the
list: Hyperdrive, service bindings, queues, workflows, Vectorize, Analytics
Engine, the analytics (Analytics SQL) binding, which reads the account's datasets, send_email, which would send mail through production's sender, containers, Artifacts, lunora.config services, a Durable Object on
another Worker's script_name, a singular route, an R2 bucket with a
jurisdiction, a binding that exists only inside an env.<name> block when no --env is given (a preview is otherwise planned from the top-level config, which would lack it), or any binding kind the CLI does not know.
--env <name> plans the preview from that Wrangler environment instead, the way Wrangler builds it for lunora deploy --env <name>: the top level's settings (entry point, compatibility date and flags, assets, migrations) with the environment's own laid over them, and only the vars and bindings the environment declares, since an environment does not inherit those. The preview Worker is named from the environment's own name (else <name>-<env>), so a binding that lives only in env.<name> gets its own preview copy. An unknown name is refused with the list of valid ones. The environment is recorded with the preview, so delete removes exactly what was created. Only the account it is looked up in is not recorded: when an environment names an account_id other than the top level's, pass the same --env <name> to list and delete (or set CLOUDFLARE_ACCOUNT_ID); without either they refuse rather than guess the account. The scaffolded CI pipelines leave it unset. A secrets.required
entry has to be passed with --secret; the preview refuses before creating
anything otherwise. Copying any of these would point the preview
at production's resource.
A preview name that needed cleaning (foo_bar, Foo-Bar) gets a short hash
of the original appended, so it never shares a Worker, record or resources with
foo-bar; a name already in the alphabet, such as a pull request number, is
used as it is. A production LUNORA_ORIGIN_URL var is replaced by the
preview's own URL (the scheduler dispatches to it); --var still overrides. The
URL the preview is recorded and migrated under is built from its Worker name
and your workers.dev subdomain, never read from wrangler's output. The
lunora-preview-locks database is only used when it carries a marker table
the preview commands write when they make it; a database of that name that
did not come from them is refused and never written to. A hold is renewed while
a run works, an interrupt (Ctrl-C, a cancelled CI job) puts the config back and
removes the secrets file before the process exits, and delete empties a
bucket of any size, refusing (and keeping the bucket on record) an object whose
key has a . or .. segment, since that cannot be addressed without leaving the bucket.
It needs CLOUDFLARE_API_TOKEN with Workers Scripts, D1, Workers KV Storage
and Workers R2 Storage edit permissions, plus CLOUDFLARE_ACCOUNT_ID (or
account_id), and a registered workers.dev subdomain. For CI, create a custom
token (My Profile > API Tokens > Create Custom Token) with only those four
Account permissions and Account Resources limited to the one account, never the
production token. Cloudflare cannot limit a token to the preview-named
resources, so on GitLab, where the token is Masked but not Protected and so
readable by anyone who can push a branch, that person can edit or delete every
Worker, D1 database, KV namespace and R2 bucket on the account. If production
shares the account, give previews an account of their own. It works on Cloudflare
only. celld has no Wrangler environments, so deploy a separate config with its
own CELLD_BUCKET instead. The Node target deploys as a container, which has
no isolated previews: run a second container on its own data volume instead.
lunora build
Pass --lazy-functions to generate lazy imports for the bundle. Generation is
eager by default unless codegen.lazyFunctions in lunora.config.ts enables it. Use lunora deploy --prebuilt to keep that generated registry
in a later deployment. Lazy imports do not make the upload smaller: wrangler
bundles with a single output and no code splitting, so the import() targets are
inlined, and the bundle is somewhat larger than the eager one. The change is in
when modules are evaluated, not how many bytes are uploaded.
Every build also smoke-loads the modules the Worker loads on demand in workerd first: lazy function modules, the auth module, API spec documents, and packages loaded with import() (see lunora deploy); pass --no-smoke-load to skip it.
After bundling, build profiles the Worker's startup: three wrangler check startup runs on the
exact upload form the dry run wrote, reported as their median "Active" time. Cloudflare rejects a
Worker whose global scope takes more than 1 s of its CPU to evaluate (error 10021), and nothing
before the upload says so. Above 200 ms of local CPU the line becomes a warning that names the
startup CPU limit page, and for an eager build,
--lazy-functions. The 200 ms line is a heuristic: how laptop CPU maps to Cloudflare's is unknown,
and local profiles of 0.4–0.7 s have been rejected. It never fails the build. It is skipped, with a
debug line, when wrangler cannot run or wrote no upload form; --no-startup-check skips it. A
plain lunora deploy does not profile, because wrangler bundles and uploads in one step there;
wrangler profiles a rejected upload itself.
Runs the full pre-deploy pipeline (codegen, the schema-drift gate, wrangler.jsonc
validation) and writes the bundled Worker to disk without publishing
(wrangler deploy --dry-run --outdir). This is the build half of a build/deploy
split: produce a verified artifact in one CI step, then ship it with
lunora deploy --prebuilt in another.
lunora build # bundle to .lunora/build
lunora build --out-dir dist-workerlunora deploy --prebuilt skips codegen + the schema-drift gate (trusting the
prior build, which writes the client output; prepare builds no client output);
wrangler still bundles the Worker.
Before wrangler runs, build and deploy run the project's client build when wrangler would
otherwise read a stale or missing output: rsbuild build or vite build, picked
from the rsbuild.config.* or vite.config.* file. A worker whose main is
virtual:lunora/worker (the Vite-generated class-A entry) is always built with Vite, even
when an rsbuild config also exists. A framework with neither config (Astro, Nuxt) runs its
project build script through its package manager. It runs when main is
virtual:lunora/worker, when the framework is class A or B, or when assets.directory is
set, including in the --env block being deployed. A build script consumes none of the
plugin's settings, so --api-spec and --target apply to the deploy's own codegen. Pass --no-framework-build to skip
it and bundle what is already on disk. Edits the client build makes to
wrangler.jsonc are rolled back, so build leaves the committed config alone.
deploy --prebuilt never runs it, because that artifact was built earlier.
--api-spec is refused when the build runs: set it in the plugin config instead.
--target is refused only when it names a target other than the project's.
lunora link
Records the deployed Worker's name + public URL in a gitignored
.lunora/project.json, so commands that target a live worker stop needing
--url on every invocation.
lunora link --url https://my-app.acme.workers.dev
lunora link --url https://my-app.acme.workers.dev --env production
lunora link --removeOnce linked, lunora run, lunora logs, and lunora deploy --migrate resolve
the worker from the link automatically. The bulk / destructive commands
(export, import, migrate, backup, seed, insights) use the link only
under --prod, so a production link never silently becomes the target of an
unguarded write. The link carries only public identifiers, never secrets.
Calling a function that requires a signed-in user
lunora run sends an anonymous RPC. Any app that configures authorizeShard
(the recommended posture) default-denies that, so the call comes back
FORBIDDEN_SHARD no matter what you pass.
--as is the way through: it dispatches via the admin-gated runAs op, which
forges the named identity for that one call, so the function and any RLS
middleware observe that user instead of an anonymous caller.
lunora run messages:list --as user_123
lunora run messages:list --as user_123 --claims '{"org":"acme"}' # extra identity claimsIt needs the admin bearer, resolved in this order: --token, then
LUNORA_ADMIN_TOKEN, then .dev.vars. The last applies only to a loopback
target, so a dev secret is never sent to a deployed worker. Against your own dev
server that means no flags at all.
Identity forging is admin-gated, refuses to target reserved admin functions, and is recorded in the shard's audit trail. Treat the admin bearer accordingly.
lunora cloudflare
Tools that only apply to an app deployed to your own Cloudflare account. Lunora
also deploys to Node and celld hosts, where they have no meaning: on such a
project every tool refuses and names the host in use (or the --target flag
that chose it). The host comes from --target, then target in
lunora.config.*, then Cloudflare. lunora cloudflare on its own lists the
tools; lunora cloudflare --help shows every tool's arguments and options.
lunora cloudflare ai and lunora cloudflare ai gateway are accepted for
ai-gateway.
These commands used to be top-level (lunora containers, lunora deployments,
lunora ai gateway). The old names now exit 2 and print the new command to
run.
lunora cloudflare alerts
Usage alerts for a self-hosted Cloudflare account, so a runaway Worker or a
Durable Object loop shows up in your inbox instead of on next month's invoice.
lunora cloudflare alert works too. Walkthrough:
Protect yourself from a runaway bill.
lunora cloudflare alerts # last month's usage + which products have an alert
lunora cloudflare alerts setup --email ops@example.com --dry-run # the plan, nothing written
lunora cloudflare alerts setup --email ops@example.com --yes # create / update the alerts
lunora cloudflare alerts test # what Cloudflare has delivered so farIt calls the Cloudflare API with CLOUDFLARE_API_TOKEN (a wrangler login
session is not reused) on the account from CLOUDFLARE_ACCOUNT_ID or
wrangler's account_id. The token needs Notifications Write for setup
(Notifications Read is enough for status and test) and Account
Analytics Read for the usage history; a refusal names the missing one.
| Subcommand | What it does |
|---|---|
status | Default. Last calendar month's usage for Workers requests and CPU, Durable Objects requests, duration and rows, and D1 rows, and which enabled usage alert covers each. |
setup | A Usage Based Billing notification for Workers requests and Durable Objects requests at --multiplier (default 3) × last month, never below the included allowance. |
test | Each webhook destination's last delivery and failure, and the notifications Cloudflare sent for these policies. It sends nothing: Cloudflare's API has no test-send endpoint. |
setup options: --email <address> and --webhook <destination-id> (each
repeatable, at least one required), --multiplier <n>,
--threshold <metric>=<n> (repeatable), --allow-floor,
--replace-recipients, --dry-run, and --yes (required when stdin is not a
TTY or with --format json).
- Product identifiers. The
productvalues come from the account when it offers them, and otherwise from the list Cloudflare documents in its Terraform provider (v4.52.0):worker_requestsand seven Durable Objects products. There is no usage alert for D1 or for Workers CPU time; for those the budget alert is the only guard. - Only request alerts are automatic. Durable Objects duration and storage
reads/writes are metered in units that cannot be matched to an analytics
reading, so
setupskips them unless you set a limit with--threshold do-duration=<n>(metrics:workers-requests,do-requests,do-duration,do-rows-read,do-rows-written). - Unreadable usage is not zero. When last month's usage cannot be read,
setupwrites no alert for that metric and exits1, rather than setting one at the floor that an already-busy account would trip every month. Pass--threshold, or--allow-floorto accept the floor anyway. - Re-runs are safe. Its policies are named
Lunora usage: <metric>and found by that name, so a re-run updates them in place. An update adds the new recipients to the existing ones (--replace-recipientsreplaces them; the plan and the prompt list what is added or removed). An enabled alert of your own on the same product is left alone; a disabled one does not count. - Limits are read back. Cloudflare does not document the unit of a usage
alert's limit. After writing,
setupreads each policy back and shows the limit Cloudflare stored, and it warns when your own alert's limit differs from its plan by 100× or more. - Budget alerts cannot be created or checked. The account-wide USD budget alert has no API; every subcommand prints where to make it: Manage Account > Billing > Billable Usage > Create budget alert.
- Usage notifications are offered to Pay-as-you-go accounts only; on an
ineligible account
setupexits4without writing.
lunora cloudflare ai-gateway
ctx.ai.model("<provider>/<model>") (for example "anthropic/claude-sonnet-5")
routes through Cloudflare AI Gateway
over the Workers AI binding. The gateway is the one named by
LUNORA_AI_GATEWAY_ID in the Worker's vars; without it, calls go through the
account's auto-created default gateway. lunora cloudflare ai-gateway gives
the app its own:
lunora cloudflare ai-gateway # gateway id = the worker `name` in wrangler.jsonc
lunora cloudflare ai-gateway --id my-gateway # explicit id
lunora cloudflare ai-gateway --no-logs # don't store prompts/responses in the gateway
lunora cloudflare ai-gateway --dry-run # print the plan; no API call, no file editIt creates the gateway over the Cloudflare API (or reuses it when the id already
exists on the account), then writes LUNORA_AI_GATEWAY_ID and
LUNORA_AI_GATEWAY_ACCOUNT_ID into the top-level vars of wrangler.jsonc,
keeping comments and formatting. Redeploy afterwards so the Worker sees them.
Credentials follow wrangler's non-interactive convention: CLOUDFLARE_API_TOKEN
(a token with the AI Gateway Write permission) and CLOUDFLARE_ACCOUNT_ID,
which falls back to the config's account_id. The binding is pre-authenticated,
so no gateway token is needed.
Log collection is on by default, matching the dashboard, so requests, costs
and errors show up in the gateway's logs. Those logs include prompts and
responses; pass --no-logs if they may carry data you must not store.
Caching and rate limiting are left off.
The gateway does not pay for third-party models on its own. Before the first
<provider>/<model> call, set one of these up in the dashboard:
- Unified Billing for OpenAI, Anthropic, Google, xAI, Groq and DeepSeek: load credits on the account (docs).
- A key stored on the gateway for other OpenAI-compatible providers (Mistral, Perplexity, OpenRouter, …) (docs).
lunora cloudflare containers
Thin wrappers over wrangler containers …, so container image and instance
management lives under the same CLI as the rest of the deploy workflow. The
split matters in CI: build and push the image in one step, then ship the worker
with lunora deploy in another.
lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1
lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push
lunora cloudflare containers push transcoder:v1
lunora cloudflare containers images list
lunora cloudflare containers images delete transcoder:v1build uses your local Docker engine; --push uploads to the Cloudflare
Registry in the same step. --env selects the Cloudflare environment. See
@lunora/container for declaring containers in the
first place.
lunora cloudflare deployments
Inspect deployment history and move traffic between Worker versions (wraps
wrangler versions / wrangler rollback):
lunora cloudflare deployments list # 10 most recent deployments
lunora cloudflare deployments status # live version and its traffic split
lunora cloudflare deployments inspect <version-id> # view a specific Worker version
lunora cloudflare deployments rollback --yes # roll back to the previous version
lunora cloudflare deployments promote <version-id> --yes # send 100% of traffic to a version
lunora cloudflare deployments promote <version-id> --percent 10 --from <live-version-id> --confirm-shared-state --yes
# send 10% to a version and keep 90% on the live one (partial rollout; both versions share one Durable Object database)rollback and promote change live traffic, so they require --yes. A partial
promote first reads deployments status and refuses when --from is not one of
the live versions, or when the live deployment cannot be read.
lunora cloudflare profile
Capture an on-demand CPU or heap profile from the live Worker, with no redeploy, and save it as a gzip-compressed pprof file:
lunora cloudflare profile # 10s CPU profile of the latest version
lunora cloudflare profile --type heap --duration-ms 30000 # 30s allocation profile
lunora cloudflare profile --version-id <version-id> --out cpu.pprof.gz
lunora cloudflare profile --namespace-id <id> --actor-id <64-hex> # one Durable Object instance
go tool pprof -http=: cpu.pprof.gz # view the flamegraphIt calls the Workers profile API, so it needs CLOUDFLARE_API_TOKEN with the
"Workers Scripts Read" permission and an account id (CLOUDFLARE_ACCOUNT_ID or
account_id in wrangler config). --duration-ms is 1000–50000. The capture
does not invoke your code: the target version must be loaded and receiving
traffic while it runs, and a Durable Object must be active. --env staging
profiles <name>-staging. A heap profile records allocations made during the
window, not retained memory. Set upload_source_maps: true in the wrangler
config so TypeScript function names are not mangled; the command warns if it
is missing. The same capture is available from the dashboard's Observability
tab (Flamegraph).
lunora prepare
Pass --lazy-functions to prepare a lazy function registry. The default is
eager generation unless codegen.lazyFunctions in lunora.config.ts enables
it. Keep the flag on a later deploy, set the config key so every command agrees,
or use deploy --prebuilt to skip regeneration.
Literally the same pipeline as lunora deploy, stopped before anything ships —
one implementation, so what prepare accepts is what deploy accepts. No Vite
step, no container image build, no wrangler invocation, no network traffic.
It runs, and fails on, every pre-deploy gate:
- codegen, its
postcodegenhook, and platform-portability diagnostics - ERROR-level advisories (CI-default;
--no-strict-advisoriesopts out) - the schema-drift gate — breaking schema changes with no new migration
- binding provisioning into
wrangler.jsonc - a placeholder D1
database_id, localhost origins invars, missing container sources, and an unavailable Docker daemon when Dockerfile containers are declared wrangler.jsoncvalidation
Earlier versions checked less than deploy did, so prepare could report "project is ready to deploy" for a project the deploy then refused. If you pinned
a CI job to the old behaviour, expect it to start failing on exactly the things the deploy would have.
lunora verify
Pass --lazy-functions to check the metadata requirements of the lazy registry
without writing files. Verification uses eager generation rules by default
unless codegen.lazyFunctions in lunora.config.ts enables the lazy registry.
Validates wrangler.jsonc, runs a codegen dry-run, and type-checks the
project with tsc --noEmit. Nothing is written to disk. Exits non-zero on
any error so you can gate merges on it.
The codegen dry-run applies all three of codegen's gates — portability
diagnostics, the schema-drift gate, and ERROR-level advisories — so a project
verify passes is one prepare and deploy accept. The advisory gate takes the
same --no-strict-advisories opt-out and the same CI-on/local-off default as
everywhere else.
Pass --env <name> to validate the env.<name> view of wrangler.jsonc, the
way lunora deploy --env <name> will. It matters for bindings: durable_objects
is not inheritable, so one declared only under env.production is invisible from
the top level, and a PR check without the flag validates a surface the deploy
does not use.
Part of the wrangler validation is a cross-check of every declared
durable_objects / workflows class_name against the worker entry's exports —
wrangler refuses to bundle a Worker whose classes are not exported, and that used
to surface only at lunora build. lunora doctor reports the same finding as
wrangler-class-unexported.
lunora migrate
Manages both schema migrations (D1 SQL) and online data migrations (row transforms that run against a live worker):
lunora migrate generate add_email_index # diff schema.ts → emit D1 SQL
lunora migrate create --name backfill_at # scaffold a data-migration stub
lunora migrate up backfill_at # run one data migration (dev)
lunora migrate up backfill_at --prod --url <url> # against production (requires --yes)
lunora migrate down backfill_at # run its `down` direction
lunora migrate status backfill_at # applied / pending / failedup, down and status each take the migration id declared in
lunora/migrations.ts — there is no "run everything pending" mode here;
lunora deploy --migrate is what iterates the declared ids in order.
generate parses lunora/schema.ts, filters to .global() tables (sharded
tables live in per-DO SQLite, so they need no migration), diffs against
lunora/migrations/.snapshot.json, and emits a timestamped SQL file. Commit
both the SQL and the snapshot: they are deterministic.
Apply the SQL with wrangler d1 execute <database> --file lunora/migrations/<file>.sql. It is a multi-statement file, so it is not a
@lunora/d1 Migration — that API takes one statement per entry. In practice
most of the file is redundant: the worker provisions every .global() table on
first use, idempotently and additively. What it will never do is drop or
retype, so the DROP TABLE / DROP INDEX statements and the hand-written
block under "NOT auto-generated" are the parts worth applying.
lunora migrate d1-to-hyperdrive
The third kind: a backend migration that copies .global() table data out
of a D1-backed deployment into a Hyperdrive-backed one, for when a project
outgrows D1. It is a guided orchestration over the admin export/import — it
streams the source's global rows to an NDJSON dump, imports them into the
target (whose .global({ backend: "hyperdrive" }) tables route the writes to
Hyperdrive), and verifies the row counts match. The blue-green flow: deploy the
new Hyperdrive worker alongside the old D1 one, then point the two legs at them.
lunora migrate d1-to-hyperdrive \
--from-url https://old-worker.example.workers.dev \
--to-url https://new-worker.example.workers.devThe two URLs must be distinct deployments: given one, both legs would
address the same database and the run would report "counts match" having done
nothing, so the command refuses. --from-token / --to-token each fall back to
--token (prefer LUNORA_ADMIN_TOKEN). --tables a,b limits the move to named
.global() tables (default: all of them), and --out <path> keeps the
intermediate NDJSON dump — without it the dump is staged in a private 0700
temp directory and discarded. Sharded tables are untouched: they live in
per-Durable-Object SQLite, not in D1.
lunora migrate hyperdrive-to-d1 is the rollback. It takes the same flags with
the Hyperdrive deployment as --from-url and the D1 one as --to-url. The
export/import does not care about direction, because the target's .global()
backend decides where the rows land.
The import is insert-only by default: a row whose _id already exists in the
target is reported as a conflict and left unchanged. On a rollback after
cutover, that means rows missing from D1 come back but edits made on Hyperdrive
to rows D1 still holds do not. Pass --replace to overwrite those rows with the
source's values (it keeps their _id and takes the source's _creationTime),
or keep the dump with --out and reconcile by hand. --replace writes like any
import, so a remote target still needs --yes. Neither mode deletes anything: a
row removed from the source since cutover is still in the target afterwards.
lunora run
Send a single RPC to a running Worker without spinning up the client SDK:
lunora run messages:send --args '{"channelId":"general","text":"hi"}'--shard overrides shard routing; --url lets you point at a deployed
Worker instead of http://localhost:8787.
lunora codegen
Set codegen: { lazyFunctions: true } in lunora.config.ts to enable
per-module lazy imports for the project. Codegen reads it on every run, so
codegen, dev, build, deploy, prepare, verify and advisor, dev watch
runs, Studio edits and the Vite and Rspack plugins all generate the same registry.
For a single run, pass --lazy-functions or set LUNORA_LAZY_FUNCTIONS to 1
or true in the shell (advisor has no flag). Any one opt-in enables lazy
imports; a false flag value does not override the config or an enabled
environment setting. With none enabled, generation stays eager.
Lazy mode moves a module's top-level failures from deploy time to the first call
that loads it: the upload check no longer evaluates procedure modules. build,
deploy and prepare evaluate them in workerd instead (see lunora deploy), so
--no-smoke-load hands that check back to your tests.
Runs codegen once and exits, the one-shot form of what lunora dev and the
Vite plugin do in watch mode. It reads lunora/schema.ts plus your function
files and writes lunora/_generated/.
lunora codegen
lunora codegen --api-spec both # also emit openapi.json and openrpc.json
lunora codegen --format json # machine-readable outputIt also keeps your linter and formatter skipping what it just wrote. lunora init offers this and lunora add re-applies it, which covers a project Lunora
scaffolded — but a codebase that adopted Lunora later runs neither, so nothing
ever told its ESLint / Prettier / Biome / oxlint about _generated/, and the
first lint after adoption buries the real findings under thousands of
generated-file errors. Detection is driven by the tools already in the project,
every writer is idempotent, and a config it cannot safely edit (an ESLint flat
config is arbitrary JavaScript; a monorepo-root config belongs to the workspace)
is printed for you to paste rather than rewritten.
--api-spec selects which API description to emit alongside the generated
modules: openapi (the default) writes openapi.json, openrpc writes
openrpc.json, both writes both, and none writes neither.
The success line names the files this run actually emitted, which is not a fixed
set: alongside the always-written modules, the per-feature ones (containers,
workflows, agents, queues, scheduler, seed, collections) are written only while
their feature is in use and deleted when it stops being, and the spec
artifacts follow --api-spec. Codegen output below describes
what each file is for.
lunora advisor
Scores your app's static advisor findings — the splinter-style schema, query and
security lints from @lunora/advisor — into a health map, so the trend is a
number CI can gate on rather than a wall of warnings:
lunora advisor # score the app, write lunora.advisor.map.json
lunora advisor --all # every procedure as a check matrix
lunora advisor --entry messages#sendMessage # inspect one procedure
lunora advisor --min-score 80 # exit non-zero below 80
lunora advisor --baseline # fail on any regression vs the committed map
lunora advisor --no-write # report only, write no artifactCommit the map: --baseline diffs against it, so a PR that makes the schema
worse fails even while the absolute score is still above --min-score. The same
findings drive the studio's Advisors tab.
lunora eval
Discovers every *.eval.ts under evals/ and runs it through its default-
exported run(), which calls evaluate / agentHarness from
@lunora/testing. Entirely in-process — unlike seed and insights it needs
no running worker:
lunora eval # run every eval, print the aggregate table
lunora eval --threshold 0.8 # non-zero exit below an average of 0.8
lunora eval --dir evals/support --format json # a subset, machine-readable--threshold is a global score gate in [0, 1]; an eval that exports its own
threshold wins over it for that eval.
lunora sdk
Generates a self-contained, typed client SDK for another language from the project's OpenRPC surface — transport included, so the emitted package has no Lunora runtime dependency:
lunora sdk generate --lang python # → ./sdk/python
lunora sdk generate --lang go --out ./clients/go # choose the output directory
lunora sdk generate --lang dart # Flutter-ready; live queries arrive as a Stream
lunora sdk generate --lang rust --from ./sdks # copy the transport from a local checkout--lang defaults to python; lunora sdk generate --help lists the registered
targets, and an unrecognised one is refused with the same list. The spec
defaults to ./lunora/_generated/openrpc.json, so run lunora codegen --api-spec openrpc (or both) first — --spec <path> points at another
document. The transport is
fetched at this CLI's own release tag so it matches the generated surface;
--ref overrides that and --from <dir> copies from a local directory of
per-language transports instead.
lunora insights
Reports per-function metrics from a running worker, ranked into three sections:
- Write-conflict hot-spots: functions that lose the OCC race most often. These are your sharding candidates: a high conflict rate means many writers are contending on one Durable Object.
- Error hot-spots: functions by error rate, with the most recent error message.
- Latency outliers: slowest single call, plus the mean, per function.
lunora insights # against the local dev worker
lunora insights --shard channel:demo # scope to one shard
lunora insights --limit 25 # more rows per section (default 10)
lunora insights --format json # raw report
lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKENTargeting production requires an explicit --url. See
Sharding for what to do about a write-conflict
hot-spot, and Performance for the latency side.
lunora profile
Captures an on-demand CPU or heap profile from a running Node-target app and
writes it as a gzip-compressed pprof file. Read it with go tool pprof, or load
it into Pyroscope or Speedscope.
The app serves the capture itself. It mounts createNodeProfileHandler from
@lunora/platform-node on a route it chooses, and that route is what --url
points at. There is no default URL for a Node app, so --url is required.
lunora profile --target node --url https://app.example.com/__profile
lunora profile --target node --url http://localhost:3000/__profile --type heap --duration-ms 30000
lunora profile --target node --url https://app.example.com/__profile --out cpu.pprof.gz--type cpu(default) samples the call stack for the window. The app has to be doing work during it, or the profile is empty. Functions V8 had already inlined before the capture began can appear under their caller rather than under their own name, so a long-running, warm app may show a caller where the work is done.--type heapreports the sampled allocations still alive when the window ends. Allocations freed during the window do not appear.--duration-msis an integer from 1000 to 50000 (default 10000).- The bearer is
--token, elseLUNORA_ADMIN_TOKEN. It must match the token the app passes tocreateNodeProfileHandler. The.dev.varsfallback applies to localhost only, as it does for the other admin commands. - Only one capture runs per app process. A second request gets
409until the first finishes.
On a project that deploys to Cloudflare the command refuses and points at
lunora cloudflare profile. A project with no configured target resolves to
Cloudflare, so the Node target must be passed with --target node, or set as the
target in lunora.config.
lunora reset
Clears local Miniflare state: the simulated Durable Objects, D1, R2, and KV
that lunora dev persists under .wrangler/state. This is the "start from an
empty database" button for local development; it never touches a deployed
worker.
lunora reset # clear Miniflare state (prompts to confirm)
lunora reset --all # also remove .lunora-cache
lunora reset --yes # skip the prompt (required when stdin is not a TTY)lunora env
Manage .dev.vars (local secrets) and push them to Cloudflare via wrangler secret:
lunora env list # list all keys in .dev.vars
lunora env get DATABASE_URL # read a single key
lunora env set FOO bar # write a key
lunora env unset FOO # remove a key
lunora env generate # generate strong values for the project's secrets
lunora env generate AUTH_SECRET --set # generate one and write it into .dev.vars
lunora env push # upload to Cloudflare (prompts unless --yes)
lunora env push --prod --yes # push to the production environment
lunora env diff # compare local .dev.vars keys against Cloudflare
lunora env doctor # validate .dev.vars against .dev.vars.examplegenerate mints cryptographically-strong values (32-byte hex). With no key it
mints every secret this project can generate locally (AUTH_SECRET, …); name
one to mint only that. By default it prints KEY=value lines on stdout — so
you can pipe them into wrangler secret put — and --set writes them into
.dev.vars instead. Minting replaces a value irreversibly, so --set refuses
to overwrite a key that already holds a live (non-placeholder) secret unless you
add --yes.
diff reads the deployed Worker's secret names via wrangler secret list
and reports which keys are local-only (need a push), remote-only, or in both.
Cloudflare never returns secret values (they are write-only), so diff
compares names, not values. Pass --prod to target the production environment.
lunora export / lunora import
Bulk data transfer between workers, mirroring Convex's convex export /
convex import:
lunora export --out ./backup.ndjson
lunora export --tables messages,channels --url https://my-worker.workers.dev --token $TOKEN
lunora import ./backup.ndjson
lunora import ./users.ndjson --table users # wrap bare docs as {table,doc} envelopes
lunora import ./backup.ndjson --mode upsert # overwrite rows whose _id already exists
lunora import ./backup.ndjson --mode replace --dry-run # what a full replace would add, overwrite, deleteAn export file is one { table, doc } row per line, then a last line, the end
marker {"end":true,"rows":N}, whose N is the number of rows before it. A
file or response cut on a row boundary is still valid NDJSON that reads as a
smaller export, so the marker is what proves it is whole: lunora export fails
(and keeps no file) when the response has no marker or a different count, and
lunora import of an NDJSON file refuses one with no marker, a count that does
not match the rows it read, or anything after the marker, before it writes a
row. Files written before the marker existed, and hand-written NDJSON, must end
with a marker line to import. The /_lunora/admin/import endpoint itself takes
bare rows, and applies the same check when a body does carry a marker. The
marker is not a row and is never imported. Backup snapshots, lunora seed
output and Studio's shard export end with it too.
--mode says what happens to rows the target already holds:
| Mode | A row whose _id is stored | A stored row the file lacks |
|---|---|---|
append (import default) | conflict, left as it is | kept |
upsert | overwritten, keeping its _id | kept |
replace | overwritten, keeping its _id | deleted |
require-empty (backup restore default) | refused before anything is written, if any of the file's tables holds a row |
Only the tables the file names are compared, so replace never touches a table
the file has no rows for (including an empty table in a backup). Its deletes
skip the schema's onDelete actions for the same reason: no cascade, set null
or restrict runs, so a row in a table the file leaves out keeps a reference to
a row replace removed. Delete triggers still fire, as insert triggers do for
every imported row, so a trigger that writes elsewhere still does. An _id held
by a different table is still refused. Every mode but append first reads the
target's rows for those tables and prints a plan, one line per table:
import plan (--mode replace):
users: 2 in file, 2 stored — 1 to add, 1 replaced, 1 to delete--dry-run stops there and writes nothing (it also prints the plan for
append). upsert with --yes skips the read: its plan only feeds the prompt,
and reading every stored row of a large table to count matches costs a full
export. A plan that overwrites or deletes a stored row asks before it writes;
without a TTY or under --format json it needs --yes, as does any target that
is not local.
replace is two passes and is not atomic. It writes every file row first
(overwriting existing ones), and deletes the rows the file lacks only after that
write came back clean. A run that fails part-way leaves the old rows plus what
was written, never fewer rows than before. Re-running the same command
converges: the write overwrites what already landed, and the deletes run once
it is clean. A reader between the two passes sees both old and new rows. The
plan is a read taken before the write, so require-empty and replace assume
nothing else writes those tables meanwhile: stop all writes to the target for
the duration of a replace import. The delete step removes the stored row
that currently holds each planned _id, not the version the plan read, so a row
a client updates between the plan and the delete is deleted with its newer
contents, and nothing detects it. Stop the app's writers (or take it offline)
before you run a replace, and start them again once it reports clean. The
worker has to support each mode; an older one is detected before any row is
sent.
lunora backup
Managed snapshot backups and native point-in-time recovery (PITR):
lunora backup create # snapshot the running shard
lunora backup list # list available snapshots
lunora backup restore <id> # restore a snapshot into empty tables (refused otherwise)
lunora backup restore <id> --mode replace --dry-run # what restoring over live rows would do
lunora backup restore <id> --mode replace # make each snapshot table hold exactly its rows
lunora backup retention # what a prune would delete
lunora backup prune # delete it — the only command that removes a backup
lunora backup pitr --at 2024-06-01T12:00:00Z # read PITR bookmark
lunora backup pitr --at 2024-06-01T12:00:00Z --restore --yes # restore to that pointcreate, list and restore write to a directory (--dir, default
.lunora-backups) or to an R2 bucket in your account (--bucket <name>,
--prefix, default prefix backups/). The snapshot is identical either way;
only the destination changes, and bucket traffic goes through the worker's
admin storage routes under the admin bearer, so the CLI holds no R2
credentials. restore --verify checks the snapshot's SHA-256 against the
manifest before importing anything, and fails when no checksum was recorded.
One invocation reads one destination: a bucket and a directory are never
merged into one listing.
lunora backup create --bucket default --tables users,messages
lunora backup list --bucket default
lunora backup restore 2026-06-01T12:00:00.000Z --bucket default --verifyA backup id is the ISO timestamp the snapshot was taken at
(2026-06-01T12:00:00.000Z). That is what list prints first and what
restore matches. The filename / object key is the same timestamp with :
and . swapped for -, because those characters are awkward in filenames
(lunora-backup-2026-06-01T12-00-00-000Z.ndjson). restore takes either: an id
it finds in the manifest, or a path/key you name directly.
A bucket-backed snapshot goes through the checksum-verified admin upload route,
which takes one body and caps it at 32 MiB. Above that create --bucket refuses
and names the workaround (--tables to narrow the snapshot, or --dir plus
wrangler r2 object put to move the file yourself). The alternative (the
signed-PUT fallback the blob importer uses for large files) is not
checksum-verified and needs URL signing configured, which is not what the copy
you restore from should depend on.
See Backups, export & import for the full picture: snapshot format, restore drills, and moving data between deployments.
lunora seed
Generates deterministic fake data from lunora/schema.ts and bulk-inserts it
through the worker's admin endpoint. Rows are derived from a seed number, so the
same --seed always produces identical ids and non-time columns. Columns named
like a timestamp (createdAt, expiresAt, …) are generated relative to the
wall clock, so a fixture that must be byte-identical across machines and CI runs
needs --now <epoch-ms> pinned alongside --seed.
lunora seed # every table, default 10 rows each
lunora seed --table posts --count 50 # 50 posts; FK parents seeded automatically
lunora seed --seed 7 --dry-run # print the NDJSON for seed 7, insert nothing
lunora seed --reset # wipe local .wrangler/state, then seedSeeding respects foreign keys: naming one table with --table also seeds the
tables it references. A required foreign key with no row to point at fails the
run with the column named; --allow-orphans gives it a dangling id instead.
--batch-size (default 500) sets rows per HTTP request.
Targeting a non-local worker needs --prod plus an explicit --url, and prompts
unless you pass --yes; prefer LUNORA_ADMIN_TOKEN over --token, which is
visible to other local processes through the process table. See
@lunora/seed for using the same generator inside tests.
lunora shards
Maintains the shard registry, the record of which shards hold .shardBy() rows
that cross-shard export, backups, CDC sync and migrations fan out to. A shard
registers when it first writes a table and is never removed on its own, so
fan-outs keep visiting shards that have since emptied. prune asks every
registered shard to drop its entry for each table it holds no rows of.
lunora shards prune --dry-run # list the empty registered shards, change nothing
lunora shards prune # remove them from the registry
lunora shards prune --tables messages # only the shards listed for `messages`Each shard checks its own rows, so a shard written during the prune keeps (or
regains) its entry. A shard the prune cannot reach keeps its entry too, and the
command exits 1 so you can re-run it. Needs a registry: an app without
.shardRegistry(...) gets a 400. See Sharding.
lunora pause / lunora resume
The incident switch. lunora pause stops the deployment doing work without a
redeploy, and lunora resume starts it again:
lunora pause --reason "bad migration, rolling back" # pause the dev server
lunora pause status # running, or paused since … — reason
lunora pause --prod --url https://app.example.com # pause production
lunora resume --prod --url https://app.example.comWhile paused, app function calls (/_lunora/rpc, batches, REST routes) and new
WebSocket, socket-route and voice connections answer 503 DEPLOYMENT_PAUSED
with a Retry-After and a fixed message; the --reason note is shown only to
operators (lunora pause status, Studio). A realtime socket opened before the pause keeps serving its
subscriptions until it reconnects; writes go over HTTP, so they are refused. Scheduled jobs stay where they are, with their attempt budgets
untouched, and run when you resume. Cron ticks are skipped and recorded as such,
and a raw crons handler is skipped too; the built-in scheduled backup still runs.
Queue messages are re-sent as delayed copies every five minutes with their
attempt budgets intact, so no pause length sends them to the dead-letter queue. A
message that cannot be copied (no producer binding or admin token, or a send that
fails or is too large) is retried with the same delay instead, which does spend
one of the consumer's max_retries. A Workers-for-Platforms tenant answers forwarded batches with
every message marked for retry. Calls carrying the admin token or an adminGate
grant keep working, so Studio, the CLI and health checks stay usable. Studio shows a banner on every page while
paused, and the Schedule tab has the switch.
A pause reaches every isolate within five seconds. The flag lives in the
deployment's SchedulerDO instance, which every app with a scheduler or a cron
has. An app without one gets 400 PAUSE_NOT_CONFIGURED. Jobs scheduled through
a separately named scheduler instance (a tenant scheduler, a workpool with its
own instanceName) are held too: each named instance registers with the main one
the first time it is used, pause and resume reach every registered instance,
and an instance first used during a pause starts paused. If some instance cannot
be reached the command fails with PAUSE_INSTANCES_FAILED and names them; the
main instance has already changed, and running the same command again reaches the
rest. A custom schedulerInstanceName must also be passed to createScheduler and
createWorkpool as primaryInstanceName. HTTP actions and SSR pages behind httpRouter,
and custom routes handlers, keep serving.
lunora admin-token
Creates, lists and revokes named admin tokens. A named token works wherever the
admin token does, except for root-only operations: token management, admin
WebSocket sub-tokens, storage signed URLs, runAs, point-in-time restore and
most auth admin writes. Each needs the root LUNORA_ADMIN_TOKEN.
lunora admin-token create ci-deploy --expires-days 90 # prints lnat.ci-deploy.<secret> once
lunora admin-token list # created / last used / expiry, never the secret
lunora admin-token revoke ci-deploy # refused everywhere within 30 secondsThe secret is shown only at creation; the store keeps its SHA-256 digest.
--expires-days must be a positive number. Revoking a token takes effect at once
on the isolate that served the revoke and within 30 seconds on every other.
lunora workflow
Starts a workflow instance or delivers an event to a waiting one, through the same
admin operations the Studio Workflows panel uses. The target workflow is the export
name in lunora/workflows.ts.
lunora workflow create onboarding --params '{"userId":"u1"}' # start an instance
lunora workflow create onboarding --id user-u1 # ... under an explicit id
lunora workflow send-event onboarding user-u1 approved --payload '{"by":"ada"}'create prints the new instance id and its initial status. send-event takes the
instance id and the event type positionally; the type must match a
defineWorkflowEvent declared in lunora/, and lunora:-prefixed types are
reserved. Both need the admin token (--token, LUNORA_ADMIN_TOKEN, or .dev.vars
for a local target) and exit non-zero when the worker refuses the call.
lunora introspect
Reads an existing Postgres or MySQL database and scaffolds lunora/schema.ts
from it, plus a list/get procedure module per table. Use it when you're
adopting Lunora on top of a database that already exists, instead of
transcribing the schema by hand.
lunora introspect --url postgres://localhost/shop # every base table
lunora introspect --tables users,orders # just these (reads $DATABASE_URL)
lunora introspect --dry-run # print, write nothing
lunora introspect --no-procedures --force # schema only, overwriteThe command is read-only against the source database: it queries
information_schema (and pg_index on Postgres) and never writes.
Re-runs merge, they don't clobber. The first run writes a whole
lunora/schema.ts; after that the file is yours, and a second run folds only
what's new (tables, columns, indexes) into it as additive edits, preserving
your formatting, comments, and any validator you tightened. That goes through the
same ts-morph editor the Studio schema editor uses, so two of its rules apply: a
column added to a table that already exists lands v.optional(...) (a required
one needs a backfill migration), and names that aren't bare identifiers are
reported and skipped. Nothing is ever removed: a column dropped upstream stays,
because deleting it would drop rows. Pass --force to overwrite instead of merge,
and --dry-run to see the plan first.
What it emits is a starting point you own, not a build artifact: review it before shipping. Specifically:
- Every table is
.global({ backend: "hyperdrive" }), because the rows live in the external database. Point theHYPERDRIVEbinding at it; see @lunora/hyperdrive. - Lunora mints its own
_id, so the source primary key is carried over as a unique index rather than replacing it. - Foreign keys become
v.id("<target>"); a type with no direct validator becomesv.any()with aTODObeside it, and is reported as a warning. - The emitted procedures are RPC-only. Publishing one over REST stays an
explicit
.expose({ rest: true })decision you make after adding whatever auth or RLS the table needs:introspectcannot know who may read your data. listis built ondefineListArgs, so only index-backed columns are filterable and paging is keyset-based. That bounds which columns a caller can reach, not the cost of every operator over them. Review the generatedfilterlist before exposing the procedure.
The driver is loaded on demand and is not a CLI dependency: install pg or
mysql2 in your project first.
lunora registry
Fetch and manage reusable Lunora components (queries, mutations, UI widgets):
lunora registry list
lunora registry view auth/session-token
lunora registry add auth/session-token
lunora registry build --from ./registry # regenerate the local catalog index.jsonlunora rules
Installs the Lunora agent skills into the project's .agents/skills/: they
are portable instructions that teach AI coding agents (Claude Code, Cursor,
Copilot) how to use Lunora. lunora dev, the Vite plugin, and the studio nudge
you to run this when the rules are missing.
lunora rules install # copy the skills into .agents/skills/ (skips files that exist)
lunora rules install --overwrite # reinstall, replacing every existing file
lunora rules check # report which skills are present
lunora rules check --strict # exit non-zero when missing (CI gate)lunora mcp
Connects AI editors to Lunora over the
Model Context Protocol. Where lunora rules
teaches an agent how Lunora works, this gives it live tools: documentation
search, dev-server status and logs, and typed access to your app's functions.
lunora mcp install # every MCP client already configured here
lunora mcp install claude-code cursor # or name them
lunora mcp install --list # supported clients and their config files
lunora mcp install --print # show the config without writing it
lunora mcp install --force # replace entries that already exist
lunora mcp install --docs-only # skip this project's local serverinstall writes two servers, and they go to different places by default:
lunora-docs, the hosted documentation server at https://lunora.sh/mcp,
is the same URL in every project, so it lands in the client's machine-wide
config; lunora, which runs lunora mcp serve for this app, only means
anything inside the project, so it lands in the project config. Pass
--global or --project to force both one way. Where a client only has one of
the two (Zed has no project config, VS Code no global one), it falls back rather
than skipping the client.
lunora mcp uninstall removes both again, from both scopes and every client by
default. It touches only the two entries Lunora wrote, leaving the rest of the file
and its comments alone. It knows each client's own
config file, top-level key, and entry shape, so you don't have to remember that
VS Code says servers where Cursor says mcpServers:
| Client | Config file |
|---|---|
claude-code | .mcp.json |
cursor | .cursor/mcp.json |
vscode | .vscode/mcp.json |
gemini | .gemini/settings.json |
claude-desktop | the OS application-data directory |
windsurf | ~/.codeium/windsurf/mcp_config.json |
codex | ~/.codex/config.toml (snippet printed to paste) |
Existing entries are left alone unless you pass --force, comments in a JSONC
config survive the edit, and a file that doesn't parse is reported rather than
overwritten.
lunora mcp serve is the stdio server those entries spawn; you rarely run it
by hand. It takes no required configuration: the dev server's URL comes from
.lunora/dev.json and the admin token from .dev.vars, both re-read per tool
call, so starting lunora dev after your editor is already open works without a restart. It
exposes the documentation tools, lunora_dev_status / lunora_dev_logs, and the
read-only deployment tools; --allow-writes adds the mutation and action tools.
lunora analyze
Runs a wrangler dry-deploy and sizes the source modules in the bundle from
wrangler's esbuild metafile, then reports the total, the heaviest modules, and
the modules under _generated/. Source maps are excluded from the total. A
pre-bundled entry writes no metafile, so the command falls back to listing the
largest output files and warns. Pass --format json to pipe the output to a CI
artifact; its topModules lists source modules, and breakdown says which
meaning applies.
lunora logs
Streams live logs from a deployed Lunora Worker by wrapping wrangler tail:
lunora logs
lunora logs my-worker --format json --status error
lunora logs --search "auth" --env stagingThe host comes from --target, then target in lunora.config.*, then
Cloudflare. celld and Node have no log tail, so on such a project logs refuses
instead of running wrangler tail.
Writing Lunora functions by hand
Queries, mutations, and actions are plain TypeScript files under lunora/.
There is no scaffolding command, so create the file yourself:
import { mutation, query, v } from "@/lunora/_generated/server";
export const list = query.input({ channelId: v.id("channels"), limit: v.optional(v.number()) }).query(async ({ ctx, args: { channelId, limit } }) => {
return ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
.order("desc")
.take(limit ?? 50);
});
export const send = mutation.input({ channelId: v.id("channels"), text: v.string() }).mutation(async ({ ctx, args: { channelId, text } }) => {
await ctx.db.insert("messages", {
channelId,
userId: ctx.auth.userId!,
text,
createdAt: Date.now(),
});
});After saving, lunora dev picks up the change and re-runs codegen
automatically. Run lunora codegen once manually if you are outside the dev
loop.
Codegen output
lunora/_generated/:
api.ts: the typedapi.<file>.<function>namespaceserver.ts:internalQuery,internalMutationexports re-typed against your schemadataModel.ts:Doc<"messages">,Id<"users">, etc.
These files are deterministic, so commit them. Nothing checks the committed
copy for you — verify runs codegen as a dry run and prepare overwrites it —
so gate it explicitly: lunora codegen && git diff --exit-code lunora/_generated.
API reference
The package also exports these for scripts and tests. The lunora binary does not
need them.
runCli(options?)
Type: (options?: RunCliOptions) => Promise<number>. Runs the lunora command
set against options.argv and resolves to the process exit code. Import it from
@lunora/cli.
RunCliOptions
Type: interface. argv is the command-line arguments to parse, cwd is the
project directory, and logger is a Console-compatible sink for output.
EXIT_CODE
Type: const. The exit codes lunora returns: SUCCESS (0), FAILURE (1),
USAGE (2), AUTH (3), PERMISSION (4), NOT_FOUND (5), CONFLICT (6),
RATE_LIMITED (7), UNAVAILABLE (8), MISSING_DEPENDENCY (9) and CANCELLED
(130). See Exit codes for when each one applies.
exitCodeForCode(code)
Type: (code: string) => ExitCode. Maps a Lunora error code to the exit code
lunora returns for it.