Skip to content

fix: close the remaining findings from a third-party Convex migration - #241

Merged
prisis merged 18 commits into
alphafrom
fix/migration-findings-round-2
Jul 31, 2026
Merged

prisis merged 18 commits into
alphafrom
fix/migration-findings-round-2

Conversation

@prisis

@prisis prisis commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Closes the remaining findings from a large third-party Convex→Lunora migration report — the ones a first pass left open. Each was verified against this repo before being acted on.

The two that could lose data

Sharded export and import were unimplemented stubs that reported success. ShardDO's base runShardExport / runShardImport return [] and {conflicts:0,errors:[],inserted:{}}; the codegen subclass was expected to override them and never did. Both returns are success-shaped — indistinguishable from a correct export of an empty shard — so lunora backup on a .shardBy() schema succeeded and backed up nothing, and admin/import reported success and dropped every row. The sibling stubs in the same class reject with NOT_IMPLEMENTED, which is why the two that don't were never noticed. The engine helpers already existed and were tested; only the overrides were missing.

admin/import asserted success by omission. errors: [] and conflicts: 0 together read as "nothing went wrong", and an empty inserted map is also what a legitimately empty batch returns. The response now carries received as the denominator. A worker missing resolveTableSharding also cannot recognise a .global() table, so every row went to the default shard and the GLOBAL_NOT_CONFIGURED error never fired — two missing options cancelling out each other's diagnostics. That combination now warns.

Silent-until-production correctness

  • Two search indexes on one table can collide through an FTS5 shadow suffix. search_prompts reserves <table>__fts_search_prompts_content as its own _content shadow, so a sibling search_prompts_content cannot be created. A legal pair of names; the runtime error lands in ensureMigrated, making every sharded table unreadable while the HTTP response is still 200. Now a static check.
  • withIndex took a bare string. A renamed, dropped, or mistyped index produced zero type errors and either threw at runtime or degraded silently to a full table scan — the worse outcome, since it stays green in tests. TableReader now carries index-name parameters bound to the per-table unions codegen was already emitting (IndexNamesByTable existed, and its doc comment already claimed withIndex used it).
  • A nested v.optional() was emitted as a required key typed T | undefined. The handler saw the right type and the caller did not, so a partial-update argument obliged callers to name every field and the {...args.patch} spread carried explicit undefineds into ctx.db.patch.
  • The generated api.ts did not typecheck when a handler returned a type from its own ./lib/types — the qualifier only resolves from the source file. It hid because a progress script that greps out _generated reads zero errors, and it surfaces only when a sibling package compiles the same file.

Commands that lied about the tree

  • verify and doctor greenlit a tree wrangler refuses to bundle. .scheduler() / .workflow() write the binding and the migration entry but cannot add the export { SchedulerDO } the entry needs. Reported as a warning — see the Review section for why a heuristic scanner must not fail closed here. It is skipped entirely on a star re-export, ignores script_name bindings, and blanks comments and strings first (a worker entry that discusses its Durable Objects in comments is the normal case). Verified against all nine apps/examples in the repo: no finding on any.
  • The schema-drift remediation prescribed a flag the printing command rejects. verify accepts only --allow-schema-drift, but the message offered --update-schema-baseline too. It now renders from what the invoking command actually takes, and points at prepare for the one verify cannot do (it runs the gate read-only, so re-blessing from it would be wrong rather than missing).
  • lunora import --help and run --help printed no help at all, exiting 1 with Found extraneous } in template literal — the renderer passes help text through chalk's tagged-template parser, so a literal brace in a JSON example hard-errors that command's help. Escaped at registration; every registered command's help is now rendered in CI (advisor and introspect are reachable but absent from the user-facing name list, so a per-name test would have missed two).

Capability gaps

  • HttpActionCtx.storage. R2 is a worker binding, so an HTTP action reaches it where an action does. The omission propagated: a helper touching storage on one branch still types its ctx for the worst case, barring every HTTP caller from the whole helper. (db stays absent — an HTTP handler is not transactional.)
  • Migration transforms get a shard-scoped reader and may be async, so the common backfill — read the parent, copy a field down — is expressible. Read-only, because the runner accounts for one rewrite per row read. Documented alongside it: a shard key cannot be backfilled by a migration at all, since the row belongs to no shard and writing the key would have to move it to another Durable Object.
  • createReadOnlyDbStore for rate limits, so "how many requests are left" is answerable from a query context. Mirrors the ReadOnlyStorage/Storage split.
  • postcodegen runs from prepare/deploy, which generate in-process. Without it lunora deploy shipped output the project considered unfinished, and the deploy pipeline has no reason to run the project's codegen script first.

