Skip to content

fix(codegen): close the remaining migration findings, add v.from() columns + binding manifest - #335

Merged
prisis merged 16 commits into
alphafrom
worktree-migration-round-3
Aug 3, 2026
Merged

prisis merged 16 commits into
alphafrom
worktree-migration-round-3

Conversation

@prisis

@prisis prisis commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Closes the remaining open findings from a third-party Convex→Lunora port, and adds the two features that port asked for.

Most of what the report claimed was already fixed on alpha — the fail-open codegen, the strict typecheck in CI, the advisor gate, postcodegen on build/prepare/deploy, and four of its eight newest issues. This is the part that genuinely wasn't.

Fixes

A shared validator rendered unknown. const vDoc = v.object({…}) reused across .output() calls reached the parser as a bare Identifier and fell through to the catch-all. unknown doesn't stay contained — a consumer narrowing it gets {} and every property access is an error — so the only way to get a real type was to inline a 20-field literal at every call site. Fixed at the parser, so it covers .input() shapes, columns, and nested v.array(vRow) too.

Argument types were never rebased. Return types climbed out of _generated/; arguments didn't, so a relative import("./lib/…") qualifier in an argument stayed one directory too deep. TS2307 inside a generated file while lunora codegen exits 0 — it only surfaces when a sibling package typechecks the same file.

A type merely imported into the handler leaked unimported. The reachability guard only covered types declared in the handler's own file, so a shared ./lib/types interface — the ordinary way to write one — printed as a bare undeclared identifier.

lunora codegen still needed two passes on a warm tree. The cold-start bootstrap only fired when a generated file was missing, so an ordinary edit (add a table, add a handler returning its Doc) left pass 1 inferring against the previous run's declarations. That's what pushes a project into wrapping the CLI in a run-until-the-hash-stops-changing loop.

Features

v.from() works as a table column. The restriction predated type recovery; a column needs no SQL type of its own, since a shard row is a JSON document and a .global() table maps this like v.object/v.record/v.union. Two consequences are stated rather than hidden: the on-disk form is the JSON encoding, and @lunora/seed refuses such a column by name instead of generating one that fails on insert.

lunora build --emit-bindings <file> writes a JSON manifest of the bindings, crons, vars names, and compatibility settings the bundle needs, for a project running its own IaC. Derived from wrangler.jsonc after the pre-deploy pipeline reconciles it. Every binding is listed including the ones Lunora can't provision — those are exactly the ones an external deployer can create. vars contributes names only.

Linter/formatter ignores. Codegen output is linted like source, so a project's first lint run reports thousands of errors in files nobody wrote (one port measured 23,553). lunora init asks which tools you use; lunora add re-derives it from the manifest with no prompt. Per-tool mechanics were verified against primary sources — oxlint's shipped config schema, Biome's docs, and ESLint's own source, which confirms flat config warns about and ignores .eslintignore, so none is ever written.

Review round

/thermos (both passes) found nine issues in the above, all fixed here:

A v.from() column on a .global() table read back as a JSON string encode is JS-type driven, decode is kind driven, and from was in neither group — it belongs with union/any, since parsing unconditionally would read "123" back as the number 123
Column types were the one un-rebased position the same bug class this PR fixes for arguments, in the slot the column feature newly opened
The scope probe leaked one generic deep Wrapper<import("./x").Bar> cleared itself because the argument supplied the qualifier
Alias resolution swallowed real errors a typo in a hoisted validator rendered unknown while the same typo inline aborted — replaced the catch with a precondition
A failed run committed a torn _generated/ the disk write was never what made the fix work; it moves back to the write phase
lunora add could silently disable a monorepo's linting creating a package-level config shadows the root — ESLint 9 stops at the first flat config walking up, so a file with only ignores switched off every root rule and still exited 0
A created ESLint config was .js the body is ESM; without "type": "module" Node loads it as CJS and ESLint dies
lunora init --dry-run wrote to the user's project the one post-scaffold step without a guard
The manifest cried wolf on $schema, dropped env.*/assets, and invented {"binding": ""} all three now reported or modelled

Two reviewer findings were not applied, with reasons: the MySQL LONGTEXT mapping for from is correct (a JSON column rejects the bare string a scalar schema stores), and the runtime package-extension path genuinely cannot recover a tsType (~standard.types.output is types-only). Both are now commented so they aren't re-filed.

Verification

All touched suites pass — codegen 1053, cli 1072, config 578, server 568, d1 238, values 172, sql-store 99, seed 79, hyperdrive 64. Lint, types, api:check (additive only), dist:check after a prod build, lint:package-json, lint:registry:sync all green, and regenerating every examples/*/lunora/_generated/ produces zero drift.

🤖 Generated with Claude Code

https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347

Summary by CodeRabbit

  • New Features
    • Automatically detects supported lint and formatting tools and configures generated paths to be ignored.
    • Adds portable Cloudflare resource requirement manifests.
    • Supports Standard Schema validators in table columns and generated database handling.
    • Adds typed service-binding clients for calling public actions, mutations, and queries.
  • Bug Fixes
    • Improves generated type imports, validator resolution, and schema-relative paths.
    • Keeps generated declarations synchronized during every code generation run.
  • Documentation
    • Clarifies storage, seeding, and usage behavior for Standard Schema validators.

prisis and others added 11 commits August 3, 2026 10:07
A validator written once and reused — `const vDocumentDoc = v.object({…})`,
then `.output(v.union(vDocumentDoc, v.null()))` — reached the parser as a bare
`Identifier`, which is not a `CallExpression`, so it fell through to the
`{ kind: "any" }` catch-all and rendered `unknown` in the generated api.

`unknown` does not stay contained: a consumer narrowing it gets `{}`, and every
property access on that is an error. The only workaround was to inline the
object literal at every call site, giving up the one place a table's public
shape is defined.

Resolution goes through the symbol (with `getAliasedSymbol` for an import), so
a validator imported from a sibling module resolves like a local one, and it
applies to every validator position — `.input()` shapes, table columns, and
nested `v.array(vRow)` arguments all route through the same parser and degraded
the same way. A const holding something the parser does not recognise keeps the
previous behaviour rather than aborting the run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
The type checker prints a type relative to the module it was read in, so a
recovered `v.from(externalSchema)` whose type names something from the
handler's own `./lib/…` renders as `import("./lib/tools").Tool`. Inlined
verbatim into `lunora/_generated/api.ts` that resolves to
`lunora/_generated/lib/tools`, which does not exist.

Return types were already rebased against the output directory; argument types
were not, so the same qualifier in an argument position stayed one directory
too deep. That is a TS2307 inside a generated file while `lunora codegen` exits
0, which is why it only surfaces when a sibling package typechecks the same
file and has nowhere to filter the error away.

The generated-vs-user rebase order is load-bearing, so the pair now lives
behind one helper applied to arguments, returns, and HTTP stream chunk types
alike.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
The reachability guard only treated a type as unprintable when it was declared
in the handler's OWN file. A type declared elsewhere in user code but imported
into that file is equally nameable there, so the checker prints it bare too —
and a generated file imports nothing from the user's modules, so the bare name
lands in `api.ts`/`functions.ts` as an undeclared identifier (TS2304). A shared
`./lib/types` interface is the ordinary way to write one, so this was easy to
hit.

Bare-vs-qualified is now decided by asking the checker what it renders: an
out-of-scope type comes back carrying an `import("…")` qualifier, which the
emitter rebases instead, so only the qualifier-free rendering is expanded.

`_generated/` declarations are excluded — the emitter deliberately imports
`Doc`/`Id` by name, and expanding them instead discards a branded `Id` (not an
expandable object) and falls back to `unknown`, which collapses every
`Doc`/`Id`-shaped return type at once.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
Codegen infers each handler's return type against the ts-morph project as it
stands when `discoverFunctions` runs. Everything a handler's type can depend on
— `Doc`/`Id` from `dataModel.ts`, the schema-typed `ctx.db` and its paginated
results from `server.ts` — lives in those two files, so whatever version of them
the project happens to hold is what pass 1 sees.

Emitting them only on a cold start was not enough. An ordinary edit — add a
table, add a handler returning a row from it — left pass 1 inferring against the
previous run's declarations, which name neither the new table nor its `Doc`. The
return collapsed to `unknown`/`{}` and the collapse was written into `api.ts`,
so the tree converged only on a second run. That is what pushes a project into
wrapping the CLI in a run-until-the-hash-stops-changing loop.

Both files are pure functions of inputs that never depended on `discoverFunctions`,
so their discovery is hoisted above it and each is now rendered exactly once,
before inference. Rendering unconditionally costs nothing extra: these are the
same two strings the run emits anyway, and `writeIfChanged` no-ops when the bytes
match, so an unchanged project touches neither disk nor any watcher.

Syncing the project copy uses in-place `replaceWithText` rather than
`createSourceFile` with overwrite. The latter swaps in a new `SourceFile`, so
already-loaded handler modules keep pointing at the orphaned one and their
`dataModel` type import stops resolving — which collapses every `Doc`/`Id`-shaped
return type in the run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
`v.from(externalSchema)` was args-only, so a project that needs both validator
languages — commonly because an SDK's types demand zod — had to maintain the
same shape twice, in two languages, and hope they stayed in step. Inlining the
`v.*` equivalent at the column was the only option, which gives up the one place
the shape is defined.

The restriction existed because a column needs a type and codegen could not
recover one from an external schema. It can now, through
`~standard.types.output`, and a column needs no SQL type of its own: a shard row
is a JSON document, and a `.global()` table maps this to a JSON text column
exactly like `v.object`/`v.record`/`v.union` already do. So the emitted drizzle
column carries the recovered type as its `$type<…>()` annotation instead of
`unknown`, and the runtime validates through the wrapped schema as before.

Two consequences stated rather than hidden. The on-disk form is the JSON
encoding of whatever the external schema produces, so `v.from(z.string())` holds
`"x"` rather than a bare TEXT `x` — use `v.string()` when the plain column type
matters. And `@lunora/seed` cannot introspect an external schema to invent a
conforming value, so it now refuses such a column by name rather than generating
one that fails validation on the very next insert.

`isOrWrapsFromValidator` keeps its export — nothing calls it from `defineTable`
any more, but it remains the way tooling asks whether a value is validated
externally.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
`lunora deploy` is the batteries-included path: infer, reconcile, provision,
publish. A project running its own infrastructure-as-code wants only the first
half of that — the bundle — plus a statement of what the bundle expects to be
bound to, so its own program can create the resources.

Without one, those requirements get restated by hand in the IaC program and the
two drift silently: a binding added on one side is simply missing on the other,
and the failure lands at runtime as an undefined `env.X`.

`lunora build --emit-bindings <file>` writes a JSON manifest of the bindings,
crons, `vars` names, and compatibility settings the built Worker needs. It is
derived from `wrangler.jsonc` AFTER the pre-deploy pipeline has reconciled it,
because that is the point at which the config IS the resolved answer — reading
it earlier would describe what the project happened to write down rather than
what the bundle actually needs.

Three decisions worth stating:

- Every binding is listed, including the ones Lunora cannot provision (KV,
  Hyperdrive and Vectorize ids it warns about and never writes). Those are
  precisely the ones an external deployer CAN create.
- An unrecognised wrangler section is reported in `unknown` and warned about
  rather than dropped, so a binding type added to wrangler before it is added
  here degrades to a name instead of vanishing into an under-provisioned deploy.
- `vars` contributes names only. The manifest is committed and read by CI, and a
  var can hold a value a project would rather not publish.

A project with no wrangler config fails the flag instead of writing an empty
manifest — "this Worker needs nothing" is the one answer a deployer must never
be handed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
Codegen output lands in the repo and is linted like source, so a project's first
lint run reports thousands of errors in files nobody wrote — one port measured
23,553, effectively all of them from generated output. Every consumer
independently rediscovers the same five paths.

`.gitignore` does not cover it. Two of the paths are committed on purpose (the
schema-drift baseline is the whole point of the deploy gate), and a project may
legitimately commit `_generated/` so the API surface is reviewable — at which
point every gitignore-derived exclusion stops applying.

`detectLintTools` reads both the manifest and the config files on disk: a
dependency without a config is a tool about to be configured, and a config
without a dependency is one installed globally or hoisted from a monorepo root.
Missing either signal means silently skipping a tool the project runs.

`applyLintIgnores` writes each tool's own mechanism, verified rather than
assumed:

- Prettier gets `.prettierignore`.
- oxlint gets `ignorePatterns` in `.oxlintrc.json`, the key its published
  configuration schema declares.
- Biome v2 has no ignore key — exclusions are negated patterns in
  `files.includes`, seeded with `**` so they have something to subtract from.
  v1's `files.ignore` is still in the wild, so the writer follows whichever key
  the config already uses instead of sniffing a version.
- ESLint gets an `eslint.config.js` when the project has none, and is reported
  as `manual` with a paste-ready snippet when it already has one — a flat config
  is arbitrary JavaScript and is not something to rewrite on a user's behalf.

No `.eslintignore` is ever written. Flat config removed support for it, and
ESLint warns about the file while ignoring its contents, so creating one would
leave behind something that looks like it works.

Every writer appends only what is missing, so re-running is a no-op.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
Two entry points, because they know different things.

`lunora init` asks. A template ships no lint tooling, so at scaffold time there
is usually nothing to detect — the answer is the developer's, not the
filesystem's. Whatever IS detectable pre-selects the prompt, so it confirms
rather than guesses, and a non-interactive run configures the detected set
instead of blocking automation on a question.

`lunora add` does not ask. It already refuses to run outside a Lunora project,
so the manifest answers the question, and prompting on every feature install
would be noise. It re-runs after each successful add because that is exactly
when the generated surface grows — and because a team that adopted Prettier or
Biome after `init`, or ported an existing app in, would otherwise never be
configured at all.

Both go through the same writers, which append only what is missing, so the
common case is silent. Where the change cannot be made safely — an existing
ESLint flat config, which is arbitrary JavaScript — the exact snippet is printed
rather than the omission left to surface as a few thousand lint errors.

The lint prompt gets its own injection point rather than reusing the feature
offer's: that one is pinned to the feature value union, so sharing it would only
typecheck through a cast.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
`sqliteEncode` keys off the runtime JS type; `sqliteDecode` keys off the
validator kind, and `from` was in neither group — so it fell through to
"verbatim" and a `.global()` column stored as JSON came back as the raw string.
The generated `Doc_*` and the drizzle `$type<…>()` both promise the object, so
every consumer type-checks clean and fails at the first property access. One
decoder backs D1, Postgres, MySQL, the studio data browser, and admin export
alike, so the miss reached all of them.

`from` joins `union`/`any` rather than `object`/`array`/`record`: an external
Standard Schema can describe a string as easily as an object, and since encode
is JS-type driven, parsing unconditionally would read a `v.from(z.string())`
column holding "123" back as the NUMBER 123. The union rule parses only a stored
JSON non-scalar, which round-trips both shapes.

The MySQL dialect's LONGTEXT mapping is correct for the same reason and now says
so — a `JSON` column would reject the bare string at insert.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
…ed atomic

Four fixes to the codegen changes earlier on this branch.

**Column types were never rebased.** `api.ts`/`functions.ts` route argument and
return types through the relative-qualifier rebase; `dataModel.ts` and the
drizzle view did not, because a `v.from()` column was rejected at runtime and the
path was unreachable. Allowing the column opened it: a recovered type naming the
schema module's own `./lib/…` landed verbatim one directory too deep — TS2307
inside a generated file while codegen exits 0. Both emitters now rebase against
`schema.ts`, applied to the whole rendered file so a future column-rendering path
cannot miss it. `emitCollections` was the last un-rebased argument site.

**The reachability probe conflated a type with its type arguments.** Deciding
"printed bare" by scanning the rendered text for `import(` cleared an imported
`Wrapper<import("./x").Bar>`, because the ARGUMENT supplied the qualifier — so
the wrapper printed bare and became TS2304, the same bug class one generic deep.
It now asks the handler's source file whether it imports the name, which is
depth-independent.

**Alias resolution swallowed real errors.** A catch around the recursive parse
also caught `Unsupported validator kind` raised by a typo inside a hoisted
validator, so `const vRow = v.object({ x: v.strng() })` rendered `unknown` while
the identical expression written inline aborted the run. Two forms that are meant
to be interchangeable must not diverge on the error path. Replaced with a
precondition — the target must look like a `v.*` chain — so anything past the
gate throws exactly as the inline form does.

**A failed run committed a torn `_generated/`.** Writing the declaration surface
before inference meant any later throw left a new `dataModel.ts` beside a stale
`api.ts`/`shard.ts`; worst on a table removal, where `Doc_x` vanishes while its
referrers stay and the errors point at generated code rather than the cause. The
disk write was never what made the fix work — `discoverFunctions` reads the
ts-morph project, which the in-memory sync feeds — so the writes move back to the
write phase and the run is all-or-nothing again.

Also removes a 27-line comment describing the deleted cold-start bootstrap, which
asserted the opposite of what now runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
…ctory

`detectLintTools` fires on a declared dependency alone — deliberately — but in a
monorepo the dependency sits in the package while the config sits at the root.
The writers then created a config in the directory they were handed, which does
not add ignores there: it SHADOWS the root. ESLint 9 stops at the first flat
config walking up, so a package-level file holding only `ignores` and no rules
silently switched off every rule the root enforced, and lint still exited 0.
Biome and oxlint replace an outer rule set the same way. `lunora add` ran this
with no prompt and no opt-out.

Configs are now resolved by walking up to the repository boundary. A config found
above the project is reported with a paste-ready snippet, never duplicated
downward; creation is reserved for the case it was meant for — a standalone
project with nothing above it. `.prettierignore` is exempt: it only ever adds
exclusions and resolves from the working directory, so a nested one cannot
disable anything.

A created ESLint config is now `eslint.config.mjs`. The body is ESM, and a `.js`
config in a package without `"type": "module"` is loaded as CommonJS, where
ESLint dies on `Unexpected token 'export'`.

`lunora init --dry-run` no longer writes. It was the one post-scaffold step
without a guard, and `--in-place --dry-run` targets the user's existing repo.

The manifest gains three corrections: `$schema` is no longer reported as
unmodelled on every real project (it heads every scaffolded wrangler config, and
crying wolf trains users to ignore the one signal the design depends on); `env.*`
and `assets` are no longer silently dropped as non-binding settings — `assets` is
modelled, `env` is reported; and an entry with no binding name is reported rather
than emitted as `{"binding": ""}`, which hands an IaC program a resource it
cannot wire.

Internals: the four parallel per-tool maps collapse to one table, the duplicated
dependency reader gives way to the package's own `readProjectDependencyNames`,
the two copies of the outcome-reporting loop become one helper, `collectBindings`
splits into three functions and drops its complexity suppression, and
`writeBindingManifest` returns a typed result instead of "a string means failure".

`@lunora/seed`'s refusal message now names escapes the seeder actually offers
(`overrides`, `only`) instead of one it does not.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
@netlify

netlify Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit 403f403
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a70c505d537c00008f87cc6
😎 Deploy Preview https://deploy-preview-335--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

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@prisis, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 5 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7c8bcff3-e418-4def-abf3-7e54c745136d

📥 Commits

Reviewing files that changed from the base of the PR and between eb88142 and 403f403.

📒 Files selected for processing (4)
  • apps/docs/src/content/docs/concepts/data-types.mdx
  • apps/docs/src/content/docs/concepts/generated-code.mdx
  • apps/docs/src/content/docs/concepts/monorepos-and-iac.mdx
  • apps/docs/src/content/docs/concepts/typescript.mdx

Walkthrough

The PR adds lint-ignore setup to CLI commands, restructures declaration discovery and emission, improves validator-aware code generation, supports v.from() columns, adds a typed service-binding client, and introduces a deterministic Cloudflare binding manifest API.

Changes

Lint configuration

Layer / File(s) Summary
Lint detection and configuration writers
packages/config/src/lint-ignores.ts, packages/config/src/index.ts
Detects supported lint tools, updates ignore settings, and reports manual configuration requirements.
CLI lint-ignore orchestration
packages/cli/src/commands/add/handler.ts, packages/cli/src/commands/init/..., packages/cli/src/util/lint-ignore-report.ts
Runs lint-ignore setup after successful add and init extras. Supports prompts, dry runs, and outcome reporting.

Validator-aware code generation

Layer / File(s) Summary
Validator resolution and type reachability
packages/codegen/src/parse-validator.ts, packages/codegen/src/resolve-package-extension.ts, packages/codegen/src/discover-functions.ts
Resolves validator aliases with cycle guards and detects imported user-defined types unavailable to generated files.
Declaration synchronization and discovery pipeline
packages/codegen/src/declaration-surface.ts, packages/codegen/src/run-codegen.ts
Builds declarations in memory, synchronizes them before discovery, applies platform-gated values, and writes them during final emission.
Relative qualifier rebasing
packages/codegen/src/emit.ts
Rebases relative type qualifiers across generated APIs, collections, streams, callers, data models, and Drizzle output.
Standard Schema column and value handling
packages/seed/src/generate-value.ts, packages/server/src/schema.ts, packages/sql-store/src/value-codec.ts, packages/values/src/v.ts, packages/hyperdrive/src/global-dialect.ts
Allows v.from() columns, defines storage and decoding behavior, and rejects unsupported seed generation.

Service-binding client

Layer / File(s) Summary
Typed service-binding RPC client
packages/client/src/service.ts, packages/client/package.json, packages/lunora/src/client/service.ts, packages/lunora/package.json, apps/docs/src/content/docs/concepts/monorepos-and-iac.mdx
Adds typed action, mutation, and query calls through service bindings, with wire encoding, error reconstruction, shard routing, package exports, and documentation.

Cloudflare binding manifest

Layer / File(s) Summary
Manifest contracts and binding collection
packages/config/src/cloudflare/binding-manifest.ts
Defines manifest contracts and collects Wrangler bindings, Durable Object metadata, queues, singleton capabilities, and unknown sections.
Manifest assembly and public exports
packages/config/src/cloudflare/binding-manifest.ts, packages/config/src/cloudflare/index.ts
Builds deterministic manifests with selected metadata and sorted variable names, then exports the public API.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant LintToolDetection
  participant ApplyLintIgnores
  participant Logger
  CLI->>LintToolDetection: detectLintTools(projectRoot)
  CLI->>ApplyLintIgnores: apply selected tools
  ApplyLintIgnores-->>Logger: return and report outcomes
Loading
sequenceDiagram
  participant RunCodegen
  participant DeclarationSurface
  participant DiscoverFunctions
  participant Emit
  RunCodegen->>DeclarationSurface: build declarations in memory
  RunCodegen->>DiscoverFunctions: discover from synchronized declarations
  DiscoverFunctions-->>RunCodegen: return functions and metadata
  RunCodegen->>Emit: render generated output
Loading
sequenceDiagram
  participant Worker
  participant ServiceBinding
  participant ServiceClient
  Worker->>ServiceClient: call typed action, mutation, or query
  ServiceClient->>ServiceBinding: fetch encoded RPC request
  ServiceBinding-->>ServiceClient: return encoded result or remote error
  ServiceClient-->>Worker: decode value or reconstruct LunoraError
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 codegen fixes and the two major added features: v.from() columns and binding manifests.
Description check ✅ Passed The description provides a detailed summary, review context, and verification results, but it omits the template's explicit checklist and CLA section.
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 worktree-migration-round-3

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.

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@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: 6

🧹 Nitpick comments (3)
packages/config/src/cloudflare/binding-manifest.ts (2)

57-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add workflow to the resource field doc.

The resource doc lists d1, analytics_engine, queue, vectorize, and pipelines, but omits workflow. workflows in ARRAY_SECTIONS (Line 197) sets resourceKey: "name", so the workflow name also lands in resource. Update the comment to list it.

📝 Proposed doc fix
-    /** Bucket name (`r2`), database name (`d1`), dataset (`analytics_engine`), queue name (`queue`), index (`vectorize`), pipeline (`pipelines`). */
+    /** Bucket name (`r2`), database name (`d1`), dataset (`analytics_engine`), queue name (`queue`), index (`vectorize`), pipeline (`pipelines`), workflow name (`workflow`). */
🤖 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/binding-manifest.ts` around lines 57 - 58,
Update the resource field documentation in the binding manifest type to include
workflow among the supported resource kinds, preserving the existing list and
wording.

253-302: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse readString instead of re-implementing the empty/undefined check.

collectDurableObjectBindings (Line 258: entry.name === undefined || entry.name === "") and collectQueueBindings (Line 282, Line 293) duplicate the same "missing or empty string" check that readString (Lines 216-220) already implements. Consolidating onto readString removes three duplicated conditionals and keeps the "no binding name" rule in one place, consistent with the "Follow DRY principles" requirement.

♻️ Proposed refactor using `readString`
 const collectDurableObjectBindings = (config: ManifestConfigShape, unnamed: string[]): BindingRequirement[] => {
     const sqlite = sqliteClassNames(config);
     const out: BindingRequirement[] = [];

     for (const entry of config.durable_objects?.bindings ?? []) {
-        if (entry.name === undefined || entry.name === "") {
+        const binding = readString(entry, "name");
+        if (binding === undefined) {
             unnamed.push("durable_objects");
             continue;
         }

         out.push({
-            binding: entry.name,
+            binding,
             className: entry.class_name,
             sqlite: entry.script_name === undefined && entry.class_name !== undefined ? sqlite.has(entry.class_name) : undefined,
             type: "durable_object",
         });
     }

     return out;
 };

 const collectQueueBindings = (config: ManifestConfigShape, unnamed: string[]): BindingRequirement[] => {
     const out: BindingRequirement[] = [];

     for (const entry of config.queues?.producers ?? []) {
-        if (entry.binding === undefined || entry.binding === "") {
+        const binding = readString(entry, "binding");
+        if (binding === undefined) {
             unnamed.push("queues.producers");
             continue;
         }

-        out.push({ binding: entry.binding, resource: entry.queue, type: "queue_producer" });
+        out.push({ binding, resource: entry.queue, type: "queue_producer" });
     }

     for (const entry of config.queues?.consumers ?? []) {
-        if (entry.queue === undefined || entry.queue === "") {
+        const queue = readString(entry, "queue");
+        if (queue === undefined) {
             unnamed.push("queues.consumers");
             continue;
         }

-        out.push({ binding: entry.queue, resource: entry.queue, type: "queue_consumer" });
+        out.push({ binding: queue, resource: queue, type: "queue_consumer" });
     }

     return out;
 };
As per path instructions, "`packages/**/*.ts`: Review TypeScript code following the project's coding guidelines: ... Follow DRY principles".
🤖 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/binding-manifest.ts` around lines 253 - 302,
Reuse the existing readString helper in collectDurableObjectBindings and both
producer/consumer loops within collectQueueBindings to normalize binding names
before validation. Replace the duplicated undefined-or-empty checks with the
helper’s result, preserving the current unnamed.push behavior and using the
normalized value for emitted binding fields.

Source: Path instructions

packages/config/src/lint-ignores.ts (1)

281-287: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the negation-pattern transform into a helper.

The pattern entry.endsWith("/") ? \${entry}**` : entryappears here (Line 286), again inapplyBiome(Line 334), and again ineslintIgnoresSnippet` (Line 348). If the trailing-slash convention changes, one copy is easy to miss.

♻️ Proposed refactor
+/** Turn a gitignore-style path into a negated Biome/ESLint pattern. */
+const negatedPattern = (entry: string): string => `!${entry.endsWith("/") ? `${entry}**` : entry}`;
+
 const biomeIgnoresSnippet = (): string =>
     jsonIgnoresSnippet(
         "files.includes",
-        LUNORA_IGNORED_PATHS.map((entry) => `!${entry.endsWith("/") ? `${entry}**` : entry}`),
+        LUNORA_IGNORED_PATHS.map(negatedPattern),
     );

As per path instructions, "Follow DRY principles."

🤖 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/lint-ignores.ts` around lines 281 - 287, Extract the
trailing-slash negation transformation into a shared helper, then reuse it in
biomeIgnoresSnippet, applyBiome, and eslintIgnoresSnippet. Remove the duplicated
entry.endsWith("/") logic while preserving the existing pattern output for all
ignored paths.

Source: Path instructions

🤖 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/codegen/src/emit.ts`:
- Around line 5614-5619: Adopt the verbatim-scalar contract for from columns: in
packages/codegen/src/emit.ts lines 5614-5619, update the from case to emit plain
text without mode: "json" while preserving the $type annotation; in
packages/values/src/v.ts lines 1109-1114, revise the Columns store JSON
documentation to state that non-scalars are JSON-encoded while scalars are
stored verbatim, including the bare x behavior for v.from(z.string()).

In `@packages/codegen/src/run-codegen.ts`:
- Around line 840-842: Correct the phase-boundary comment near the
dataModel.ts/server.ts rendering logic to remove the claim that those files are
already written; state only that they are rendered and synchronized in memory
before inference. Preserve the existing disk writes in the !options.dryRun block
and keep the comment consistent with the docblock around the rendering phase.

In `@packages/config/src/cloudflare/binding-manifest.ts`:
- Around line 182-198: Update ARRAY_SECTIONS and the related
collectArrayBindings flow so containers are not treated as standalone binding
requirements: either remove the containers row or explicitly correlate each
containers entry by class_name with its matching durable_objects binding. Ensure
valid container configuration is no longer added to unnamed and is represented
through the actual bindable durable-object requirement.

In `@packages/config/src/lint-ignores.ts`:
- Around line 394-403: This issue spans three files. At
packages/config/src/lint-ignores.ts L394-L403, update the applyLintIgnores
function to catch errors from each writer invocation inside the map operation
and return a failure-style outcome for that tool instead of throwing, ensuring
one tool's I/O error does not prevent other tools from being configured. At
packages/cli/src/commands/add/handler.ts L249-L264, wrap the syncLintIgnores
call in a try/catch block and log a warning on error without re-throwing, so
lint-ignore write failures do not overturn the already-successful add command
result. At packages/cli/src/commands/init/handler.ts L1153-L1176, wrap the
offerLintIgnores call (or its internal offerLintTools invocation) in a try/catch
block and log a warning on error without re-throwing, so lint-ignore write
failures do not overturn the already-completed scaffold and registry-extras
steps.
- Around line 311-344: Update the action === "report" branch in applyBiome to
inspect the inherited config at path before selecting the manual snippet. If its
files object contains an existing files.ignore array, return
jsonIgnoresSnippet("files.ignore", LUNORA_IGNORED_PATHS); otherwise retain
biomeIgnoresSnippet() using files.includes.

In `@packages/values/src/v.ts`:
- Around line 1109-1114: Update the docblock describing column storage near the
v.from documentation to match sqliteEncode and mysqlColumnType: non-scalar
values use JSON encoding, while scalar values are stored according to their
runtime JavaScript type, such as a string being stored as bare text rather than
JSON-quoted text. Preserve the guidance about using v.string() when a plain
column type is required.

---

Nitpick comments:
In `@packages/config/src/cloudflare/binding-manifest.ts`:
- Around line 57-58: Update the resource field documentation in the binding
manifest type to include workflow among the supported resource kinds, preserving
the existing list and wording.
- Around line 253-302: Reuse the existing readString helper in
collectDurableObjectBindings and both producer/consumer loops within
collectQueueBindings to normalize binding names before validation. Replace the
duplicated undefined-or-empty checks with the helper’s result, preserving the
current unnamed.push behavior and using the normalized value for emitted binding
fields.

In `@packages/config/src/lint-ignores.ts`:
- Around line 281-287: Extract the trailing-slash negation transformation into a
shared helper, then reuse it in biomeIgnoresSnippet, applyBiome, and
eslintIgnoresSnippet. Remove the duplicated entry.endsWith("/") logic while
preserving the existing pattern output for all ignored paths.
🪄 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: c93d4c13-a15a-476f-b206-66584b8ea12d

📥 Commits

Reviewing files that changed from the base of the PR and between 4a92b51 and 4f65e45.

⛔ Files ignored due to path filters (14)
  • api-snapshots/cli.api.md is excluded by none and included by none
  • api-snapshots/config.api.md is excluded by none and included by none
  • packages/cli/__tests__/commands/add-lint-ignores.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/cli/__tests__/commands/build.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/cli/__tests__/commands/init/offer-lint-tools.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/cli/src/commands/build/handler.ts is excluded by !**/build/** and included by packages/**
  • packages/cli/src/commands/build/index.ts is excluded by !**/build/** and included by packages/**
  • packages/codegen/__tests__/run-codegen-cold-start.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/run-codegen.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/config/__tests__/cloudflare/binding-manifest.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/config/__tests__/lint-ignores.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/seed/__tests__/generate-value.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/server/__tests__/schema.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/sql-store/__tests__/value-codec.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
📒 Files selected for processing (18)
  • packages/cli/src/commands/add/handler.ts
  • packages/cli/src/commands/init/handler.ts
  • packages/cli/src/commands/init/offer-lint-tools.ts
  • packages/cli/src/util/lint-ignore-report.ts
  • packages/codegen/src/discover-functions.ts
  • packages/codegen/src/emit.ts
  • packages/codegen/src/parse-validator.ts
  • packages/codegen/src/resolve-package-extension.ts
  • packages/codegen/src/run-codegen.ts
  • packages/config/src/cloudflare/binding-manifest.ts
  • packages/config/src/cloudflare/index.ts
  • packages/config/src/index.ts
  • packages/config/src/lint-ignores.ts
  • packages/hyperdrive/src/global-dialect.ts
  • packages/seed/src/generate-value.ts
  • packages/server/src/schema.ts
  • packages/sql-store/src/value-codec.ts
  • packages/values/src/v.ts

Comment thread packages/codegen/src/emit.ts Resolved
Comment thread packages/codegen/src/run-codegen.ts Resolved
Comment thread packages/config/src/lint-ignores.ts Resolved
Comment thread packages/config/src/lint-ignores.ts Resolved
Comment thread packages/values/src/v.ts Resolved
@codspeed

codspeed Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 11.88%

⚠️ 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

⚡ 3 improved benchmarks
✅ 250 untouched benchmarks
⏩ 10 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ 1 shard × 1000 rows (single round-trip) 3.1 ms 2.7 ms +15%
⚡ baseline (Object.keys + toInternal + path spread per field) 72.1 µs 65.2 µs +10.64%
⚡ 1 after-insert no-op trigger 433.9 µs 394.2 µs +10.06%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing worktree-migration-round-3 (403f403) with alpha (b52bcac)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 (4a92b51) during the generation of this report, so b52bcac was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

…gen (#336)

* refactor(codegen): extract the declaration-surface phase from runCodegen

`runCodegen` was 619 lines carrying a `sonarjs/cognitive-complexity`
suppression whose stated reason was that splitting it "would obscure the linear
pipeline". The previous commit disproved that: it moved ~130 lines of discovery
from the middle of the function to the top, and that the move was mechanically
possible is the evidence a seam was already there.

The seam is the ordering constraint the reorder existed to satisfy. Everything
feeding `dataModel.ts`/`server.ts` must run before `discoverFunctions` infers
against them, and — the half that makes the split safe — none of it may depend
on inference. `buildDeclarationSurface` is now that phase by construction rather
than by comment: it cannot read the discovered functions, because it does not
receive them.

The thirteen `const hasX = featureUsage.x` aliases are gone. Each restated one
map lookup and carried a comment explaining the capability rather than the
alias, so call sites read `featureUsage.<key>` directly. The three that were
never plain lookups keep their own fields and say why: `hasBrowser` (a sandbox
tool drives it too), `hasFlags` and `hasNotify` (gated on the module file
existing, not on code usage — the ShardDO imports their default export, so
wiring the ctx without the module emits a broken import).

`emitServer`/`emitShard`/`emitApp` signatures are untouched, so goldens and the
emit tests are unaffected. `assertNoWorkflowAgentCollision` moves with the
discovery it guards and is no longer exported — nothing outside used it.

runCodegen 619 → 474 lines; the new module is 290. Behaviour is unchanged:
1053 codegen tests pass, and regenerating every example's `_generated/` produces
byte-identical output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347

* feat: portable generated API surface + typed service-binding client (#337)

* feat(codegen): make dataModel.ts compilable without a server dependency

`api.ts` imports `dataModel.ts` for `Doc`/`Id`, and `dataModel.ts` imported
`@lunora/server/data-model`. So a sibling package — a web app, another Worker —
that only wanted the typed `api` had to install and compile a SERVER package to
get a branded string and a few interfaces. That is the raw-TS coupling issue #18
narrowed but did not remove.

The half that needs the server package is the query-DSL binding layer:
`WithArg`, `LoadWith`, the reader/writer facades, the ORM builders, and the
`Where`/`SearchReader` re-exports. None of it is referenced outside `server.ts`,
which is the server-only file already — so it moves there, and `dataModel.ts` is
left with the schema's own shapes and no imports at all.

That is asserted directly rather than implied: the new test reads the emitted
`dataModel.ts` and requires it to contain no import statement and no mention of
`@lunora/server` or `lunorash/server`.

`emitDataModel` loses its `useUmbrella` parameter, which only ever chose between
two specifiers it no longer emits.

Users importing the moved types from `./_generated/dataModel` must import them
from `./_generated/server` instead. Pre-1.0, and the split is the point: the file
a consumer compiles should not name a package it cannot install.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347

* feat(client): add a typed service-binding client for worker→worker calls

`ctx.run*` covers calls within one Lunora app. A sibling Worker in the same
account had nothing, so the documented path was the callee's public HTTPS route
— which teams reached with a plain fetch and a hand-rolled HMAC. That pays a
per-request fee, a public-internet round trip, and the upkeep of a shared secret
for a call between two Workers on one account, and because it goes out untyped, a
renamed function surfaces as a runtime 404.

`createServiceClient(env.BACKEND)` types `query`/`mutation`/`action` against the
generated `api`, so the call is checked at compile time. A service binding incurs
no request fee, never leaves the edge, and is authenticated by construction — the
binding IS the capability, so the callee needs no public route.

Three details that would each have been a silent failure:

- Arguments and results go through the same wire codec as the HTTP client. Plain
  JSON cannot carry a `bigint` — `JSON.stringify` throws on one — so skipping it
  would make the money path fail over bindings and nowhere else.
- The response envelope is `{ result }` / `{ error: { code, message, data } }`,
  and errors are reconstructed with their `code` and wire-decoded `data`, so a
  caller across a binding sees what it would see calling in-process.
- A non-JSON reply names the likeliest cause — a binding pointed at a Worker that
  is not this app — because the status alone sends people hunting through the
  callee's handlers instead of their wrangler config.

The binding is accepted structurally as `{ fetch }`: `env.BACKEND` satisfies it
without dragging `@cloudflare/workers-types` into consumers, and a one-method fake
is a complete test double.

Only public functions are reachable; an `internal*` procedure is absent from `api`
and refused by the callee, because a binding is a boundary between deployments
rather than the intra-app `ctx.run*` seam.

Closes the last open half of issue #16 — the docs previously said no such client
existed, and stated the raw-TS coupling that the dataModel split just removed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

---------

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: 5

🧹 Nitpick comments (2)
packages/codegen/src/declaration-surface.ts (2)

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

Hoist the two render calls so the documented order is explicit.

The docblock states that assertRequiredPackages must run before either file is rendered. Today that holds only because emitDataModel (Line 247) and emitServer (Line 258) sit inside the returned object literal, which evaluates after Line 239. A future edit that moves the assertion, or that adds an early return of a partial surface, breaks the invariant with no local signal. Named constants place the ordering in statement form.

♻️ Proposed restructure
     assertRequiredPackages(schema, declaredDependencies);
 
     const hasFlags = existsSync(join(lunoraDirectory, "flags.ts"));
     const hasNotify = existsSync(join(lunoraDirectory, "notify.ts"));
 
+    // Rendered only after `assertRequiredPackages` above — see this function's docblock.
+    const dataModelContent = emitDataModel(schema);
+    const serverContent = emitServer({
+        agents,
+        containers,
+        env,
+        hasAccessFacade: featureUsage.access,
+        // …unchanged options…
+        workflows,
+    });
+
     return {
         agents,
         containers,
-        dataModelContent: emitDataModel(schema),
+        dataModelContent,
         declaredDependencies,

Then reference serverContent in place of the inline emitServer({ … }) call.

🤖 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/codegen/src/declaration-surface.ts` around lines 236 - 258, In the
declaration-surface construction flow, hoist both render calls into named
statements after assertRequiredPackages(schema, declaredDependencies): assign
emitDataModel(schema) to dataModelContent and emitServer(...) to serverContent,
then reference those constants in the returned object. Keep the assertion before
either render and preserve the existing emitServer arguments.

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

Consider 422 instead of 500 for these authoring errors.

All three throws report a user schema mistake: a workflow and an agent share a deployed name, a binding, or a generated class name. The comparable schema-authoring guard in packages/codegen/src/run-codegen.ts (assertNoMaskedShapeTable) uses { status: 422 }. A 500 classifies the same class of fault as an internal failure, which changes how the CLI and any HTTP surface report it.

♻️ Proposed status alignment
-                { status: 500 },
+                { status: 422 },

Apply to all three throws at Lines 83-88, 94-99, and 105-109.

🤖 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/codegen/src/declaration-surface.ts` around lines 83 - 110, Update
all three LunoraError throws for duplicate workflow name, binding, and generated
class checks in the declaration validation flow to use status 422 instead of
500, aligning them with the existing authoring-error behavior used by
assertNoMaskedShapeTable. Preserve the existing error codes and messages.
🤖 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/monorepos-and-iac.mdx`:
- Around line 123-130: Update the documentation snippet around
createServiceClient and the threads query so env.BACKEND is accessed only inside
a handler that receives env, such as the exported fetch handler. Keep client
creation and the query within that handler, and return the resulting threads
response instead of using module-scope code.

In `@packages/client/src/service.ts`:
- Around line 140-158: Validate the value parsed by response.json() as a
non-null object before using the "error" in parsed check, since the remote
response may be null or a scalar. In the service response handling flow,
introduce/use a validated envelope and base the final result return on
envelope.result, while preserving reconstructError for valid error envelopes.
- Around line 91-107: Replace the local reconstructError helper in service.ts
with the shared RPC error reconstruction utility used by the HTTP client. Move
or expose that existing helper from the shared client module, then import and
reuse it so service-binding responses preserve the complete error contract,
including catalog metadata such as hint and docsUrl alongside code and decoded
data.
- Around line 118-138: Update the service binding request in the RPC flow around
encodeWire and binding.fetch to reuse rpcRequestHeaders, preserving the existing
content type while forwarding Client when present, x-lunora-mutation-id,
x-lunora-client-id, and x-d1-bookmark. Ensure the binding request exposes the
same headers consumed by the HTTP RPC path instead of using only content-type.

In `@packages/codegen/src/emit.ts`:
- Around line 2126-2160: Update the generated server export block in emit.ts to
re-export Insert and InsertModel from the configured server data-model
specifier, preserving support for both umbrella and non-umbrella baseSpecifiers
branches. Keep the existing dataModel.js exports unchanged and ensure generated
_generated/server files continue exposing these facade contract types.

---

Nitpick comments:
In `@packages/codegen/src/declaration-surface.ts`:
- Around line 236-258: In the declaration-surface construction flow, hoist both
render calls into named statements after assertRequiredPackages(schema,
declaredDependencies): assign emitDataModel(schema) to dataModelContent and
emitServer(...) to serverContent, then reference those constants in the returned
object. Keep the assertion before either render and preserve the existing
emitServer arguments.
- Around line 83-110: Update all three LunoraError throws for duplicate workflow
name, binding, and generated class checks in the declaration validation flow to
use status 422 instead of 500, aligning them with the existing authoring-error
behavior used by assertNoMaskedShapeTable. Preserve the existing error codes and
messages.
🪄 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: b9fdd409-d3f6-4864-ae86-60607d90f18a

📥 Commits

Reviewing files that changed from the base of the PR and between 4f65e45 and 7dd4bf5.

⛔ Files ignored due to path filters (24)
  • 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
  • examples/auth-playground/lunora/_generated/dataModel.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/blog/lunora/_generated/dataModel.ts is excluded by !**/_generated/** and included by none
  • examples/blog/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/expo/lunora/_generated/dataModel.ts is excluded by !**/_generated/** and included by none
  • examples/expo/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • examples/notify-demo/lunora/_generated/dataModel.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/offline-rejections/lunora/_generated/dataModel.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/payment-demo/lunora/_generated/dataModel.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/realtime-cursors/lunora/_generated/dataModel.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/todo-app/lunora/_generated/dataModel.ts is excluded by !**/_generated/** and included by none
  • examples/todo-app/lunora/_generated/server.ts is excluded by !**/_generated/** and included by none
  • packages/client/__tests__/service.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__/fixtures/simple/expected/_generated/dataModel.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__/relations-compile.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/run-codegen.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
📒 Files selected for processing (6)
  • apps/docs/src/content/docs/concepts/monorepos-and-iac.mdx
  • packages/client/package.json
  • packages/client/src/service.ts
  • packages/codegen/src/declaration-surface.ts
  • packages/codegen/src/emit.ts
  • packages/codegen/src/run-codegen.ts

Comment thread packages/client/src/service.ts Resolved
Comment thread packages/client/src/service.ts Resolved
Comment thread packages/client/src/service.ts Resolved
Comment thread packages/codegen/src/emit.ts Resolved
Adding `@lunora/client/service` without the matching `lunorash/client/service`
mapping broke the umbrella's re-export test, which asserts every upstream subpath
has one unless it is a declared opt-out. That test is the whole reason the gap is
visible rather than shipping as a subpath that resolves for granular installs and
404s for umbrella ones — a `lunorash`-only project would have had no way to reach
the service client at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
Ten of eleven review comments were real; each is fixed below. The eleventh —
"re-export Insert/InsertModel from server.ts" — is skipped: both are still
exported from `dataModel.ts`, and `server.ts` never re-exported them on alpha
either, so nothing was removed.

**The storage contract said two different things.** The `v.from` docblock and the
drizzle emitter both claimed "always JSON", while `sqliteEncode` stores a scalar
verbatim and only JSON-encodes a non-scalar — which is what the value codec and
the MySQL LONGTEXT mapping already documented. The code was right and the public
docblock was wrong, so the docblock now states the real rule. The drizzle column
moves off `mode: "json"` to plain text with the same `$type<…>()` annotation:
json mode would `JSON.parse` a bare `hello` and throw on every read of a
`v.from(z.string())` column.

**Every container was misreported.** The manifest keyed `containers[]` on a
`name` field that wrangler entries do not have — `@lunora/config`'s own
`ContainerEntry` is `{ class_name }` — so each real container fell into
`unnamed`, the manifest inventing a problem. Keyed on `class_name` now, with
`image` as the resource an external deployer has to build or pull.

**A lint-ignore write failure failed the whole command.** `applyLintIgnores` had
no error isolation, and both callers run it AFTER their real work succeeded — so
a read-only directory reported `lunora add` as failed when the feature had
installed fine. Each writer is now isolated and reports a `failed` outcome the
CLI surfaces as a warning.

**Service-client fixes.** Errors now carry `hint`/`docsUrl` from the catalog, not
just `code`/`data`, so a caller across a binding gets the same actionable error
it would get over HTTP. A JSON body that is not an object (`null`, `4`) is
reported instead of crashing on `"error" in parsed`. The deliberate absence of
the client-identity headers is now stated in the code: a service-binding caller
is a server, and inventing a mutation id would fabricate an idempotency key that
dedups unrelated writes.

**Docs.** The service-client snippet built the client at module scope, where
`env` does not exist on Workers — a reader copying it got a reference error.

Also corrects the "(and written)" phase comment, which contradicted the
atomicity docblock 50 lines below it, and the Biome version framing (v1 accepted
`files.includes` too; the writer follows the key, not the version).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
Four pages, two of which asserted the opposite of what now ships.

`concepts/data-types.mdx` and `concepts/typescript.mdx` both stated that
`v.from()` is arguments-only and that `defineTable` throws on one. It is now
allowed as a column, so both say so — with the trade-offs that decide whether you
should reach for it: storage follows the runtime type (a `v.from(z.string())`
column holds a bare `hello`, which is also why it cannot be a Postgres/MySQL
`JSON` column), a comparison index wants a concrete type, `@lunora/seed` refuses
the column by name, and the JSON Schema surface documents it as unconstrained.

`concepts/monorepos-and-iac.mdx` documents `lunora build --emit-bindings`, the
piece that closes the binding-list duplication the rest of that page describes —
including why every binding is listed (the ones Lunora cannot provision are
exactly the ones your program must create), why `vars` contributes names only,
and why a non-empty `unknown` is worth reading before trusting the file.

`concepts/generated-code.mdx` gains three facts a reader currently has to
discover the hard way: `dataModel.ts` imports nothing, so a sibling package
compiles it with `@lunora/client` alone; the linter/formatter configuration
`init` and `add` write, including the two cases reported rather than written and
why no `.eslintignore` is ever created; and that one codegen run converges, so
nobody else builds the run-until-the-hash-stops-changing loop that prompted the
fix.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
@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 — 403f4038 Deployed Aug 3, 2026 by prisis via Benchmarks #1413
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