/lunora:lunora-migration-helperfrom Lunora
Plans and runs Lunora schema and data migrations using the widen-migrate-narrow pattern. Covers online migrations, D1 and Hyperdrive tables, and schema-drift gate bypass.
Ships in Lunora. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Change a Lunora schema that already has data in it without breaking the deploy or losing rows.
Not needed for a greenfield schema with no data, a new optional field, a new table, or a new non-unique index. Those are additive and deploy as-is.
Check the table's modifier in lunora/schema.ts first; the tools differ.
| Table | Where rows live | Structural DDL | Data backfill |
|---|---|---|---|
default (root) or .shardBy(key) | SQLite in the root / per-key ShardDO | Applied by the runtime from the schema | defineMigration + lunora migrate |
.global() | D1 (DB binding) | Additive DDL auto-provisioned; destructive SQL applied by hand | SQL UPDATE via wrangler d1 execute |
.global({ backend: "hyperdrive" }) | Postgres/MySQL via Hyperdrive | Additive DDL auto-provisioned; no migrate generate support | SQL UPDATE against the database |
The schema-drift gate blocks a breaking change; one that needs a backfill is let through once a new migration on that table covers it (the rest are listed below). Stage every such change across deploys:
v.optional(...), keep the old one. Make reads handle both, and start
writing the new shape on every insert/patch so rows created during the
migration aren't missed. Deploy.defineMigration, run it with
lunora migrate up, and confirm with lunora migrate status. On a
.global() table, backfill with SQL instead (see below).Prefer adding a new field to changing an existing field's type: it rolls back
cleanly. Keep a deprecated field as v.optional with a // deprecated: comment
until nothing reads it.
The gate (run by lunora deploy, prepare, build and, read-only, verify)
diffs the schema against the committed lunora/.lunora-schema.json.
.unique() column (existing duplicates would make the shard
fail to open)..shardBy() ↔ .global(), or the .global() backend), turning
on .memory(), or changing the jurisdiction. Move the rows with export → import,
then declare a migration whose literal covers names the change
(covers: { table: "users", shardMode: "shardBy:tenantId" }, { table, memory: true }
or { jurisdiction: "eu" }). An unrelated migration clears nothing. Where a table is
involved its up must rewrite rows (give each what its new home needs, e.g. its
shard key); one that returns the document unchanged covers nothing.covers: { table, ttl: { field, after } }), because the next sweep deletes
every row already past the cutoff; the blocked message counts those rows when
lunora deploy can read the worker. Refresh the column on the rows that must survive
in up..commitOrdered()
turned off, and a dropped index. A dropped index is refused only while a function
still names it through .withIndex("name"); point the query elsewhere first.A migration covers a change only if it is new since the baseline, its table
is a string literal naming the affected table, and its up does more than return
the document (the migrate create placeholder covers nothing). The baseline advances
only after a successful deploy.
A migration transforms one document at a time, runs inside each shard's Durable
Object in keyset batches, and is resumable: per-shard progress is kept in a
reserved __lunora_migrations table.
Scaffold it rather than writing the file from scratch:
lunora migrate create backfill-display-name --table users
This appends to lunora/migrations.ts. Codegen only discovers
export const x = defineMigration({...}) with a literal id. An
export default is silently skipped, and lunora migrate up then can't find it.
// lunora/migrations.ts
import { defineMigration } from "@lunora/server"; // or "lunorash/server"
export const backfillDisplayName = defineMigration({
id: "backfill-display-name",
table: "users",
batchSize: 200, // optional
up: (doc) => {
if (typeof doc.displayName === "string") {
return undefined; // skip: not rewritten, not counted as changed
}
return { ...doc, displayName: doc.name ?? "Anonymous" };
},
// optional; applied by `lunora migrate down`
down: (doc) => {
const { displayName, ...rest } = doc;
return rest;
},
});
The runner keeps each row's original _id and _creationTime.
The transform's second argument is a shard-scoped, read-only ctx.db
(get, findFirst, findMany, count), and the transform may be async.
That covers the common case of copying a field down from a parent:
up: async (doc, ctx) => {
const thread = await ctx.db.get("threads", String(doc.threadId));
return thread ? { ...doc, userId: thread.userId } : undefined;
},
To change rows in a second table, write a second migration over that table.
If the field is the table's .shardBy() key, a migration can't help: a row with
no shard key belongs to no shard (so the runner never sees it), and setting the
key would mean moving the row to another Durable Object. Re-key with
lunora export → rewrite the NDJSON → lunora import. A rewrite that adds, drops or splits rows must also update the last line, the end marker {"end":true,"rows":N}, to the new row count, or the import refuses the file. Ids are preserved, so
foreign keys survive. The same route applies to any shard-mode change.
lunora migrate up backfill-display-name --dry-run # preview, rewrites nothing
lunora migrate up backfill-display-name # against the dev worker (localhost:8787)
lunora migrate status backfill-display-name # per-shard progress
lunora migrate down backfill-display-name # only if `down` is defined
Options: --batch-size <n>, --steps <n> (cap batches per run), --format json.
Production runs rewrite live data, so they require an explicit confirmation:
LUNORA_ADMIN_TOKEN=… lunora migrate up backfill-display-name --prod --url https://app.example.com --yes
--url can be omitted when the checkout is linked to production. Alternatively,
lunora deploy --migrate --migrate-yes --migrate-url <url> runs every declared
migration right after the deploy (up is idempotent, so finished ones no-op).
.global() tablesThe runtime provisions .global() tables itself on first use, on both D1 and
Hyperdrive: CREATE TABLE IF NOT EXISTS, additive ADD COLUMN, and declared
indexes. Additive changes therefore need no DDL step.
For D1-backed global tables, lunora migrate generate diffs the schema
against lunora/migrations/.snapshot.json and writes a reviewable
lunora/migrations/<timestamp>_<name>.sql:
lunora migrate generate --name add_user_status
No command applies that file, lunora deploy included. Its value is the
statements the runtime never issues (DROP TABLE, DROP INDEX) plus a comment
block of changes it couldn't generate (renames, backfilling UPDATEs), which you
write yourself. Apply it deliberately, after review:
wrangler d1 execute DB --remote --file=lunora/migrations/<file>.sql
The file is multi-statement, so it is not a @lunora/d1 Migration. Commit
.snapshot.json with it, or the next diff won't see a dropped table.
Hyperdrive-backed tables are left out of migrate generate (it emits SQLite
DDL). Write destructive DDL for them by hand against your database. See
lunora-setup-hyperdrive-global.
defineMigration does not reach .global() rows on either backend: it runs
inside each shard's Durable Object against that shard's SQLite, never D1 or
Hyperdrive. Backfill a global table with a SQL UPDATE (D1: wrangler d1 execute; Hyperdrive: your Postgres/MySQL client). The drift gate still keys on
a migration naming the table, so once the SQL backfill is done, deploy the
narrowing change with --allow-schema-drift rather than a no-op migration.
lunora migrate d1-to-hyperdrive --from-url https://old-worker --to-url https://new-worker
--tables a,b limits it to some tables, and --out <path> keeps the
intermediate NDJSON dump. lunora migrate hyperdrive-to-d1 takes the same
flags and moves the data back, for a rollback. Both are insert-only by default:
a row whose _id already exists in the target is reported as a conflict and
left unchanged, so a rollback restores missing rows, not later edits. Add
--replace (with --tables naming the .global() tables; it is refused
without one) to overwrite those rows with the source's values, or keep the dump
with --out and reconcile by hand. This moves the data to another backend; any
reshaping still follows widen → migrate → narrow.
.collect()s
a large table runs into transaction limits and can't resume.
defineMigration batches per shard and resumes.table. table: TABLE_NAME covers nothing in the gate.--allow-schema-drift ships the shape for one run
without checking anything. lunora deploy reads the stored rows of the affected tables and
lets a change through only when every row already fits..shardBy() / .global() D1 / Hyperdrive).lunora migrate create <id> --table <t>; transform filled in; --dry-run looks right.lunora migrate up <id> (prod: --prod --yes); lunora migrate status <id> complete on every shard.migrate generate output reviewed and applied with wrangler d1 execute.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub anolilab/lunora --plugin lunora15 skills in this plugin
/lunoraRoutes general Lunora requests to the right Lunora skill and gives the shared mental model (codegen loop, generated `api`/`internal` references, review commands, add-on capabilities, the `@lunora/mcp` server). Use when the user asks which Lunora skill to use, gives an underspecified task in a project with a `lunora/` directory or `lunorash`/`@lunora/*` dependencies, asks to review or audit Lunora code, asks about an add-on without its own skill (queues, workflows, agents, AI, flags, payments, notifications), or wants to expose a deployment to an AI agent over MCP./lunora-cloudflare-auditAudits a Lunora app for Cloudflare cost and reliability risk before launch or after a surprise bill. Chains the read-only `lunora doctor`, `lunora advisor` and `lunora insights` signals, then traces what they cannot see — retry and fan-out loops, cron cadence, public routes that reach a metered product (Workers AI, Browser, Containers, Vectorize, R2, D1), preview environments with paid bindings, and missing usage alerts (`lunora cloudflare alerts`). Reports each finding with the billing meter it moves, the smallest fix, and how to verify. Use when the user asks to "audit before launch", "what could blow up our Cloudflare bill", "why did the bill spike", "is this safe to put on the public internet", or "review our cron / queue / AI / workflow cost". For a slow query or OCC conflict use `lunora-performance-audit`; for a failing deploy use `lunora-deploy`./lunora-create-packageBuilds a reusable Lunora capability, either as a registry item that `lunora add` / `lunora registry add` copies into an app's `lunora/`, or as a publishable `@lunora/*` workspace package in the Lunora monorepo. Use when the user wants to package schema + functions + wrangler bindings + env vars for other apps, add or edit an item under `registry/<name>/` (`registry.json`), run `vis generate lunora-package`, or wire a new `ctx.*` capability into codegen./lunora-deployDeploys a Lunora app to Cloudflare Workers + Durable Objects and gets wrangler.jsonc, remote resources and secrets to line up. Covers `lunora deploy` (and `--env`, `--dry-run`, `--migrate`), isolated per-PR previews (`lunora preview deploy | list | delete`), the `lunora doctor` / `lunora verify` / `lunora prepare` preflights, Durable Object bindings (SHARD, SHARD_REGISTRY, SCHEDULER), the `DB` D1 binding and its placeholder id, R2 buckets, production secrets (`lunora env push`, `wrangler secret put`) versus `.dev.vars`, the schema-drift gate, the architecture diff, and rollback with `lunora cloudflare deployments`. Use when the user asks to "deploy", "ship to production", "set up a staging environment", wire CI deploys, or when a deploy fails on a binding, a placeholder `database_id`, an unexported Durable Object class, a missing secret, or "schema drift gate blocked deploy"./lunora-functionsAuthoring rules for Lunora schema and server functions under `lunora/` — `defineSchema`/`defineTable`, `v.*` validators, the generated `query`/`mutation`/`action` builders (and `internal*`), indexes and `withIndex`, the `ctx.db` API, pagination, `ctx.db.related`, opt-in `ctx.*` capabilities, topics, modules, services, and `httpAction`. Use when writing or reviewing files in `lunora/` (`schema.ts`, function files, `http.ts`, `queues.ts`), when asked to "add a query/mutation/action", "add an index", "call one function from another", or "add a webhook endpoint", or when `lunora codegen` reports an error in a function./lunora-performance-auditDiagnoses and fixes Lunora performance problems — full-table scans and missing indexes, expensive `ctx.db.related` traversals, OCC write conflicts (409 `CONFLICT`), live queries that re-run too often, hot shards, and choosing `.shardBy(key)` or `.global()` to scale. Starts from measured signal (`lunora insights`) and static signal (`lunora advisor`, `@lunora/advisor` lints such as `filter_without_index`, `unbounded_collect`, `unindexed_foreign_key`, `hot_shard`). Use when the user says a query or page is slow, mutations fail with conflicts under load, subscriptions are chatty, asks to "audit performance", "add the right index", or "should I shard this table", or when the Studio Advisors tab or `lunora advisor` flags something.Other plugins' skills for the same job