Notes for review

  • shared/ used twice (as-bucket-storage, any-api) — the documented seam for one implementation two packages need where neither may depend on the other. Public surfaces are unchanged; both re-export.
  • The generated api.ts now imports anyApi from @lunora/client, not the server package, so a sibling web app consuming <backend>/api needs no server runtime. This narrows the coupling rather than removing it — dataModel.ts still needs @lunora/server types at compile time, and the docs say so.
  • TableReader's new generics all default to string, so the schema-agnostic reader and the wide (table: string) => TableReader overload ctx.db intersects in are unchanged. The three with* members are method signatures rather than function properties, deliberately — see the Review section.
  • Example _generated/* regeneration is its own commit so the feature diff stays readable.
  • Commit messages and code comments state each defect on its own merits rather than citing an external tracker, so the history reads without it.

Review

Both /thermos passes ran against this branch. Four findings were correctness-level and are fixed in 61ba85266; each was reproduced before being acted on.

  • postcodegen never ran the script and blocked the deploy instead — it built its argv with the run-a-binary helper, so pnpm got pnpm exec run postcodegen (exit 1) and npm got npx -- run postcodegen, which resolves the registry package named run. The original test asserted only that the argv contained postcodegen, which the broken form satisfied; it now asserts the full argv.
  • The wrangler export check reported correctly-wired projects as broken — three missed forms (a prettier-wrapped export list, a whole-file type-only probe poisoning a real value export, and export const { ShardDO } = app, the generated builder's own pattern). All fail closed. Fixed, and downgraded from error to warning: three misses in one review pass is enough evidence that more exist, and a heuristic must not block a working deploy. It still closes the reported gap, and wrangler stays authoritative via lunora build.
  • received double-counted every failed row — the error list is appended to during fan-out, so summing the buckets afterwards counted failures twice. Counted at read time instead; the regression test fails on the old code.
  • TableReader's narrowing was a silent breaking change — under strictFunctionTypes the narrowed parameter made a bound reader unassignable to a helper typed TableReader<Doc>, while the doc comment claimed no impact. The three with* members are now method signatures (bivariant), so both directions hold; both are pinned in types.test-d.ts.

Also from the review: the FTS5 collision check missed __vocab (which matters more than the reserved five — it is created IF NOT EXISTS, so a collision binds silently instead of erroring); lunora import was dropping the endpoint's new warnings/received; escapeExamples could throw on a mixed array; and dead build/codegen entries came out of the drift-flag table.

Recorded, not fixed: the admin export RPC has no cursor, so a shard larger than the DO's memory budget fails its export. That is a loud failure where the bug it replaces was a silent empty one; noted at the emission site.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added optional post-generation scripts for prepare and deploy.
    • Migration transforms can read related records, including asynchronously.
    • Data imports now report received rows, warnings, conflicts, and inserted totals.
    • HTTP actions can access configured storage.
    • Generated queries provide stronger index-name validation and improved import/export support.
    • Migration imports preserve supplied IDs and relationships.
    • Added read-only database access for rate-limiting workflows.
  • Bug Fixes

    • Improved command help rendering and schema-drift guidance.
    • Added detection for conflicting search-index names and missing runtime exports.
  • Documentation

    • Documented post-generation scripts and recommended migration workflows.

prisis and others added 16 commits July 31, 2026 14:36
Three defects that share a failure mode: each one is silent, and two of them
report success while losing data.

`ShardDO`'s base `runShardExport` / `runShardImport` return `[]` and
`{conflicts:0,errors:[],inserted:{}}` — the codegen subclass was expected to
override them and never did. Both returns are success-shaped, so they are
indistinguishable from a correct export of an empty shard: `lunora backup` on a
`.shardBy()` schema succeeded and backed up nothing, and `admin/import` reported
success and dropped every row. The sibling stubs in the same class reject with
NOT_IMPLEMENTED, which is why the two that don't were never noticed. The engine
helpers already existed and were tested; only the overrides were missing. The
import path inserts with `allowExplicitId`, so a source database's ids carry
across verbatim and referencing foreign keys stay valid in one pass.

Two search indexes on one table can collide through an FTS5 shadow-table
suffix: `search_prompts` reserves `<table>__fts_search_prompts_content` as its
own `_content` shadow, so a sibling `search_prompts_content` cannot be created.
It is a legal pair of index names and nothing rejected it, but the runtime
error lands in `ensureMigrated` — every sharded table becomes unreadable, the
HTTP response is still 200, and the cause appears only in the worker log. The
shadow suffixes are a fixed list, so this is a static check.

A `v.optional()` nested inside `v.object()` / `v.array()` was emitted as a
REQUIRED key typed `T | undefined`; only the top level of `.input()` applied the
optional-property rule. The handler saw the right type and the caller did not,
so a partial-update argument obliged callers to name every field, and the
`{...args.patch}` spread then carried those explicit undefineds into
`ctx.db.patch`. Both levels now render through one helper.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`withIndex`, `withSearchIndex` and `withGeoIndex` all took a bare `string`, so a
fabricated or stale index name produced zero type errors — `tsc`, `codegen` and
`verify` were all clean on `.withIndex("by_TOTALLY_FAKE")`.

Three ways a name goes stale without the call site being touched: an index is
renamed, an index is dropped as redundant, or a `.query()` is repointed at a
different table. None were caught, and the consequence is either a runtime throw
or a silent degradation to a full table scan. The second is the worse one — it
stays green in tests and surfaces months later as a latency regression, which
also makes acting on a `duplicate_index` advisory unverifiable.

`TableReader` now carries index-name parameters alongside `Row`, and codegen
binds them to the per-table unions it was already emitting: `IndexNamesByTable`
existed, and its doc comment already claimed `withIndex()` used it to constrain
callers, but it was not among the reader's type arguments. Tables declaring no
index of a kind get `never`, so no name satisfies the call.

All three parameters default to `string`, so the schema-agnostic reader and the
wide `(table: string) => TableReader` overload that `ctx.db` intersects in are
unchanged — a caller holding a runtime string still compiles.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`HttpActionCtx` exposed no `storage`, so an HTTP handler could not store an
uploaded object, mint a presigned URL, or read one back — it had to hop through
a scheduled action for any of it.

The omission was incidental rather than principled. R2 is a worker binding, and
an HTTP action runs in the worker exactly where an action does, so nothing about
the topology required the hop. (`db` stays absent, which IS principled: an HTTP
handler is not transactional.)

What made it more than a missing member is how far the requirement propagated. A
helper that touches storage on ONE branch — an inline attachment over the size
limit gets stored and replaced with a URL — still has to type its ctx parameter
for the worst case, so requiring an `ActionCtx` there barred every HTTP caller
from the helper, including for the messages that never go near storage. The
workaround is a runtime `"storage" in ctx` check standing in for something the
type system was close to expressing.

`storage` is optional and genuinely absent when the app declared no
`.storage(...)`, rather than a throwing stub, so the type does not promise a
handler something it cannot reach.

The bucket-tagging helper moves to `shared/` so both packages can use it:
`@lunora/runtime` must not gain a dependency on `@lunora/server`, and the
public `asBucketStorage` export re-exports it unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`lunora import --help` and `lunora run --help` both exited 1 with `Found
extraneous } in template literal`, printing no help at all.

The renderer passes help text through chalk's tagged-template parser, which
reads `{style ...}` as markup. So a description or example carrying a real brace
— a JSON `--args` sample, the import line's table/doc envelope — does not render
wrong, it throws, and that command's help becomes unreachable. The import
contract had to be read out of the package's `.d.ts` instead.

Escaping at registration rather than policing every string keeps help text
written the way it reads, and means a command added later that happens to
document a JSON payload cannot reintroduce this. Nothing uses chalk styling in
help text deliberately, so there is no markup being suppressed.

The guard renders `--help` for every REGISTERED command, not the user-facing
name list: `advisor` and `introspect` are reachable but deliberately absent from
that list, so a per-name test would have left two commands uncovered. This
failure is invisible until someone asks for help on one specific command, which
is the moment they can least afford it, so spot-checking the two known-bad ones
would not have been enough.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The import response asserted success by omission. `errors: []` and
`conflicts: 0` together read as "nothing went wrong", and an empty `inserted`
map is also exactly what a legitimately empty batch returns — so a bulk import
that was structurally unable to write was indistinguishable from one that had
nothing to do. A migration script could report "imported 4.2M rows" against an
empty database.

`received` is the missing denominator: a caller can now compare it against the
inserted total and tell "wrote nothing because there was nothing" from "wrote
nothing because I cannot".

A worker with no `resolveTableSharding` also cannot recognise a `.global()`
table, so every row routes to the default shard — correct for a single-shard app,
silent misplacement for a sharded one. Worse, it suppresses the
`GLOBAL_NOT_CONFIGURED` error that would otherwise fire, because no row is ever
classified global. Two missing options cancelling out each other's diagnostics is
why this presented as a 200 with nothing written and nothing reported wrong. That
combination now comes back as an explicit warning rather than silence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`.scheduler(...)` and `.workflow(...)` write the durable_objects binding and the
migration entry but cannot add the `export { SchedulerDO }` the entry needs, so
the wiring is only half done — and wrangler refuses to bundle the result: "Your
Worker depends on the following Durable Objects, which are not exported in your
entrypoint file."

What makes this worth a check rather than leaving it to deploy is what the
toolchain reported in the meantime. `lunora verify` printed "project is valid"
and `lunora doctor` printed "all checks passed" on a tree that cannot deploy —
and verify's own description is "validate wrangler.jsonc + codegen dry-run +
tsc", where the thing that is invalid IS the relationship between wrangler.jsonc
and the entry. Only `lunora build`, which shells out to `wrangler deploy
--dry-run`, caught it. Two capabilities shipped with this shape, which points at
the pattern rather than the instances.

Both files were already parsed here, so the check is a string-set comparison,
and it lands in the shared validator so prepare/verify/deploy all get it.

Deliberately conservative, because a false error blocks a deploy that would have
worked:

- A star re-export forwards names no per-name scan can see, so the check is
  skipped entirely when the entry has one.
- A binding carrying `script_name` names a class in another Worker — that
  script's to export, not this entry's.
- Comments and string literals are blanked before scanning. A worker entry that
  discusses its Durable Objects in comments is the normal case, and counting
  those would have made the check silently pass on exactly the tree it exists to
  catch — verified by removing a real export and watching it fire.
- A type-only `export type { SchedulerDO }` counts as unexported, since it
  compiles away and is precisely the case that looks bound and is not.

Verified against all nine apps/examples in the repo: no finding on any of them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…nting it

The blocked-drift message listed both override flags unconditionally, so
following it verbatim failed. `lunora build` accepts neither
(`Found unknown option "--allow-schema-drift"`) and `verify` accepts only the
first, so half its own advice did not work on the command that printed it. This
is the message a first-time deployer hits.

The remediation is now rendered from what the invoking command actually takes.
Where a command has no override flag, it names the one that does rather than
leaving the reader to discover that the fix for a blocked `build` is to run
`prepare` instead — which the old text never said.

`verify` deliberately keeps only `--allow-schema-drift`: it runs the gate
read-only, so a flag that re-blesses the baseline does not belong on it. Saying
so is the fix, not adding the flag.

An unrecognised caller still gets both lines — an over-broad hint beats none.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`createDbStore` typed `db` as the writer (insert/patch/delete), which is right
for `limit()` and `reset()` and wrong for `getValue()` / `check()` — pure reads
that project the stored value forward to the current clock.

So "how many requests does this user have left" could not be answered from a
query context at all, because a `QueryCtx`'s `ctx.db` is a reader. Every
remaining-quota display cast instead, and a cast that appears often enough stops
carrying information.

The distinction was already in the methods; it just was not in the type. This
mirrors the split Lunora already makes for `ctx.storage` — `ReadOnlyStorage` in
a query, full `Storage` in an action — where the capability difference is
visible rather than discovered at runtime.

`set`/`delete` on the read-only store throw with a message naming the fix, since
a limiter that appears to consume budget and does not is worse than one that
refuses.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`MigrationTransform` was `(document) => document` — one argument, and it was the
row. With no ctx there was no `ctx.db`, so a transform could rewrite the row it
was handed and nothing else.

That covers a backfill whose new value is a pure function of the old row
(`displayName = name ?? "Anonymous"`, the example this skill ships). It does not
cover the backfill people actually write: denormalising a parent's field onto its
children — read the parent, copy a field down. Transforms may now be async and
receive a reader (`get`/`findFirst`/`findMany`/`count`) as their second argument.

Read-only deliberately: the runner accounts for exactly one rewrite per row read,
and a transform writing directly would make that count describe something other
than what happened. It also keeps the shard boundary honest.

Documented alongside it, because a reader does NOT make it possible: a shard key
cannot be backfilled by a migration at all. A row whose shard key is unset
belongs to no shard, so a shard-scoped query never enumerates it, and writing the
key would have to move the row to a different Durable Object. Re-keying is an
export → transform → import. The skill previously read as if a data backfill were
unconditionally an online migration.

Also fixes the scaffold's import: `lunora migrate create` emitted
`from "@lunora/server"` unconditionally, which is a real package but not a
declared dependency of an umbrella project — there `lunorash/server` is what
resolves. It now follows the same rule codegen uses for every generated import.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`prepare` and `deploy` invoke codegen in-process rather than shelling out to the
project's `codegen` script — faster, and it does not depend on that script
existing. But it also meant anything a project chained onto codegen was silently
skipped, so a project wrapping the CLI
(`"codegen": "lunora codegen && … run patch"`) watched `prepare` revert its
post-step.

The local error count is not the part that matters. **`lunora deploy` would ship
the unpatched output**, and a deploy pipeline has no reason to run the project's
codegen script first, so nothing else would catch it.

`postcodegen` is the package-manager-native name — npm/pnpm/yarn/bun all run
`postX` after `run X` — so a project calling the CLI through its own `codegen`
script already gets the hook, and this makes the in-process path agree rather
than inventing a Lunora-specific config key. A non-zero exit fails the run, since
the whole point is not shipping output the project rejected. A missing script is
the common case and costs nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The type checker prints a type relative to the module it was read in, so a
handler returning a type from its own `./lib/types` renders as
`import("./lib/types").BetterAuthUser`. Inlined verbatim into
`lunora/_generated/api.ts` that means `lunora/_generated/lib/types`, which does
not exist — TS2307, inside a generated file, while `lunora codegen` exits 0.

Only `_generated/*` qualifiers and `@lunora/*` base packages were rewritten;
a user's own relative specifier was carried across untouched.

The combination is why it hid. A progress script that greps out `_generated`
— reasonable, since nobody edits generated files — reads zero errors while
`api.ts` has nine, and it surfaces only when a SIBLING package compiles the same
file and has nowhere to hide them. A generated file that does not typecheck is a
defect that hides from exactly the person who could fix it.

The rebase resolves the specifier against the function's own directory (codegen
already tracks it) and re-expresses it from the output directory.

Ordering is load-bearing and now has a test: the user rebase must run BEFORE the
`_generated/` one. Once the generated prefix is stripped, `./dataModel.js` is
indistinguishable from a user module, and rebasing it would send every `Doc`/`Id`
qualifier one level too high.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`_generated/api.ts` is the file a SIBLING package imports — a web app, another
Worker — but its only runtime import was `anyApi` from the server package. So a
browser app consuming `<backend>/api` had to resolve the server runtime for a
forty-line proxy that mints `{ __lunoraRef }` reference objects.

The proxy moves to `shared/`, and both `@lunora/server` and `@lunora/client`
re-export the same implementation, so neither package gains a dependency on the
other and both public surfaces are unchanged. The generated `api.ts` now imports
it from the client package, which a consumer of the API surface already depends
on.

This narrows the coupling rather than removing it: `api.ts` still imports `Id`
from `_generated/dataModel.ts`, which imports types from `@lunora/server`. Those
are type-only and erase at runtime, but a consumer still needs them resolvable at
compile time — the `exports`-mapping recipe and its caveat are documented under
"Consuming the generated API from a sibling package".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Picks up this branch's emitter changes: the `runShardExport`/`runShardImport`
overrides, the client-package `anyApi` import, the per-table index-name unions
threaded into `ctx.db.query`, and the app builder's worker-side storage wiring.

No source change — `_generated/*` is derived output, regenerated in its own
commit so a feature diff stays readable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…sert does not

The Convex checklist still told readers to reshape the JSONL export and
batch-insert it through a mutation. That predates `lunora import
<convex-export-dir>`, and following it is actively harmful: `ctx.db.insert`
discards a supplied `_id` and mints a fresh one, so a hand-rolled importer
renumbers the data and breaks every foreign key.

The import path does the opposite — it writes the supplied `_id` — which is what
makes the migration one pass with no remapping, and turns self-referential and
cross-table cycles into ordinary rows rather than special cases.

Two write paths with opposite behaviour on the same field, and neither stated it.
That single sentence is the difference between a Convex migration being a
morning's work and appearing impossible.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ken hook

**`postcodegen` never ran the script, and blocked the deploy instead.** It built
its argv with `execArgsFor`, which runs a BINARY, not a script — so pnpm got
`pnpm exec run postcodegen` (`Command "run" not found`, exit 1) and npm got
`npx -- run postcodegen`, which resolves the registry PACKAGE named `run` and
executes it. Only yarn worked, by accident. The feature therefore inverted: a
project adopting the documented hook had `prepare`/`deploy` fail, blaming the
user's own script. A new `runScriptArgsFor` sits beside `installArgsFor`, and the
test now asserts the full argv rather than that it merely contains the name — the
old assertion passed on the broken form. `detectPackageManager`'s throw is also
caught, so it becomes a `code: 1` result rather than escaping `prepare`.

**The wrangler export check reported correctly-wired projects as broken.** The
proximity regex could not cross a newline, so a prettier-wrapped `export { A,\n
B }` — how three or more exports are formatted — read as "not exported"; and the
type-only probe was whole-file, so an `export type { X as T }` suppressed a real
`export { X }`. It also missed `export const { ShardDO } = app`, which is the
generated app builder's OWN pattern: the repo's playground tripped it. Replaced
with a scanner over export CLAUSES that handles wrapped lists, per-specifier
`type`, `as` renames (the EXPORTED name is what wrangler binds), and
destructuring.

That is three missed forms found in one review pass, each failing CLOSED, so the
finding is now a **warning rather than an error**. It still closes the reported
gap — `verify`/`doctor` no longer print a clean bill of health on a tree that
cannot deploy — while a form the scanner does not know degrades to noise instead
of blocking a working deploy and stopping `lunora dev`. wrangler's own check,
which `lunora build` runs, stays authoritative.

**`received` double-counted every failed row.** The error list is handed to the
caller by reference and appended to during fan-out, so summing the buckets
afterwards counted each failure twice — a 3-row body with no `importGlobals`
reported 6. Counted where the lines are read instead. The regression test fails
on the old code (6 vs 3); the previous test used a clean batch and never reached
the path.

**`TableReader`'s narrowing was a silent breaking change.** Under
`strictFunctionTypes` a narrowed function-property parameter is contravariant, so
a bound `TableReader<Doc, "by_x">` stopped being assignable to a helper typed
`TableReader<Doc>` — while the doc comment asserted no impact. The three `with*`
members are now method signatures, which are bivariant, so both directions hold:
a helper still accepts what `ctx.db.query(t)` returns, and an undeclared index
name is still rejected. Both are pinned in `types.test-d.ts`.

Also: the FTS5 collision check missed `__vocab`, which matters more than the
reserved five because it is created `IF NOT EXISTS` — a collision there does not
error, it silently binds the second index to the first's vocab table. `lunora
import` now surfaces the endpoint's `warnings` and `received` instead of dropping
them. `escapeExamples` no longer throws on a mixed array. Dead `build`/`codegen`
entries removed from the drift-flag table — neither runs the gate.

Recorded rather than fixed: the admin export RPC has no cursor, so a shard larger
than the DO's memory budget fails the export. That is a loud failure where the
bug it replaces was a silent empty one, and it is noted at the emission site.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`TableReader`'s three index members became method signatures (bivariance — see
the previous commit), which changes their rendering in the snapshot, and the
emitter picked up the export-RPC note.

Derived output only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@netlify

netlify Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit 2fbbf0d
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a6cd0a26aeb2c00086013f0
😎 Deploy Preview https://deploy-preview-241--lunorash.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e2edfe95-ea71-42f9-afe6-6a8051bede1e

📥 Commits

Reviewing files that changed from the base of the PR and between b3c52b5 and 2fbbf0d.

⛔ Files ignored due to path filters (1)
  • packages/cli/__tests__/commands/deploy.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
📒 Files selected for processing (2)
  • packages/cli/src/commands/deploy/handler.ts
  • packages/cli/src/util/post-codegen-hook.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/cli/src/commands/deploy/handler.ts

Walkthrough

The PR adds post-codegen hooks, command-aware schema-drift messages, migration readers, shard data transfer, typed generated APIs, storage context wiring, read-only rate-limit stores, and Wrangler worker export warnings.

Changes

CLI workflow updates

Layer / File(s) Summary
Post-codegen execution
apps/docs/src/content/docs/concepts/generated-code.mdx, packages/cli/src/commands/{prepare,deploy}/handler.ts, packages/cli/src/util/{detect-package-manager,post-codegen-hook}.ts
prepare and deploy run the optional postcodegen script after in-process code generation. Hook failures stop the command.
Command-aware schema-drift handling
packages/cli/src/util/schema-drift-gate.ts, packages/codegen/src/schema-drift.ts, packages/cli/src/commands/{prepare,deploy,verify}/handler.ts
Schema-drift messages now use the invoking command.
Command registration and help rendering
packages/cli/src/cli.ts
CLI help text escapes braces, and registered command names are exported.
Dependency-aware migration scaffolding
packages/cli/src/commands/migrate/handler.ts, packages/codegen/src/index.ts
Migration scaffolds select lunorash/server or @lunora/server from declared dependencies.

Migration and data transfer

Layer / File(s) Summary
Read-only migration transform contexts
packages/server/src/migration.ts, packages/server/src/index.ts, packages/shard-engine/src/data-migration.ts, packages/cli/skills/lunora-migration-helper/SKILL.md
Migration transforms receive shard-scoped readers and may perform asynchronous reads without writing other tables.
Shard export and import flow
packages/codegen/src/emit.ts, apps/docs/src/content/docs/migrating/from-convex.mdx
Generated shard RPCs export and import rows while preserving explicit IDs.
Import accounting and diagnostics
packages/runtime/src/import-stream.ts, packages/runtime/src/data-movement-admin-routes.ts, packages/cli/src/commands/data-transfer.ts
Import responses include received-row counts and warnings.

Code generation and typed APIs

Layer / File(s) Summary
Generated shape and import emission
packages/codegen/src/emit.ts
Generated types preserve optional properties and rebase user-relative imports. Generated shards emit export and import RPCs.
Typed indexes and shared API proxy
packages/codegen/src/emit.ts, packages/server/src/types.ts, packages/client/src/index.ts
Generated queries restrict index names to declared indexes, and API proxies use shared anyApi.
FTS5 shadow-table validation
packages/codegen/src/discover-schema.ts
Schema discovery reports search-index names that collide with FTS5 shadow tables.

Runtime and storage capabilities

Layer / File(s) Summary
HTTP action storage wiring
packages/codegen/src/emit-app.ts, packages/runtime/src/create-worker.ts, packages/server/src/{as-bucket-storage,http.ts}
Configured storage is resolved and exposed through HTTP action contexts.
Read-only rate-limit database store
packages/ratelimit/src/{store,index}.ts
The rate-limit package exposes reader-only database options and rejects write operations in the read-only store.

Wrangler worker export validation

Layer / File(s) Summary
Worker entry and runtime export checks
packages/config/src/cloudflare/wrangler-validator.ts, packages/config/src/infer-bindings.ts
Validation resolves worker entries, inspects runtime exports, and records missing same-script Durable Object or Workflow exports as warnings.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Codegen
  participant Postcodegen
  participant SchemaDrift
  CLI->>Codegen: Run in-process generation
  Codegen-->>CLI: Return generated output
  CLI->>Postcodegen: Run postcodegen script
  Postcodegen-->>CLI: Return success or failure
  CLI->>SchemaDrift: Evaluate drift after successful hook
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: closing remaining findings from a third-party Convex migration.
Description check ✅ Passed The description provides a comprehensive summary, validation details, reviewer notes, migration impact, and the remaining unresolved limitation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/migration-findings-round-2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (4)
packages/config/src/cloudflare/wrangler-validator.ts (3)

1161-1170: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Adopt the shared entry-resolution helper, or correct the export comment. infer-bindings.ts now exports resolveWorkerEntry and isTypeOnlyExportEntry "rather than copied", but the validator imports only WORKER_ENTRY_FALLBACKS and keeps its own resolution and type-only logic. The stated drift risk remains.

  • packages/config/src/cloudflare/wrangler-validator.ts#L1161-L1170: call resolveWorkerEntry(projectRoot) when the resolution rules match. If the validator must resolve main relative to dirname(wranglerPath) instead of projectRoot, document that difference here.
  • packages/config/src/infer-bindings.ts#L912-L916: update the comment to name only the symbols the validator actually consumes, and remove any export that has no consumer.
#!/bin/bash
# Find consumers of the newly exported helpers.
rg -nP '\b(resolveWorkerEntry|isTypeOnlyExportEntry|WORKER_ENTRY_FALLBACKS)\b' --type=ts
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/config/src/cloudflare/wrangler-validator.ts` around lines 1161 -
1170, Replace the local resolveWorkerEntryPath logic in
packages/config/src/cloudflare/wrangler-validator.ts:1161-1170 with the shared
resolveWorkerEntry(projectRoot) helper when its resolution rules match;
otherwise document the dirname(wranglerPath) distinction. In
packages/config/src/infer-bindings.ts:912-916, revise the export comment to list
only symbols actually consumed by the validator and remove unused exports.

1360-1360: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename to match the warning severity and deduplicate messages.

The results reach report.warnings, so collectUnexportedClassErrors reads as an error collector. Rename it to collectUnexportedClassWarnings. Two bindings that name the same class also produce two identical messages; deduplicate by className before mapping.

Also applies to: 1400-1407

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/config/src/cloudflare/wrangler-validator.ts` at line 1360, Rename
collectUnexportedClassErrors to collectUnexportedClassWarnings and update every
reference to reflect that its results populate report.warnings. In this
collector, deduplicate bindings by className before mapping them into warning
messages so repeated class names produce only one message.

1163-1167: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Report a main that points at a missing file.

If main is set but the resolved path does not exist, this function returns undefined and the export check is skipped without any diagnostic. A missing main also breaks wrangler deploy, so the silence hides a real misconfiguration. Return the resolution outcome and push a warning for that case.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/config/src/cloudflare/wrangler-validator.ts` around lines 1163 -
1167, Update the main-path resolution logic in the wrangler validator so a
configured main whose resolved path is missing emits a warning and returns the
resolution outcome instead of silently returning undefined. Preserve the
existing resolved-path return for files that exist, and use the function’s
established warning mechanism and diagnostic context.
apps/docs/src/content/docs/migrating/from-convex.mdx (1)

268-272: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid splitting an inline code span across a line break.

`lunora on one line and import` on the next line form a single inline code span that spans a hard line break. Rewrap so `lunora import` stays on one line, to avoid depending on the renderer's whitespace-collapsing behavior for correct display.

✏️ Proposed rewrap
 <Callout type="warn">
-    `ctx.db.insert` does the **opposite**: it discards a supplied `_id` and mints a fresh one. So a hand-rolled importer that batch-inserts through a
-    mutation renumbers your data and breaks every foreign key, which is exactly the failure that makes a Convex migration look impossible. Use `lunora
-    import` (or the admin import endpoint it calls) for a data load; `ctx.db.insert` is for new rows.
+    `ctx.db.insert` does the **opposite**: it discards a supplied `_id` and mints a fresh one. So a hand-rolled importer that batch-inserts through a
+    mutation renumbers your data and breaks every foreign key, which is exactly the failure that makes a Convex migration look impossible. Use
+    `lunora import` (or the admin import endpoint it calls) for a data load; `ctx.db.insert` is for new rows.
 </Callout>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/docs/src/content/docs/migrating/from-convex.mdx` around lines 268 - 272,
Rewrap the warning text in the Callout so the inline code span `lunora import`
remains entirely on one source line; preserve the surrounding wording and
formatting.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/docs/src/content/docs/concepts/generated-code.mdx`:
- Around line 116-129: Update
apps/docs/src/content/docs/concepts/generated-code.mdx lines 116-129 to limit
automatic postX hooks to npm, pnpm, and bun; explain that Lunora invokes
postcodegen for prepare and deploy, and document explicit Yarn codegen chaining.
Update packages/cli/src/util/post-codegen-hook.ts lines 13-17 to remove the
claim that Yarn automatically runs postcodegen after codegen.

In `@packages/cli/src/cli.ts`:
- Around line 172-178: The command-name derivation and registration currently
omit versionCommand and completionCommand because they use CLI_COMMANDS alone.
In packages/cli/src/cli.ts lines 172-178, create or reuse one shared collection
containing CLI_COMMANDS, versionCommand, and completionCommand, and derive
REGISTERED_COMMAND_NAMES from it; in lines 275-275, iterate that same collection
when sanitizing commands before cli.addCommand.

In `@packages/cli/src/commands/migrate/handler.ts`:
- Around line 404-409: Update the migration content handling around
defineMigrationImportFor and the empty/non-empty content branches to recognize
existing defineMigration imports from both `@lunora/server` and lunorash/server,
replace either one with the selected import, and only prepend when neither
exists. Add a regression test covering an existing scaffold that uses the
opposite module specifier.

In `@packages/cli/src/util/post-codegen-hook.ts`:
- Around line 96-100: Update runPostCodegenHook around the
options.spawner/defaultSpawner invocation to catch rejected spawner promises and
convert them into { error, ran: true } results, preserving the existing non-zero
result.code handling and preventing the rejection from propagating to prepare.

In `@packages/codegen/src/discover-schema.ts`:
- Around line 671-676: Update the diagnostic construction in discover-schema.ts
around diagnosticAt so the __vocab collision uses separate suffix-specific text
describing Lunora’s fts5vocab companion-table collision and possible
existing-table or incorrect binding outcomes, without claiming SQLite’s
reserved-name error. Preserve the current reserved FTS5 shadow-table diagnostic
for the other suffixes.

In `@packages/config/src/cloudflare/wrangler-validator.ts`:
- Around line 1385-1397: Update the `wrangler.workflows` loop so it only adds a
workflow class to `declared` when `entry.script_name` is undefined, matching the
cross-worker exclusion already used for durable object bindings. Preserve the
existing non-empty `class_name` validation and `"workflows"` label.

In `@packages/server/src/types.ts`:
- Around line 2215-2219: Export the typed shared binding declared as anyApi in
the visible module so direct consumers retain the `@lunora/server` export. Keep
the existing sharedAnyApi cast to AnyApi unchanged and modify only the binding’s
export visibility.

---

Nitpick comments:
In `@apps/docs/src/content/docs/migrating/from-convex.mdx`:
- Around line 268-272: Rewrap the warning text in the Callout so the inline code
span `lunora import` remains entirely on one source line; preserve the
surrounding wording and formatting.

In `@packages/config/src/cloudflare/wrangler-validator.ts`:
- Around line 1161-1170: Replace the local resolveWorkerEntryPath logic in
packages/config/src/cloudflare/wrangler-validator.ts:1161-1170 with the shared
resolveWorkerEntry(projectRoot) helper when its resolution rules match;
otherwise document the dirname(wranglerPath) distinction. In
packages/config/src/infer-bindings.ts:912-916, revise the export comment to list
only symbols actually consumed by the validator and remove unused exports.
- Line 1360: Rename collectUnexportedClassErrors to
collectUnexportedClassWarnings and update every reference to reflect that its
results populate report.warnings. In this collector, deduplicate bindings by
className before mapping them into warning messages so repeated class names
produce only one message.
- Around line 1163-1167: Update the main-path resolution logic in the wrangler
validator so a configured main whose resolved path is missing emits a warning
and returns the resolution outcome instead of silently returning undefined.
Preserve the existing resolved-path return for files that exist, and use the
function’s established warning mechanism and diagnostic context.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 33729816-8634-4fd6-8a33-15aed213faea

📥 Commits

Reviewing files that changed from the base of the PR and between ad873e8 and 6bfd780.

⛔ Files ignored due to path filters (59)
  • api-snapshots/client.api.md is excluded by none and included by none
  • api-snapshots/codegen.api.md is excluded by none and included by none
  • api-snapshots/config.api.md is excluded by none and included by none
  • api-snapshots/lunora.api.md is excluded by none and included by none
  • api-snapshots/ratelimit.api.md is excluded by none and included by none
  • api-snapshots/runtime.api.md is excluded by none and included by none
  • api-snapshots/server.api.md is excluded by none and included by none
  • api-snapshots/shard-engine.api.md is excluded by none and included by none
  • examples/auth-playground/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/auth-playground/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/auth-playground/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/auth-playground/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/blog/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/blog/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/blog/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/blog/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/expo/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/expo/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/expo/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/notify-demo/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/notify-demo/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/notify-demo/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/notify-demo/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/offline-rejections/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/offline-rejections/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/offline-rejections/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/offline-rejections/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/payment-demo/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/payment-demo/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/payment-demo/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/payment-demo/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/realtime-cursors/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/realtime-cursors/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/realtime-cursors/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/realtime-cursors/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • examples/todo-app/lunora/_generated/api.ts is excluded by !**/_generated/** and included by none
  • examples/todo-app/lunora/_generated/app.ts is excluded by !**/_generated/** and included by none
  • examples/todo-app/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/todo-app/lunora/_generated/shard.ts is excluded by !**/_generated/** and included by none
  • packages/cli/__tests__/cli.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/cli/__tests__/commands/migrate.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/cli/__tests__/commands/prepare.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/discover-schema.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/emit-api.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/fixtures/simple/expected/_generated/api.ts is excluded by !**/_generated/**, !**/__tests__/** and included by packages/**
  • packages/codegen/__tests__/fixtures/simple/expected/_generated/app.ts is excluded by !**/_generated/**, !**/__tests__/** and included by packages/**
  • packages/codegen/__tests__/fixtures/simple/expected/_generated/server.ts is excluded by !**/_generated/**, !**/__tests__/** and included by packages/**
  • packages/codegen/__tests__/fixtures/simple/expected/_generated/shard.ts is excluded by !**/_generated/**, !**/__tests__/** and included by packages/**
  • packages/codegen/__tests__/run-codegen.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/schema-drift.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/config/__tests__/wrangler-validator.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/ratelimit/__tests__/db-store.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/runtime/__tests__/admin-export-import.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/runtime/__tests__/create-worker.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/server/__tests__/migration.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/server/__tests__/types.test-d.ts is excluded by !**/__tests__/** and included by packages/**
  • packages/shard-engine/__tests__/data-migration.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • shared/any-api.ts is excluded by none and included by none
  • shared/as-bucket-storage.ts is excluded by none and included by none
📒 Files selected for processing (31)
  • apps/docs/src/content/docs/concepts/generated-code.mdx
  • apps/docs/src/content/docs/migrating/from-convex.mdx
  • packages/cli/skills/lunora-migration-helper/SKILL.md
  • packages/cli/src/cli.ts
  • packages/cli/src/commands/data-transfer.ts
  • packages/cli/src/commands/deploy/handler.ts
  • packages/cli/src/commands/migrate/handler.ts
  • packages/cli/src/commands/prepare/handler.ts
  • packages/cli/src/commands/verify/handler.ts
  • packages/cli/src/util/detect-package-manager.ts
  • packages/cli/src/util/post-codegen-hook.ts
  • packages/cli/src/util/schema-drift-gate.ts
  • packages/client/src/index.ts
  • packages/codegen/src/discover-schema.ts
  • packages/codegen/src/emit-app.ts
  • packages/codegen/src/emit.ts
  • packages/codegen/src/index.ts
  • packages/codegen/src/schema-drift.ts
  • packages/config/src/cloudflare/wrangler-validator.ts
  • packages/config/src/infer-bindings.ts
  • packages/ratelimit/src/index.ts
  • packages/ratelimit/src/store.ts
  • packages/runtime/src/create-worker.ts
  • packages/runtime/src/data-movement-admin-routes.ts
  • packages/runtime/src/import-stream.ts
  • packages/server/src/as-bucket-storage.ts
  • packages/server/src/http.ts
  • packages/server/src/index.ts
  • packages/server/src/migration.ts
  • packages/server/src/types.ts
  • packages/shard-engine/src/data-migration.ts

Comment thread packages/cli/src/cli.ts Resolved
Comment thread packages/codegen/src/discover-schema.ts Resolved
Comment on lines +2215 to +2219
// The proxy itself lives in `shared/any-api.ts` so `@lunora/client` can serve
// the same value: the generated `api.ts` is what a sibling package imports, and
// its runtime import should not be the server runtime. Re-exported here
// unchanged, typed to this package's `AnyApi`.
const anyApi = sharedAnyApi as unknown as AnyApi;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Export the shared anyApi binding.

Line 2219 declares anyApi as module-local. This removes the @lunora/server export for direct consumers. Export the typed shared binding.

Proposed fix
-const anyApi = sharedAnyApi as unknown as AnyApi;
+export const anyApi = sharedAnyApi as unknown as AnyApi;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// The proxy itself lives in `shared/any-api.ts` so `@lunora/client` can serve
// the same value: the generated `api.ts` is what a sibling package imports, and
// its runtime import should not be the server runtime. Re-exported here
// unchanged, typed to this package's `AnyApi`.
const anyApi = sharedAnyApi as unknown as AnyApi;
// The proxy itself lives in `shared/any-api.ts` so `@lunora/client` can serve
// the same value: the generated `api.ts` is what a sibling package imports, and
// its runtime import should not be the server runtime. Re-exported here
// unchanged, typed to this package's `AnyApi`.
export const anyApi = sharedAnyApi as unknown as AnyApi;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/server/src/types.ts` around lines 2215 - 2219, Export the typed
shared binding declared as anyApi in the visible module so direct consumers
retain the `@lunora/server` export. Keep the existing sharedAnyApi cast to AnyApi
unchanged and modify only the binding’s export visibility.

@codspeed

codspeed Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 6.16%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
❌ 2 regressed benchmarks
✅ 248 untouched benchmarks
⏩ 10 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ in-batch: single IN(...) query + id->doc re-projection 792.4 µs 952.5 µs -16.8%
❌ count, no attributes 57.7 µs 64.3 µs -10.31%
⚡ baseline (Object.keys + toInternal + path spread per field) 72.4 µs 65.4 µs +10.72%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix/migration-findings-round-2 (2fbbf0d) with alpha (b583ffb)2

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on alpha (ad873e8) during the generation of this report, so b583ffb was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

**`lunora migrate create` could emit a duplicate import.** The guard matched only
the specifier it was about to write, so a file scaffolded before the project
adopted the `lunorash` umbrella (carrying `@lunora/server`) got a SECOND
`defineMigration` import prepended beside the first. A duplicate local binding
does not compile. It now recognises either specifier and rewrites in place.

**A rejecting spawner escaped `prepare`.** Only a non-zero exit was converted to
an error, but a spawner REJECTS when the binary is missing or the process cannot
start — that propagated as an unhandled exception instead of the `code: 1`
result the caller is written to expect.

**A workflow class in another Worker was demanded of this entry.** Cloudflare
lets a `workflows[]` entry carry `script_name`, in which case that script owns
the export. The durable-object branch already had this carve-out; the workflow
branch did not.

**The `__vocab` diagnostic promised the wrong failure.** It said the collision is
rejected with `object name reserved for internal use: SQLITE_ERROR`, which is
true of SQLite's five reserved shadows and false of Lunora's `fts5vocab`
companion — that one is created `IF NOT EXISTS`, so nothing is rejected and the
second index silently reads the first's vocabulary. Since that difference is
precisely why `__vocab` is the worse case, the message now states it.

**The Yarn lifecycle claim was wrong.** Yarn Berry deliberately dropped automatic
pre/post hooks for user-defined scripts, so `yarn codegen` does not run
`postcodegen` — only npm, pnpm and bun do. This does not change what the CLI
does (`prepare`/`deploy` invoke the script directly on every manager), but the
docs and the module comment both overstated it, and a Yarn project needs to
chain explicitly.

**`version` and `completion` were registered without being escaped or tested.**
They were added after the loop, so the brace-escaping pass skipped them and the
per-command help guard did not cover them. One collection now feeds both, which
is what stops the two from disagreeing again.

Skipped, with reason: the report claimed `anyApi` had lost its `@lunora/server`
export. It has not — `export { anyApi };` is two lines below the declaration the
report cited, `index.ts` re-exports it, and it is present in the committed api
snapshot.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/util/post-codegen-hook.ts`:
- Line 106: Update runPostCodegenHook() to accept and forward a stdoutToStderr
output-mode option to defaultSpawner, ensuring post-codegen child output is
redirected in JSON mode. In the deploy caller, pass its existing output mode
when invoking runPostCodegenHook() so deploy --format json preserves
machine-readable stdout.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c1c2b6fc-2582-48e2-9c44-702f69bfdffd

📥 Commits

Reviewing files that changed from the base of the PR and between 6bfd780 and b3c52b5.

⛔ Files ignored due to path filters (3)
  • api-snapshots/config.api.md is excluded by none and included by none
  • packages/cli/__tests__/commands/migrate.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/discover-schema.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
📒 Files selected for processing (6)
  • apps/docs/src/content/docs/concepts/generated-code.mdx
  • packages/cli/src/cli.ts
  • packages/cli/src/commands/migrate/handler.ts
  • packages/cli/src/util/post-codegen-hook.ts
  • packages/codegen/src/discover-schema.ts
  • packages/config/src/cloudflare/wrangler-validator.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/docs/src/content/docs/concepts/generated-code.mdx
  • packages/codegen/src/discover-schema.ts
  • packages/cli/src/cli.ts
  • packages/cli/src/commands/migrate/handler.ts

In `--format json` mode stdout is reserved for the single JSON document, and
every other spawned tool already honours that — `deploy` sets `stdoutToStderr`
for wrangler precisely so its progress output cannot interleave with the JSON.

The `postcodegen` hook spawned without it, so a script that prints anything
would corrupt the document that `lunora deploy --format json | jq` reads. The
failure is silent on the producing side: the deploy succeeds and the consumer
gets unparseable output.

The hook now takes the output mode and `deploy` passes it, matching the wrangler
call beside it. The regression test asserts both directions (routed in json,
inherited in pretty) and fails when the flag is not forwarded.

`prepare` declares no `--format` option, so it has no JSON document to protect
and passes nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using our GitHub Discussions tab for questions.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 8, 2026

This branch was previously deployed

1 inactive deployment
benchmarks — 2fbbf0d2 Deployed Jul 31, 2026 by prisis via Benchmarks #1264
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant