@quickback-dev/cli 0.56.10 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +20 -1
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/migrate.d.ts +44 -0
  5. package/dist/commands/migrate.d.ts.map +1 -0
  6. package/dist/commands/migrate.js +391 -0
  7. package/dist/commands/migrate.js.map +1 -0
  8. package/dist/commands/migrate.test.d.ts +2 -0
  9. package/dist/commands/migrate.test.d.ts.map +1 -0
  10. package/dist/commands/migrate.test.js +174 -0
  11. package/dist/commands/migrate.test.js.map +1 -0
  12. package/dist/docs/content.js +5 -5
  13. package/dist/docs/content.js.map +1 -1
  14. package/dist/index.js +6 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/lib/audit-canon.d.ts +22 -0
  17. package/dist/lib/audit-canon.d.ts.map +1 -0
  18. package/dist/lib/audit-canon.js +57 -0
  19. package/dist/lib/audit-canon.js.map +1 -0
  20. package/dist/skill/docs/changelog.md +56 -0
  21. package/dist/skill/docs/compiler/definitions/actions.md +39 -3
  22. package/dist/skill/docs/compiler/definitions/schema.md +28 -4
  23. package/dist/skill/docs/compiler/definitions/sealed-protocol.md +14 -0
  24. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +13 -0
  25. package/dist/skill/docs/stack/queues/handlers.md +28 -2
  26. package/package.json +1 -1
  27. package/src/skill/docs/changelog.md +56 -0
  28. package/src/skill/docs/compiler/definitions/actions.md +39 -3
  29. package/src/skill/docs/compiler/definitions/schema.md +28 -4
  30. package/src/skill/docs/compiler/definitions/sealed-protocol.md +14 -0
  31. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +13 -0
  32. package/src/skill/docs/stack/queues/handlers.md +28 -2
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## Unreleased\n\n### Feature areas — hierarchical authz grouping (`_area.ts`)\n\nA folder under `features/` carrying an `_area.ts` (`export default defineArea({...})`) is now\nan **area**: it declares a route prefix + admission lanes (the same shape as a project\nnamespace, incl. `mintScope`/`acceptScope`) and an authz vocabulary — relationships, composed\nroles, named gates, tenant anchors, scope kinds — that every feature inside the folder\nreferences by bare name. The vocabulary is visible to the area's subtree ONLY: the compiler\nchecks every reference channel (access roles/gates/scoped aliases, action `access`/`anchor`,\nfirewall `via`/`{ rule }`/`{ tenant }` arms, `ctx.scope.<kind>` accessors, auth-view tenant\nincludes, realtime handshake roles, table-level namespace lanes, and other `_area.ts` nodes)\nand fails the build on any outside reference. Root `authz` stays the global level, and root\nbodies may reference root-declared names only (no laundering an area name project-wide).\n\nFail-closed rules shipped with it: re-declaring an inherited name is a compile error (no\noverrides in v1); a descendant action whose path opts out of the area prefix must carry an\nexplicit `route: 'self'` marker; relative `path: './…'` resolves against the area prefix with\ndot segments rejected; foreign features can't claim paths (or table-level namespace prefixes)\nunder an area's prefix; nested areas may add vocabulary but not mount a second prefix under a\nmounted ancestor (unlinked parent/child admission never compiles); and area-tree projects\nmust declare `requires: ['feature-areas']` — the marker reaches the compiler through ANY CLI\nversion, so an area-unaware toolchain is rejected instead of silently dropping nested\nfeatures. Area projects also emit a reviewed audit artifact, `quickback/authz-manifest.json`\n(area tree, declared names, member features, area-gated vs self-gated actions, root-config\nnamespace consumers), and the generated `AGENTS.md` gains a feature-areas section.\n\nByte-parity guarantee: a flat root-authz project re-expressed as an area tree compiles to\nbyte-identical output (the emit-site key-order determinism pass from v2 step 0 makes the fold\norder provably irrelevant). See [Feature areas](/compiler/definitions/feature-areas).\n\nOne cosmetic side effect of that determinism pass: the first recompile of an existing project\non this release may reorder generated relationship-table **import lines** (they are now\nemitted in sorted order instead of authz-map insertion order). The reordering is a one-time,\nbehavior-free diff.\n\n### Access rules: named gates (`authz.rules`) and tenant anchors (`authz.tenants`)\n\nTwo new root-`authz` blocks let you declare a row/role rule once and stamp it by name instead\nof copying predicates across files. A **named gate** in `authz.rules` bundles up to three\narms — `who` (roles), `record:` (record-aware predicates), and `firewall` lanes — under one\nname, referenced by bare name in any `access: { roles: [...] }` array (applies who + record)\nand as `{ rule: '<name>' }` in a resource's `firewall:` (splices the lanes into the top-level\nAND array — a reference can only *narrow* row admission, never widen it). A **tenant anchor**\nin `authz.tenants` names the tenant predicate (`{ column, equals }`, claim side locked to\nverified ctx claims) and is written `{ tenant: 'org' }` in firewalls — with an optional\nper-site column override — and `tenant: 'org'` in auth-view includes. Expansion happens at\ncompile time; emitted SQL is byte-identical to the inline spelling.\n\nEverything fails closed: gate/role/scoped-role/`+`/`:` name collisions, `+` hierarchy sugar\ninside rule bodies, `{ rule }` inside `all`/`any` groups, firewall-less gates referenced from\n`firewall:`, firewall-bearing gates on actions or in `masking.show`, and an access-side\nreference to a firewall-bearing gate whose lanes the resource doesn't also stamp are all\ncompile errors. Gates in `realtime.requiredRoles` lower to static who-roles at the handshake;\na declared non-empty list that lowers to nothing is a compile error, never a silent `[]`. A\nnew `AUTHZ_UNKNOWN_ROLE_NAME` warning flags reference-shaped names that resolve to nothing.\nSee [named gates](/compiler/definitions/access#named-gates-authzrules) ·\n[`{ tenant }`](/compiler/definitions/firewall#named-tenant-anchors-tenant) ·\n[`{ rule }`](/compiler/definitions/firewall#named-gate-references-rule).\n\n## v0.55.0 — July 17, 2026\n\n### Generated projects ship an `AGENTS.md`\n\nEvery compiled project now emits an `AGENTS.md` at its root — the file coding agents read first — weaving Quickback's security model and a *\"when to use what\"* decision guide into the output. An agent editing the features is steered to the right primitive: a **view** for a filtered read, a **transition** for a guarded state change, an **action** for custom logic, **guards**/**masking** for field-level control, **named invalidations** for realtime refresh — each with a `docs.quickback.dev` link. It also documents the access tiers (incl. `SESSION`/`SCOPED`), the `WHERE column = value` firewall model with the org-OR-scope `{ any: [...] }` pattern for non-org callers, and the fail-closed coherence guardrail (with the *\"never `exception: true` as a workaround\"* rule). Regenerated on every compile.\n\n## v0.54.0 — July 17, 2026\n\n### Realtime: named invalidations\n\nActions can now fire typed, targeted *\"this changed — refresh\"* signals after commit. A `defineRealtime` registry declares typed events (wire name, contract `version`, named variants with strict Zod payloads); a `defineRealtimeDelivery` profile sets the maximum audience (a scope room or the org/user lane + required roles); and an optional `defineRealtimeRecipients` resolver narrows delivery to a resolved identity set — post-commit on the firewalled db, intersecting `scope ∩ roles ∩ recipients`, fail-closed (a throw or `[]` reaches nobody, never a wider audience). Bind them with `invalidates:` on an action and call `invalidate.<binding>.<variant>(payload)` inside `execute`. Delivery is after-commit + best-effort (discarded on throw/dryRun), projects the payload to declared keys, and works on every action kind — standalone, per-record, bulk, and namespace-hoisted. See [Named invalidations](/stack/realtime/named-invalidations).\n\n### Access: `SESSION` and `SCOPED` pseudo-role tiers\n\n`AUTHENTICATED` is now explicitly the wrapper over two auth flavors: **`SESSION`** (a full Better Auth session only) and **`SCOPED`** (a sessionless scope-token principal only — e.g. an event attendee with no account). Use the specific tier when a route must admit or exclude one flavor; `AUTHENTICATED` still admits both and excludes only external delegated principals. See [Access → Pseudo-roles](/compiler/definitions/access).\n\n### Access: fail-closed scope/firewall coherence guardrail\n\nGranting a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) on a resource whose firewall can't filter that caller now **fails the build** instead of silently returning `200 + []` — the trap that pushes apps toward a fake \"active organization.\" The fix is named in the error: compose org **or** scope in an `{ any: [...] }` firewall group, use a `via:` relationship, or `firewall: [{ exception: true }]`.\n\n## v0.53.0 — July 17, 2026\n\n### Realtime: the broadcast surface tracks `contract.version`\n\nThe `/api` and `/auth` bases already move to `/api/v2` and `/auth/v2` under\n`contract.version: 'v2'`, but the realtime/broadcast surface stayed pinned\nat `/broadcast/v1` — so a v2 project's WebSocket mount, ws-ticket mint, DO\nroute matcher, notify helper, auth skip-set, and discovery all disagreed\nwith the rest of the contract. The broadcast base now derives from the same\nresolved contract version (single source of truth in `resolveSystemRoutes`),\nthreaded through every emitter:\n\n- **contract v1 (or omitted)** → `/broadcast/v1` everywhere, byte-identical\n to prior output.\n- **contract v2** → `/broadcast/v2` everywhere, with **no hidden v1 alias**.\n\nAn explicit `compiler.routes.broadcast` override still wins. Existing v1\nprojects are unaffected.\n\n### Web Push: VAPID delivery, queue fan-out, and identity-tag targeting\n\n`push.provider: 'web-push'` turns on a full push pillar: a self-contained\ndelivery module (RFC 8292 VAPID JWTs + RFC 8291 aes128gcm, `crypto.subtle`\nonly — no Node polyfills), a Cloudflare Queues fan-out with a dead-letter\nqueue, and a hardened `push_subscriptions` schema. The crypto core is\nverified against the RFC 8291 Appendix A known-answer vector — the emitted\nmodule reproduces the RFC's ciphertext byte-for-byte.\n\n- **Send path** — `enqueuePushFanout(queue, target, payload)` from an\n action's after-commit phase (`effects.enqueue`), so rolled-back writes\n never notify and `dryRun` sends nothing. Declarative targets\n (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`)\n resolve server-side in the queue consumer — subscription crypto never\n enters action code. Targeting speaks the realtime identity-tag dialect\n and is fail-closed: `[]` selects nobody, broadcast requires an explicit\n `{ all: true }`.\n- **Default schema** (`push.defaultSchema: true`) — owner-firewalled,\n INTERNAL-read `push_subscriptions` with a `views.mine` device list.\n Creates validate `https:` endpoints (SSRF blocker), 65-byte P-256\n `p256dh`, 16-byte `auth`; `tags` is stamped server-side from the\n session's proven identity (client tags ignored); 10/min create rate\n limit; per-user cap keeps the newest 10 live subscriptions.\n- **Fail-closed config** — a literal `vapidPrivateKey` in config is a\n compile error (`env:VAPID_PRIVATE_KEY` only); the worker refuses to boot\n without the three VAPID vars; the private key never lands in\n `wrangler.toml`, SPA bundles, or logs (DLQ chunks log counts only).\n- **SPA bake** — the VAPID public key ships to CMS/Account bundles as\n `VITE_QUICKBACK_VAPID_PUBLIC_KEY` and `window.__QUICKBACK_RUNTIME.vapidPublicKey`.\n- **CLI** — `quickback push generate-keys [--out <file>]`; `--out` writes\n the private key to a `0600` file so it never touches stdout or shell\n history.\n\nSee [Web Push](/stack/push) for the full guide.\n\n## v0.52.1 — July 17, 2026\n\n### CLI: cold-start tolerance for the cloud compiler\n\nRight after a service deploy, the first compile pays a fresh container image\npull — which routinely exceeds the CLI's old 60-second readiness budget and\nsurfaced as `Compiler container did not become ready in time` even while\n`/health` was green. `waitForReady` now allows 4 minutes, reports elapsed\nwarm-up progress, and the timeout message explains the deploy-in-progress\ncase.\n\n## v0.52.0 — July 17, 2026\n\n### Five action primitives: afterCommit, realtime emit, transitions v2, refs, bundles\n\nOne release, five primitives that collapse the most-repeated hand-written\npatterns in real Quickback projects (measured across a 349-action production\ncorpus). Every one is additive — existing projects compile unchanged, and\nplain `{ field, fromTo, to|via }` transitions keep their emission\nbyte-identical.\n\n- **`afterCommit` hooks + `effects.enqueue`** — named best-effort side\n effects that run after `execute` returns. Each hook is independently\n wrapped (failures log as `[<action>] afterCommit:<hook> failed`, never\n touching the response), non-blocking hooks ride `executionCtx.waitUntil`,\n `{ blocking: true }` awaits before responding, and everything skips when\n `execute` throws or returns `dryRun: true`. The execute context also gains\n `effects.enqueue(name, fn)` for mid-execute captures and `now` — one ISO\n timestamp per invocation. Replaces the per-leg `try/catch + waitUntil`\n idiom. See [After-commit hooks](/compiler/definitions/actions#after-commit-hooks).\n\n- **Realtime emit for custom actions** — tables that lock auto-CRUD no\n longer hand-roll frames. `realtime: { emitFromActions: true, scopeKeyFrom:\n \"events:{eventId}\" }` makes scoped-db writes inside record-bound and bulk\n actions emit auto-CRUD-byte-compatible frames after commit (masking +\n audience applied at fanout; the fail-closed audience requirement extends to\n action emission). Actions can also declare `emit:` for a pre-bound\n `emitCrud(row, oldRow?)`. Updates/deletes pre-select old rows on the same\n WHERE; raw `unsafeDb` writes stay invisible. See\n [When auto-broadcast fires](/stack/realtime/durable-objects#when-auto-broadcast-fires-and-when-you-call-it-manually).\n\n- **Transitions v2** — `transition` grows `guard` (equality / null / notNull\n / `custom(record)`), `onIllegal { code, status, message }`, `idempotent:\n \"noop\"`, and `stamp`/`clears` that ride a compiler-applied, TOCTOU-safe\n UPDATE (guards fold into the WHERE; a lost race is 409\n `ACCESS_TRANSITION_LOST`). With an applied write, `execute` becomes\n optional. Table-level `transitions: { publish: { field, from, to, access } }`\n *generates* the action files — including `undo:` inverses and `onEnter`\n cascades — mounted exactly where hand-written files would be (explicit\n files win, with a warning). The ten byte-identical publish/revert files in\n the podcast fixture become two lines per entity. See\n [Transitions](/compiler/definitions/transitions).\n\n- **`refs` — scoped foreign-key inputs** — the \"load the id, 404 if missing,\n assert it belongs to this event\" preamble becomes declarative. Loads run\n through the scoped db (a cross-org id 404s by construction), batch into one\n `Promise.all`, assert `matchScope` / cross-input `matchWith` parenthood, and\n inject rows under their `as` names. Ref keys are validated against the\n inline `z.object` input (with agreeing optionality) at compile time. See\n [Refs](/compiler/definitions/actions#refs-scoped-foreign-key-inputs).\n\n- **`defineBundle` — single-round-trip bootstrap reads** — declarative\n `list()` slices with the firewall, the table's *real* mask functions, and\n `{ data }` cache-seed envelopes; `custom()` escape-hatch sections; a SHA-1\n ETag over `{ scopeSeed, userId, payload }` with the `ifNoneMatch →\n notModified` short-circuit; and `Server-Timing`. Fail-closed: a bundle's\n roles must be a subset of every list table's `read.access` roles — a bundle\n can never widen read access. The digest ships as `sha1Hex` in `lib/etag`\n so hand-written reads can delete their copies. See\n [Bundles](/compiler/definitions/bundles).\n\nSupporting changes: `ActionError` / `TransitionLostError` are re-exported\nfrom the generated `.quickback/define-action` helpers (routes duck-type on\n`error.name`, so project-local copies keep working); `sendQueueBatched` in\n`lib/effects` chunks queue sends at the Cloudflare 100-message cap; and the\n`$record.*` / `$ctx.*` substitution grammar used by `onEnter` and bundle\n`where` is one strict allowlist, always parameterized — never interpolated\ninto SQL.\n\n### CLI device login fixed: /cli/authorize now claims the code before approving\n\nBetter Auth's `deviceAuthorization` plugin requires the verifying session to\nclaim a device code (`GET /device?user_code=…`) before it accepts an approve\nor deny. The account SPA's `/cli/authorize` page posted the approval directly,\nso every `quickback login` failed with *\"Device code has not been claimed by\na verifying session.\"* The page now claims first, then approves — and surfaces\nclaim failures (expired or mistyped codes) with the server's message.\n### Generated builds no longer rewrite the auth schema\n\nGenerated Better Auth projects now run `tsc` directly from `npm run build`.\n`quickback compile` already generates, qualifies, and envelopes\n`src/auth/schema.ts`; invoking `auth:schema` again during every build rewrote\nthat compiler-owned artifact and made an otherwise clean release worktree\ndirty. The explicit `auth:schema` diagnostic command remains available, while\nnormal build, Wrangler, and deployment preflight paths are source-read-only.\nWhen recompiling an existing project, compiler-owned `package.json` script\nnames now converge to their current generated commands while unrelated custom\nscripts are preserved. This upgrades projects whose previous generated\n`build` script still invoked `auth:schema`.\n\n### Non-cross-tenant unsafe actions preserve delegated RLS claims\n\nGenerated Neon handlers now reserve `createServiceDb` for actions that\nexplicitly enable `unsafe.crossTenant`. An action that enables raw database\naccess with `crossTenant: false` keeps the request database, so organization\nand delegated-principal claims survive into Hyperdrive transactions instead of\nbeing cleared by the service-role preamble. True cross-tenant sysadmin actions\nretain their audited RLS bypass.\n\nNeon Hyperdrive guidance now also calls out Postgres' `SELECT … FOR UPDATE`\nauthorization rule: a locked row must pass both `SELECT` and `UPDATE` policies.\nDelegated actions should use ordinary selects for read-only eligibility tables\nand lock only mutable rows they are authorized to update. A PGlite regression\nproves that ordinary delegated reads remain visible while the generated\nrestrictive update fence blocks an unauthorized row lock.\n\n### Atomic email-OTP auth routing no longer recurses on ordinary requests\n\nThe generated atomic email-OTP wrapper now captures and binds Better Auth's\noriginal request handler before replacing the public `handler` property.\nSession reads and every other non-atomic auth route therefore forward to Better\nAuth exactly once instead of re-entering the wrapper until the Worker exhausts\nits call stack. The exact email-OTP sign-in route retains its transactional\nadmission and rollback behavior.\n\n### Generated Better Auth CLI dependencies no longer retain vulnerable Lodash\n\nBetter Auth projects now emit a root npm override for `lodash@4.18.1`. This\nkeeps the supported stable `auth@1.6.x` CLI and its `better-auth` executable,\nwhile lifting the CLI's dev-only Prisma parser chain off Lodash releases\naffected by the 2026 code-injection and prototype-pollution advisories. Runtime\nBetter Auth packages and generated authentication behavior are unchanged.\n\nThe CLI now merges generated npm overrides explicitly when recompiling an\nexisting project: unrelated user overrides remain, while compiler-owned\nsecurity pins win a conflict. Recompile and reinstall dependencies to refresh\nthe project lockfile. `npm audit --omit=dev` remains the production dependency\nview; upstream development-server advisories may still appear separately.\n\n### Postgres constraint replacements apply in dependency-safe order\n\nNeon migration post-processing now orders both halves of a Drizzle constraint\nreplacement. A dependent foreign key is dropped before its referenced unique\nor primary-key constraint, then the replacement key is added before the\nforeign key that consumes it. This prevents Postgres `2BP01` failures when\nDrizzle emits the parent key drop first, while preserving byte-identical output\nfor already-correct migrations and the relative order of unrelated statements.\n\n### Schema registry output is byte-reproducible\n\n`schema-registry.json` no longer includes the wall-clock `generatedAt` field.\nIts remaining metadata and schema content are derived entirely from compiler\ninputs, so consecutive compiles of identical logical input now produce the\nsame registry bytes. This makes artifact hashes, caches, and deployment diffs\nstable without timestamp normalization.\n\n### Generated auth and discovery surfaces now remain truthful and type-safe\n\nAtomic email-OTP generation now imports and invokes\n`before-email-otp-activate.ts` exactly once and preserves the transaction's\nreal Drizzle `select` capability in the hook context. Strict generated\nTypeScript therefore accepts both the base Neon service database and its\ninteractive transaction without erasing the hook's read contract.\n\nContract-v2 projects that omit `auth.jwt` no longer advertise the disabled\nQuickback JWT fast path in `llms.txt` or RFC 8414 metadata. Bearer-JWT guidance,\nthe fallback `/api/v2/token` endpoint, and JWT scopes are emitted only when the\ncorresponding JWT surface exists; real Better Auth OAuth-provider discovery is\nunchanged.\n\nCloudflare Email callbacks now all enter the shared credential-delivery\nscheduler exactly once. The scheduler anchors the observed rejection with\n`waitUntil`, emits the metadata-only `auth.credential_delivery_failed` event,\nand never leaks the provider error. Generated CRUD routes also keep delegated\nprincipal and account authority disjoint: `?organizationId=` is rejected for a\ndelegated principal instead of synthesizing `activeOrgId` on its context. This\ncloses both the authority ambiguity and the generated `AppContext` union type\nerrors.\n\n### Email-OTP activation can be admitted atomically in the API layer\n\nContract-v2 Cloudflare projects using one Neon Hyperdrive database can opt the\nexact Better Auth `POST /sign-in/email-otp` handler into an interactive\ntransaction with `atomicAuthRoutes: [\"emailOtpSignIn\"]`. The paired recognized\nhook, `quickback/hooks/before-email-otp-activate.ts`, receives a proven dormant\nuser `{ userId, email, user }` plus transaction-bound `db` / full `schema` and\n`authDb` / `authSchema` handles. Quickback owns only identity proof and atomic\norchestration; application admission, status, event, pass, and eligibility\nrules remain authored in the project API hook.\n\nThe hook executes after OTP validation but in Better Auth's\n`databaseHooks.user.update.before`, before the user update lock. This preserves\napplication-first lock ordering and avoids the user-to-application inversion a\nsession-create hook would introduce. Unknown-email signup must be disabled;\nalready-verified users do not rerun dormant activation.\n\nThe generated handler rebuilds Better Auth over the transaction handle, so OTP\nconsumption, project hook writes, the `emailVerified` update, and session insert\ncommit together. Admission denial, a non-ok response after activation starts,\nand any 5xx response throw a private rollback sentinel. Expected policy denial\nreturns a generic 403. Operational rollback emits the metadata-only\n`auth.atomic_email_otp_operational_rollback` event and returns a generic 503,\nwithout exposing raw errors. Ordinary invalid-OTP 4xx responses still commit\nBetter Auth's attempt accounting, and the OTP-send route remains outside the\ntransaction. Unsupported contracts, runtimes, database modes,\nmissing/duplicated config, enabled signup,\nand a hook/config mismatch now fail at compile time.\n\n### Neon migrations can declare cross-schema foreign keys\n\nNeon projects can now declare fully qualified, single-column or composite\nforeign keys under `compiler.migrations.foreignKeys`. Each entry names the\nconstraint, source and target schema/table/column tuples, and explicit\n`onDelete` / `onUpdate` actions. The compiler rejects unsafe identifiers,\nmismatched tuple arity, duplicate or ambiguous declarations, unknown keys,\nand non-Neon providers before generating SQL.\n\nDeclared constraints are sorted deterministically and folded into Quickback's\ncontent-addressed Postgres journal after the Drizzle schema migration. A new\nconstraint is added `NOT VALID` and then validated, so existing orphan rows\nfail the migration; replay verifies an exact catalog match and rejects a\nsame-named constraint with different semantics. This surface enforces\nrelational integrity only—business rules remain in generated or authored API\nactions, not database triggers.\n\n### Compile completion steps honor the Neon connection mode\n\nThe CLI's successful-compile footer now distinguishes Neon HTTP from\nHyperdrive. HTTP projects retain the direct `DATABASE_URL` Worker setup.\nHyperdrive projects show `DATABASE_MIGRATION_URL` only as a local or CI\nmigration input, point local development at the configured Hyperdrive\n`localConnectionString`, and never recommend deploying `DATABASE_URL` as a\nWorker secret.\n\nNamed Hyperdrive environments also show their configured Neon branches,\nrequired-secret inventories, and explicit Wrangler `--env` targets. The footer\nno longer suggests the unnamed `.env.neon` / `.dev.vars` workflow or a bare\ndeploy for an isolated `dev` / `prod` setup.\n\n### Cloudflare email delivery and named Neon targets fail visibly and deploy explicitly\n\nGenerated Cloudflare email code now uses the native Workers `SendEmail`,\n`EmailAddress`, attachment, and `EmailSendResult` contracts. The Workers\nbuilder keeps its camel-case fields and `{ email, name }` address shape, while\nthe REST transport retains its separate snake-case fields and `{ address,\nname }` shape. Generated projects move to `@cloudflare/workers-types` v5 with\nWrangler 4.110 so the binding and result types agree without `any` casts.\n\nEvery Better Auth email callback now creates an observed delivery promise. On\nWorkers, the callback hands that still-rejecting promise to\n`executionCtx.waitUntil(...)` and returns after the task is accepted; outside a\nrequest lifecycle it returns the promise for the caller to await. Failures emit\nonly a structured generic event, never provider error content, and remain\nrejected instead of being detached or swallowed. SES and SNS background sends\nuse the same lifecycle rule.\n\nNeon Hyperdrive's generated postgres.js client now caps each request-scoped\npool at five connections. Named environments gain explicit `deploy:dev` and\n`deploy:prod` package scripts (mapped to their configured Wrangler environment\nnames), while the unsafe bare `deploy` script remains absent and migrations\nremain a separate target-owned step.\n\n### Contract v2 auth and Neon authority boundaries are fail-closed\n\nContract-v2 projects no longer emit Quickback's generic JWT mint endpoint,\nJWT helper, middleware verification/mint fast-path, or related imports unless\nthe project explicitly declares `auth.jwt`. Contract v1 retains its existing\ndefault for compatibility. Adding `auth.jwt: {}` to a v2 config opts back into\nthe custom Quickback JWT with its normal default settings.\n\nConfigured delegated authenticators now produce closed TypeScript unions in\nboth generated `AppContext` and Neon RLS context. Request contexts contain only\nresolved principal variants; the compiler-internal credential-lookup variants\nexist only in the database context. Delegated standalone actions do not require\nBetter Auth `activeOrgId` / `activeTeamId` before their declared principal\naccess tree runs, and their context cannot acquire account, organization, team,\nmembership, or scope authority.\n\nOn Cloudflare + Neon, the API-key organization membership lookup now runs with\nrequest-scoped user/org RLS claims before it stamps verified organization and\nrole authority into `AppContext`. Generated security migrations also converge\ndirect privilege drift: the audit schema/table revoke all direct grants from\n`PUBLIC`, the runtime, and admin before restoring their exact write-only/admin\nsets, while the Drizzle journal schema/table/sequences and database `CREATE`\ncapability explicitly revoke `PUBLIC` and runtime access before granting the\nmigration role.\n\n### Standalone action routes preserve their exact authority context\n\nGenerated standalone routes now pass each action the context and scoped\ndatabase types inferred from that action's own `execute` signature. Account actions therefore receive a\nrequired account identity, while `event_pass`, `event_delegate`, and other\ndelegated-principal actions retain their exact principal literal at the route\nboundary. Relationship `loads` / `exposeAs` hydration is intersected with that\nauthority context, including required shared targets and optional distinct\nmulti-lane targets, instead of replacing it with the broad application\ncontext.\n\nThe same boundary keeps ordinary request databases and temporary\nservice-role-backed scoped databases assignable to the generated Hyperdrive\naction helper without widening the handler's schema-aware `db` type.\n\nGenerated principal-auth identity guards also emit explicit strict TypeScript\nparameter and return types. Contract-v2 Cloudflare + Neon output no longer\nfails `tsc` on implicit-`any` guard parameters.\n\n### Parameterized actions keep complete v2 schema harvests\n\nThe action-input harvest plan now converts Hono-style `:param` segments to the\nOpenAPI `{param}` form for standalone actions and parameterized resource paths.\nPreviously the CLI could harvest every schema successfully, but the compiler\ncould apply only parameter-free actions because it looked up parameterized\noperations under the wrong OpenAPI key. Contract v2 now counts and patches the\nsame canonical path emitted by OpenAPI and MCP.\n\nGenerated standalone-action routes also remove template-only trailing spaces\nwhen optional audit blocks are absent, keeping regenerated source diffs clean.\n\n### Action-schema harvest uses the generated runtime dependency tree\n\nThe CLI now resolves action-harvest dependencies from the configured\n`build.outputDir/node_modules` before unrelated ancestor installs. This fixes\nisolated projects that keep authored definitions under `quickback/` and the\ngenerated runtime under a sibling directory such as `src/`: their actions can\nuse the runtime's Zod 4 and Drizzle installation without adding workspace-root\nsymlinks. An older user-level or monorepo-level Zod can no longer shadow the\nruntime's declared version during schema evaluation.\n\nSchema-only evaluation also emits inert named table proxies for authored\nDrizzle exports. Shared input/DTO modules may therefore construct top-level\nselection objects such as `{ id: records.id }` without executing a database\noperation or losing the action's Zod schema.\n\nHarvest failures now retain the exact action key, failing phase (`bundle` or\n`evaluation`), and bounded underlying error. Contract v2 includes those\nper-action diagnostics in its fail-closed compile error; v1 retains its\nbest-effort static-schema fallback.\n\n### Contract v2 delegated principals and RLS-only action tables\n\nCloudflare + Neon Hyperdrive projects on `contract.version: \"v2\"` can now\ndeclare framework-generic delegated authenticators under `auth.principals`.\nEach named principal owns an exact, non-`Bearer` Authorization scheme, a\nproject hook that proves the credential and returns only `{ digest }`, and one\ncompiler-owned indexed lookup that resolves the actor, optional session/family,\nstring claims, and active status. The hook receives no database handle. Proof\nhooks authored under `quickback/lib` are staged into generated `src/lib`, even\nwhen no action imports them directly.\n\nDelegated authority is structurally disjoint from Better Auth accounts:\n`ctx.principal` is populated while user, organization, team, and membership\nfields remain absent. Access arms may use `principals: [...]`; fields inside an\narm are ANDed and sibling arms are ORed. Generated action helpers preserve\nthat boundary in TypeScript, including the anonymous possibility of a\n`PUBLIC` sibling arm. Mixed credential transport rejects Authorization plus an\nAPI key or an actual Better Auth session cookie, while unrelated analytics\ncookies do not create a false conflict. `Bearer` remains reserved for account\nauthentication.\n\nResources can also declare operation-specific `databaseAccess` policies for\nauthored actions and support tables. This is an RLS-only surface: it emits no\ngeneric route or OpenAPI operation and is accepted only on Cloudflare + Neon\nHyperdrive. Every authorization path must contain a nonempty SQL-lowerable\nrecord equality; unbounded principal/role leaves, any unbounded OR arm, empty\nrecords, ambiguous mixed boolean nodes, app-only predicates, and unsupported\nproviders fail compilation. This keeps business logic in authored API actions\nwhile Postgres independently enforces the same event/person or account/org row\nboundary.\n\nPrincipal claims use the same transaction-local Hyperdrive preamble as account\nclaims, with query caching disabled. Restrictive per-operation principal\nfences prevent a public, exception, or legacy permissive policy from admitting\nthe wrong principal type. Credential lookup indexes and RLS journal entries are\ncontent-addressed and converge when a table, digest column, or definition\nchanges; generated Postgres identifiers include collision-resistant hashes and\nstay within the 63-byte limit. Each security migration also drops the complete\ncompiler-owned `databaseAccess` policy family before recreating the current\noperations, so removing or moving an operation revokes the old permissive\npolicy instead of leaving it active. Record fields resolve through authoritative\nDrizzle metadata to exact quoted physical identifiers, unknown fields fail the\ncompile, and DB-only pseudo-roles follow the same ADMIN/SYSADMIN/INTERNAL\ncontract as the application surface.\n\n### Action execute helpers preserve their typed boundary\n\nGenerated per-feature `defineAction` helpers no longer erase `services`, the\nHono request context, record predicates, or the action's return value to\n`any`. Zod input and record inference remain intact, `whereRecord` and\n`whereTransition` accept only the helper's bound table, and the existing D1 /\nNeon Hyperdrive scoped `db` and interactive `tx` types now flow through the\nsame execute boundary. The returned value is inferred exactly; this does not\nadd a response schema, invalid-return rule, or new output contract.\n\nHTTP/WebSocket Neon retains its intentionally dynamic `db`, and `AppContext`\nretains its open index signature for runtime-hydrated namespace fields.\n\n### Neon Hyperdrive is now the only Worker database lane, including Better Auth\n\nFor `connectionMode: \"hyperdrive\"`, generated Better Auth code now uses the\nsame HYPERDRIVE-backed, service-role-scoped database handle as the rest of the\ngenerated API. `DATABASE_URL` is no longer emitted or required as a Worker\nsecret in Hyperdrive mode; migration credentials remain inputs to the compiler\nor CI environment. HTTP-mode Neon retains its existing `DATABASE_URL` runtime\ncontract.\n\n### Public contract v2 now compiles as one coherent API/auth surface\n\nProjects may set `contract: { version: \"v2\" }` to select `/api/v2/*` feature\nroutes and `/auth/v2/*` Better Auth routes. The compiler now threads that\nselection through generated route mounts, Better Auth configuration and\nmiddleware, OpenAPI paths and server metadata, MCP internal tool calls, OAuth\ndiscovery, `llms.txt`, schema/embeddings/system routes, live views, namespace\nactions, and dedicated-domain `/v2/*` shortcuts. The option is no longer\nfail-closed. Omitting `contract` or selecting `v1` preserves the existing v1\noutput.\n\nBundled CMS and Account clients now receive the selected API and auth base\npaths through both their Vite build environment and the Worker-injected runtime\nconfig. CMS CRUD, schema, sysadmin, and live-view requests and Account auth,\ndata, and live-view requests therefore stay on `/api/v2` and `/auth/v2` for a\nv2 project instead of falling back to client-side v1 literals. V1 SPA config\nretains its historical byte shape.\n\nV2 compiles also require a complete client-side action input-schema harvest.\nThe current CLI reports the exact action files that failed to produce a JSON\nSchema, and the compiler independently rejects missing, invalid, or partial\nmaps at the shared parse boundary used by both complete and validation-only\ncompiles. `POST /compile?complete=false` can no longer bypass the v2 gate. For\nrecord actions with `bulkVariant: true`, the harvested schema now patches both\nthe single-record request body and the bulk operation's nested `input`; the\naction is counted complete only when both OpenAPI targets exist. Harvest\nplanning also normalizes filename-based action bindings to the table's declared\nname and resource path, so kebab-case filenames exporting snake/camel-case\ntables are not silently omitted. V1 remains best-effort for backward\ncompatibility.\n\n### Complete, isolated Wrangler targets for named Neon environments\n\n`providers.database.environments` now defines deployable Neon Hyperdrive\ntargets instead of emitting empty `[env.*]` shells. Because Wrangler does not\ninherit vars or bindings into named environments, each target must explicitly\nown its generated vars, required-secret contract, Hyperdrive and KV IDs,\nrate-limit namespace IDs, and Cloudflare Email binding. The compiler rejects\nmissing overrides, shared stateful IDs, optional secret declarations, invalid\ntarget semantics, and unsupported binding families rather than generating a\nWorker that starts without part of its runtime.\n\nThe required-secret inventory is now centralized and includes generated\ncredentials as well as custom declarations: `BETTER_AUTH_SECRET`, a configured\n`auth.jwt.secretEnv`, `ENCRYPTION_KEK` when envelope encryption is present, and\nevery `bindings.secrets` entry marked `required`. Generated Better Auth SES/SNS\ncredentials, AWS-backed anonymous-upgrade credentials, enabled social-provider\nclient id/secret pairs, and R2 presign credential env names are included as\nwell. Cloudflare social auth now reads those credentials from the Worker `env`\nbinding instead of relying on `process.env` compatibility behavior. Named\ntargets also reject every generated top-level custom-domain source — including\nruntime routes, the primary/CMS/Account/Admin/Auth/API domains, and app domains\nor aliases — until routes can be declared with explicit per-environment\nownership; top-level routes can no longer produce an ambiguous deployment\ntarget.\n\nNamed targets are currently limited to Neon Hyperdrive with Better Auth.\nExternal auth remains fail-closed until its service binding can be declared\nindependently for every named environment.\n\nFor named-environment projects, the base Worker has no deployable stateful\nbindings, local development selects a named target, and that selected target\nis always the required logical `dev` environment, which must own an explicit\ndevelopment-only Hyperdrive `localConnectionString`. Quickback emits it only\nin the selected named binding, rejects a top-level\noverride when named environments exist, and rejects local URLs on staging or\nproduction targets; deployed targets continue to resolve the remote\nHyperdrive configuration by ID. The generated package omits the unsafe bare\ndeploy script. Existing projects that omit\n`environments` keep byte-identical Wrangler output and the existing dev/deploy\nscripts. See [Neon → Named Cloudflare deployment environments](/compiler/targets/hono-api/database/neon#named-cloudflare-deployment-environments).\n\n### Local compiler trust boundary and deterministic Drizzle commands\n\nThe supported Docker launcher now opts into unauthenticated local compilation\nexplicitly and publishes the compiler only on `127.0.0.1`; missing or unknown\ncompiler modes retain hosted authentication. The CLI recognizes only exact\nloopback hostnames as local. Migration post-commands now use the configured\npackage manager's local binary execution form, with npm forced offline and its\nimplicit install prompt disabled, so a missing `drizzle-kit` fails clearly\ninstead of fetching an unpinned package.\n\n### Action rate limits now emit — documented since the rate-limit pillar, wired now\n\nThe [rate-limit docs](/compiler/definitions/rate-limit#actions) have described\nper-action rate limiting since the pillar shipped: record-based actions inherit\nthe resource's `update` bucket, standalone actions inherit the project-default\n`update` bucket, and actions may declare a `rateLimit` override or opt out with\n`rateLimit: false`. The generated routes never contained the checks. They now\ndo, exactly per the documented contract:\n\n- Record-based actions (and their bulk variants, which share the same counter —\n one token per batch request) are keyed\n `<resource>:action:<name>:<user>`; standalone actions are keyed\n `standalone:<declaredPath>:<user>`. The `:action:`/`standalone:` infixes mean\n action counters never collide with CRUD counters.\n- `rateLimit: { limit, period }` on an action emits its own binding\n (deduped by tuple, same `RL_<limit>_<period>` scheme); `rateLimit: false`\n opts the action out entirely.\n- Record-based action routes are now **exempted** from the per-resource CRUD\n catch-all middleware. Previously a `POST /:id/approve` was incidentally\n counted against the resource's `create` bucket — wrong bucket, wrong key.\n- Actions-only (tableless) projects now provision the project-default binding;\n previously they shipped with none.\n\n**Behavior change:** standalone actions were previously *unlimited*; they now\ninherit the project-default `update` bucket (200 requests / 60s per user/IP\nwith shipped defaults). PUBLIC webhook-style endpoints that absorb provider\nbursts should declare their own budget (`rateLimit: { limit: 1000, period: 10 }`)\nor opt out (`rateLimit: false`). The compiler emits a warning when a PUBLIC\nstandalone action silently inherits the default, so affected actions are\nflagged at compile time.\n\n### Better Auth CLI pinned and shipped as a generated devDependency\n\nThe generated `auth:schema` script runs `npx better-auth generate`, but the\n`better-auth` runtime package ships no executable — the `better-auth` bin\nlives in the npm package `auth` (the official Better Auth CLI; the team took\nover that name at 1.5.0, superseding the frozen `@better-auth/cli`). Generated\nprojects now declare `auth` as a devDependency pinned to the runtime's minor\nline, so `npm run auth:schema` resolves the CLI locally instead of requiring a\nglobal install. The compiler image's global CLI is pinned to the same version,\neliminating silent skew between the CLI on `latest` and the pinned runtime.\n\n### Compile warning when an action's input schema degrades to untyped\n\nWhen action input schemas aren't harvested client-side (older CLI, or a direct\n`/compile` API call), the static Zod parser supplies OpenAPI/MCP input schemas\n— and silently degrades unrecognized constructs (discriminated unions,\nrefinements, `z.record`, transforms) to the accept-anything `{}`. That\ndegradation is no longer silent: the compile result now carries a warning per\naffected action naming the route, source file, and the exact untyped field\npaths. Actions covered by the CLI harvest are never warned on, and actions\nthat declare no input are skipped.\n\n### Auth docs: JWT security posture stated up front\n\nThe [Auth & JWT page](/compiler/config/auth) now leads with the posture\nsummary instead of burying it: the default 180-second auto-refreshed TTL plus\n`revocationCheck: 'kv'` (seconds-level revocation, auto-stamped on ban /\nmember removal / role change / scope-conferring row changes) is the\nrecommended configuration and covers the vast majority of deployments — with\nthe residual trade-offs (per-principal granularity, fail-open on KV outage,\n~60s cross-PoP propagation) stated explicitly for strict threat models.\n\n### Neon via-user reads: generated list handlers now typecheck against the concretely-typed service handle\n\nOn Neon, a read firewall carrying a via-user multi-hop relationship predicate\nroutes the generated read handlers to `createServiceDb(c.env)` — a genuine\n`NeonHttpDatabase<typeof schema>` — instead of the loosely-typed request db.\nThe list handler's query construction declared drizzle select builders with\n`let` and reassigned them (`query = query.where(…)`, `.orderBy(…)`,\n`.limit(…).offset(…)`, and the count/aggregation/group-by variants), which is\na type error against drizzle's immutable builder typing: `.where()` returns\n`Omit\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
6
+ "content": "## Unreleased\n\n### Typed scoped `db` on every Neon mode + write-side audit forbids\n\nThe action `db` is now schema-aware on **all** Neon connection modes, not just\nHyperdrive: http mode gets the same insert relaxation and typed reads with\n`.transaction` **blocked at the type level** (the neon-http driver throws at\nruntime — the type now says so instead of a 500), websocket mode gets the full\ninteractive-tx flavor. With D1 already typed, every supported provider's action\n`db` now carries the schema — including the `SealedValue` brand on `.sealed()`\ncolumns, so string-processing a sealed value is a compile error everywhere.\n\nOn every typed provider, the compiler-managed audit keys are now `?: never` in\n`.insert().values()` **and** the newly-typed `.update().set()`: the audit\nwrapper hard-stamps them from the verified caller, so a supplied value was\nalways discarded — now it's a compile error instead of a silent lie.\n`.set({ deletedAt })` stays allowed (the soft-delete signal).\n\n### Hard-stamp unification — one audit-actor contract\n\nThe scoped db's dead \"fill-if-absent\" actor lane is gone: on every wrapped\nhandle, `createdBy`/`modifiedBy` come from the verified principal, period (the\nraw client remains the documented escape for system writes that own their\nprovenance). Three attribution gaps closed with it: cron schedules' and queue\nhandlers' `withInternalContext` now hand out an **audit-wrapped** db, so\n`system:cron-<name>` / `system:queue-<name>` actually land on audit columns;\nupserts into encrypted/sealed tables now stamp `modifiedAt`/`modifiedBy` on the\n`onConflictDoUpdate` conflict branch like every other write; and an org-scoped\nchild table whose source can't accept the injected `organizationId` column now\nfails the compile instead of silently shipping without its tenant column.\n\n### Visible audit columns — `...q.audit()` / `...q.softDelete()` + canon validator\n\nThe compiler-managed audit quartet and soft-delete pair can now be **declared visibly**\nin authored feature files: q-DSL tables spread `...q.audit()` / `...q.softDelete()` into\nthe columns object (types flow through — `$infer` shows `createdAt`/`modifiedBy`/… on the\nauthor's own table object), raw Drizzle tables declare the canonical lines literally.\n`quickback migrate visible-columns` codemods an existing project in one shot; emitted\noutput is unchanged either way (the spreads expand to the exact injector lines).\n\nWith visibility comes validation, **on by default**: every feature table must declare its\nmanaged columns visibly (`...q.audit()` / `...q.softDelete()` or the canonical literal\nlines — one `quickback migrate visible-columns` run), and every managed column that appears\nin authored source is checked against the canonical spec — insert-time default chains on\n`createdAt`/`modifiedAt` (+`$onUpdate`), nullable no-default actor columns, nullable\nno-default `deletedAt`, canonical SQL names, never `.encrypted()`/`.sealed()`. Divergence\n(silently accepted before) and missing declarations **fail the build**, with soft-delete\npresence pinned to `crud.delete.mode`. Opt out with\n`compiler.features.visibleAuditColumns: false`, which downgrades divergence to warnings and\nrestores invisible injection. Unknown spreads in a q-DSL columns object are now a compile\nerror instead of being silently dropped.\n\nAlso in this line: `q.table`'s `$insert` type is honest (required vs defaulted/stamped\ncolumns; audit keys are `?: never` — the wrapper hard-stamps them), `$infer` includes the\naudit columns, and the canonical column definitions collapsed into one shared spec\n(`constants/managed-columns.ts`) consumed by the injectors, meta augmentation, request\nvalidation, spread expansion, and the new validator.\n\n### Feature areas — hierarchical authz grouping (`_area.ts`)\n\nA folder under `features/` carrying an `_area.ts` (`export default defineArea({...})`) is now\nan **area**: it declares a route prefix + admission lanes (the same shape as a project\nnamespace, incl. `mintScope`/`acceptScope`) and an authz vocabulary — relationships, composed\nroles, named gates, tenant anchors, scope kinds — that every feature inside the folder\nreferences by bare name. The vocabulary is visible to the area's subtree ONLY: the compiler\nchecks every reference channel (access roles/gates/scoped aliases, action `access`/`anchor`,\nfirewall `via`/`{ rule }`/`{ tenant }` arms, `ctx.scope.<kind>` accessors, auth-view tenant\nincludes, realtime handshake roles, table-level namespace lanes, and other `_area.ts` nodes)\nand fails the build on any outside reference. Root `authz` stays the global level, and root\nbodies may reference root-declared names only (no laundering an area name project-wide).\n\nFail-closed rules shipped with it: re-declaring an inherited name is a compile error (no\noverrides in v1); a descendant action whose path opts out of the area prefix must carry an\nexplicit `route: 'self'` marker; relative `path: './…'` resolves against the area prefix with\ndot segments rejected; foreign features can't claim paths (or table-level namespace prefixes)\nunder an area's prefix; nested areas may add vocabulary but not mount a second prefix under a\nmounted ancestor (unlinked parent/child admission never compiles); and area-tree projects\nmust declare `requires: ['feature-areas']` — the marker reaches the compiler through ANY CLI\nversion, so an area-unaware toolchain is rejected instead of silently dropping nested\nfeatures. Area projects also emit a reviewed audit artifact, `quickback/authz-manifest.json`\n(area tree, declared names, member features, area-gated vs self-gated actions, root-config\nnamespace consumers), and the generated `AGENTS.md` gains a feature-areas section.\n\nByte-parity guarantee: a flat root-authz project re-expressed as an area tree compiles to\nbyte-identical output (the emit-site key-order determinism pass from v2 step 0 makes the fold\norder provably irrelevant). See [Feature areas](/compiler/definitions/feature-areas).\n\nOne cosmetic side effect of that determinism pass: the first recompile of an existing project\non this release may reorder generated relationship-table **import lines** (they are now\nemitted in sorted order instead of authz-map insertion order). The reordering is a one-time,\nbehavior-free diff.\n\n### Access rules: named gates (`authz.rules`) and tenant anchors (`authz.tenants`)\n\nTwo new root-`authz` blocks let you declare a row/role rule once and stamp it by name instead\nof copying predicates across files. A **named gate** in `authz.rules` bundles up to three\narms — `who` (roles), `record:` (record-aware predicates), and `firewall` lanes — under one\nname, referenced by bare name in any `access: { roles: [...] }` array (applies who + record)\nand as `{ rule: '<name>' }` in a resource's `firewall:` (splices the lanes into the top-level\nAND array — a reference can only *narrow* row admission, never widen it). A **tenant anchor**\nin `authz.tenants` names the tenant predicate (`{ column, equals }`, claim side locked to\nverified ctx claims) and is written `{ tenant: 'org' }` in firewalls — with an optional\nper-site column override — and `tenant: 'org'` in auth-view includes. Expansion happens at\ncompile time; emitted SQL is byte-identical to the inline spelling.\n\nEverything fails closed: gate/role/scoped-role/`+`/`:` name collisions, `+` hierarchy sugar\ninside rule bodies, `{ rule }` inside `all`/`any` groups, firewall-less gates referenced from\n`firewall:`, firewall-bearing gates on actions or in `masking.show`, and an access-side\nreference to a firewall-bearing gate whose lanes the resource doesn't also stamp are all\ncompile errors. Gates in `realtime.requiredRoles` lower to static who-roles at the handshake;\na declared non-empty list that lowers to nothing is a compile error, never a silent `[]`. A\nnew `AUTHZ_UNKNOWN_ROLE_NAME` warning flags reference-shaped names that resolve to nothing.\nSee [named gates](/compiler/definitions/access#named-gates-authzrules) ·\n[`{ tenant }`](/compiler/definitions/firewall#named-tenant-anchors-tenant) ·\n[`{ rule }`](/compiler/definitions/firewall#named-gate-references-rule).\n\n## v0.55.0 — July 17, 2026\n\n### Generated projects ship an `AGENTS.md`\n\nEvery compiled project now emits an `AGENTS.md` at its root — the file coding agents read first — weaving Quickback's security model and a *\"when to use what\"* decision guide into the output. An agent editing the features is steered to the right primitive: a **view** for a filtered read, a **transition** for a guarded state change, an **action** for custom logic, **guards**/**masking** for field-level control, **named invalidations** for realtime refresh — each with a `docs.quickback.dev` link. It also documents the access tiers (incl. `SESSION`/`SCOPED`), the `WHERE column = value` firewall model with the org-OR-scope `{ any: [...] }` pattern for non-org callers, and the fail-closed coherence guardrail (with the *\"never `exception: true` as a workaround\"* rule). Regenerated on every compile.\n\n## v0.54.0 — July 17, 2026\n\n### Realtime: named invalidations\n\nActions can now fire typed, targeted *\"this changed — refresh\"* signals after commit. A `defineRealtime` registry declares typed events (wire name, contract `version`, named variants with strict Zod payloads); a `defineRealtimeDelivery` profile sets the maximum audience (a scope room or the org/user lane + required roles); and an optional `defineRealtimeRecipients` resolver narrows delivery to a resolved identity set — post-commit on the firewalled db, intersecting `scope ∩ roles ∩ recipients`, fail-closed (a throw or `[]` reaches nobody, never a wider audience). Bind them with `invalidates:` on an action and call `invalidate.<binding>.<variant>(payload)` inside `execute`. Delivery is after-commit + best-effort (discarded on throw/dryRun), projects the payload to declared keys, and works on every action kind — standalone, per-record, bulk, and namespace-hoisted. See [Named invalidations](/stack/realtime/named-invalidations).\n\n### Access: `SESSION` and `SCOPED` pseudo-role tiers\n\n`AUTHENTICATED` is now explicitly the wrapper over two auth flavors: **`SESSION`** (a full Better Auth session only) and **`SCOPED`** (a sessionless scope-token principal only — e.g. an event attendee with no account). Use the specific tier when a route must admit or exclude one flavor; `AUTHENTICATED` still admits both and excludes only external delegated principals. See [Access → Pseudo-roles](/compiler/definitions/access).\n\n### Access: fail-closed scope/firewall coherence guardrail\n\nGranting a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) on a resource whose firewall can't filter that caller now **fails the build** instead of silently returning `200 + []` — the trap that pushes apps toward a fake \"active organization.\" The fix is named in the error: compose org **or** scope in an `{ any: [...] }` firewall group, use a `via:` relationship, or `firewall: [{ exception: true }]`.\n\n## v0.53.0 — July 17, 2026\n\n### Realtime: the broadcast surface tracks `contract.version`\n\nThe `/api` and `/auth` bases already move to `/api/v2` and `/auth/v2` under\n`contract.version: 'v2'`, but the realtime/broadcast surface stayed pinned\nat `/broadcast/v1` — so a v2 project's WebSocket mount, ws-ticket mint, DO\nroute matcher, notify helper, auth skip-set, and discovery all disagreed\nwith the rest of the contract. The broadcast base now derives from the same\nresolved contract version (single source of truth in `resolveSystemRoutes`),\nthreaded through every emitter:\n\n- **contract v1 (or omitted)** → `/broadcast/v1` everywhere, byte-identical\n to prior output.\n- **contract v2** → `/broadcast/v2` everywhere, with **no hidden v1 alias**.\n\nAn explicit `compiler.routes.broadcast` override still wins. Existing v1\nprojects are unaffected.\n\n### Web Push: VAPID delivery, queue fan-out, and identity-tag targeting\n\n`push.provider: 'web-push'` turns on a full push pillar: a self-contained\ndelivery module (RFC 8292 VAPID JWTs + RFC 8291 aes128gcm, `crypto.subtle`\nonly — no Node polyfills), a Cloudflare Queues fan-out with a dead-letter\nqueue, and a hardened `push_subscriptions` schema. The crypto core is\nverified against the RFC 8291 Appendix A known-answer vector — the emitted\nmodule reproduces the RFC's ciphertext byte-for-byte.\n\n- **Send path** — `enqueuePushFanout(queue, target, payload)` from an\n action's after-commit phase (`effects.enqueue`), so rolled-back writes\n never notify and `dryRun` sends nothing. Declarative targets\n (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`)\n resolve server-side in the queue consumer — subscription crypto never\n enters action code. Targeting speaks the realtime identity-tag dialect\n and is fail-closed: `[]` selects nobody, broadcast requires an explicit\n `{ all: true }`.\n- **Default schema** (`push.defaultSchema: true`) — owner-firewalled,\n INTERNAL-read `push_subscriptions` with a `views.mine` device list.\n Creates validate `https:` endpoints (SSRF blocker), 65-byte P-256\n `p256dh`, 16-byte `auth`; `tags` is stamped server-side from the\n session's proven identity (client tags ignored); 10/min create rate\n limit; per-user cap keeps the newest 10 live subscriptions.\n- **Fail-closed config** — a literal `vapidPrivateKey` in config is a\n compile error (`env:VAPID_PRIVATE_KEY` only); the worker refuses to boot\n without the three VAPID vars; the private key never lands in\n `wrangler.toml`, SPA bundles, or logs (DLQ chunks log counts only).\n- **SPA bake** — the VAPID public key ships to CMS/Account bundles as\n `VITE_QUICKBACK_VAPID_PUBLIC_KEY` and `window.__QUICKBACK_RUNTIME.vapidPublicKey`.\n- **CLI** — `quickback push generate-keys [--out <file>]`; `--out` writes\n the private key to a `0600` file so it never touches stdout or shell\n history.\n\nSee [Web Push](/stack/push) for the full guide.\n\n## v0.52.1 — July 17, 2026\n\n### CLI: cold-start tolerance for the cloud compiler\n\nRight after a service deploy, the first compile pays a fresh container image\npull — which routinely exceeds the CLI's old 60-second readiness budget and\nsurfaced as `Compiler container did not become ready in time` even while\n`/health` was green. `waitForReady` now allows 4 minutes, reports elapsed\nwarm-up progress, and the timeout message explains the deploy-in-progress\ncase.\n\n## v0.52.0 — July 17, 2026\n\n### Five action primitives: afterCommit, realtime emit, transitions v2, refs, bundles\n\nOne release, five primitives that collapse the most-repeated hand-written\npatterns in real Quickback projects (measured across a 349-action production\ncorpus). Every one is additive — existing projects compile unchanged, and\nplain `{ field, fromTo, to|via }` transitions keep their emission\nbyte-identical.\n\n- **`afterCommit` hooks + `effects.enqueue`** — named best-effort side\n effects that run after `execute` returns. Each hook is independently\n wrapped (failures log as `[<action>] afterCommit:<hook> failed`, never\n touching the response), non-blocking hooks ride `executionCtx.waitUntil`,\n `{ blocking: true }` awaits before responding, and everything skips when\n `execute` throws or returns `dryRun: true`. The execute context also gains\n `effects.enqueue(name, fn)` for mid-execute captures and `now` — one ISO\n timestamp per invocation. Replaces the per-leg `try/catch + waitUntil`\n idiom. See [After-commit hooks](/compiler/definitions/actions#after-commit-hooks).\n\n- **Realtime emit for custom actions** — tables that lock auto-CRUD no\n longer hand-roll frames. `realtime: { emitFromActions: true, scopeKeyFrom:\n \"events:{eventId}\" }` makes scoped-db writes inside record-bound and bulk\n actions emit auto-CRUD-byte-compatible frames after commit (masking +\n audience applied at fanout; the fail-closed audience requirement extends to\n action emission). Actions can also declare `emit:` for a pre-bound\n `emitCrud(row, oldRow?)`. Updates/deletes pre-select old rows on the same\n WHERE; raw `unsafeDb` writes stay invisible. See\n [When auto-broadcast fires](/stack/realtime/durable-objects#when-auto-broadcast-fires-and-when-you-call-it-manually).\n\n- **Transitions v2** — `transition` grows `guard` (equality / null / notNull\n / `custom(record)`), `onIllegal { code, status, message }`, `idempotent:\n \"noop\"`, and `stamp`/`clears` that ride a compiler-applied, TOCTOU-safe\n UPDATE (guards fold into the WHERE; a lost race is 409\n `ACCESS_TRANSITION_LOST`). With an applied write, `execute` becomes\n optional. Table-level `transitions: { publish: { field, from, to, access } }`\n *generates* the action files — including `undo:` inverses and `onEnter`\n cascades — mounted exactly where hand-written files would be (explicit\n files win, with a warning). The ten byte-identical publish/revert files in\n the podcast fixture become two lines per entity. See\n [Transitions](/compiler/definitions/transitions).\n\n- **`refs` — scoped foreign-key inputs** — the \"load the id, 404 if missing,\n assert it belongs to this event\" preamble becomes declarative. Loads run\n through the scoped db (a cross-org id 404s by construction), batch into one\n `Promise.all`, assert `matchScope` / cross-input `matchWith` parenthood, and\n inject rows under their `as` names. Ref keys are validated against the\n inline `z.object` input (with agreeing optionality) at compile time. See\n [Refs](/compiler/definitions/actions#refs-scoped-foreign-key-inputs).\n\n- **`defineBundle` — single-round-trip bootstrap reads** — declarative\n `list()` slices with the firewall, the table's *real* mask functions, and\n `{ data }` cache-seed envelopes; `custom()` escape-hatch sections; a SHA-1\n ETag over `{ scopeSeed, userId, payload }` with the `ifNoneMatch →\n notModified` short-circuit; and `Server-Timing`. Fail-closed: a bundle's\n roles must be a subset of every list table's `read.access` roles — a bundle\n can never widen read access. The digest ships as `sha1Hex` in `lib/etag`\n so hand-written reads can delete their copies. See\n [Bundles](/compiler/definitions/bundles).\n\nSupporting changes: `ActionError` / `TransitionLostError` are re-exported\nfrom the generated `.quickback/define-action` helpers (routes duck-type on\n`error.name`, so project-local copies keep working); `sendQueueBatched` in\n`lib/effects` chunks queue sends at the Cloudflare 100-message cap; and the\n`$record.*` / `$ctx.*` substitution grammar used by `onEnter` and bundle\n`where` is one strict allowlist, always parameterized — never interpolated\ninto SQL.\n\n### CLI device login fixed: /cli/authorize now claims the code before approving\n\nBetter Auth's `deviceAuthorization` plugin requires the verifying session to\nclaim a device code (`GET /device?user_code=…`) before it accepts an approve\nor deny. The account SPA's `/cli/authorize` page posted the approval directly,\nso every `quickback login` failed with *\"Device code has not been claimed by\na verifying session.\"* The page now claims first, then approves — and surfaces\nclaim failures (expired or mistyped codes) with the server's message.\n### Generated builds no longer rewrite the auth schema\n\nGenerated Better Auth projects now run `tsc` directly from `npm run build`.\n`quickback compile` already generates, qualifies, and envelopes\n`src/auth/schema.ts`; invoking `auth:schema` again during every build rewrote\nthat compiler-owned artifact and made an otherwise clean release worktree\ndirty. The explicit `auth:schema` diagnostic command remains available, while\nnormal build, Wrangler, and deployment preflight paths are source-read-only.\nWhen recompiling an existing project, compiler-owned `package.json` script\nnames now converge to their current generated commands while unrelated custom\nscripts are preserved. This upgrades projects whose previous generated\n`build` script still invoked `auth:schema`.\n\n### Non-cross-tenant unsafe actions preserve delegated RLS claims\n\nGenerated Neon handlers now reserve `createServiceDb` for actions that\nexplicitly enable `unsafe.crossTenant`. An action that enables raw database\naccess with `crossTenant: false` keeps the request database, so organization\nand delegated-principal claims survive into Hyperdrive transactions instead of\nbeing cleared by the service-role preamble. True cross-tenant sysadmin actions\nretain their audited RLS bypass.\n\nNeon Hyperdrive guidance now also calls out Postgres' `SELECT … FOR UPDATE`\nauthorization rule: a locked row must pass both `SELECT` and `UPDATE` policies.\nDelegated actions should use ordinary selects for read-only eligibility tables\nand lock only mutable rows they are authorized to update. A PGlite regression\nproves that ordinary delegated reads remain visible while the generated\nrestrictive update fence blocks an unauthorized row lock.\n\n### Atomic email-OTP auth routing no longer recurses on ordinary requests\n\nThe generated atomic email-OTP wrapper now captures and binds Better Auth's\noriginal request handler before replacing the public `handler` property.\nSession reads and every other non-atomic auth route therefore forward to Better\nAuth exactly once instead of re-entering the wrapper until the Worker exhausts\nits call stack. The exact email-OTP sign-in route retains its transactional\nadmission and rollback behavior.\n\n### Generated Better Auth CLI dependencies no longer retain vulnerable Lodash\n\nBetter Auth projects now emit a root npm override for `lodash@4.18.1`. This\nkeeps the supported stable `auth@1.6.x` CLI and its `better-auth` executable,\nwhile lifting the CLI's dev-only Prisma parser chain off Lodash releases\naffected by the 2026 code-injection and prototype-pollution advisories. Runtime\nBetter Auth packages and generated authentication behavior are unchanged.\n\nThe CLI now merges generated npm overrides explicitly when recompiling an\nexisting project: unrelated user overrides remain, while compiler-owned\nsecurity pins win a conflict. Recompile and reinstall dependencies to refresh\nthe project lockfile. `npm audit --omit=dev` remains the production dependency\nview; upstream development-server advisories may still appear separately.\n\n### Postgres constraint replacements apply in dependency-safe order\n\nNeon migration post-processing now orders both halves of a Drizzle constraint\nreplacement. A dependent foreign key is dropped before its referenced unique\nor primary-key constraint, then the replacement key is added before the\nforeign key that consumes it. This prevents Postgres `2BP01` failures when\nDrizzle emits the parent key drop first, while preserving byte-identical output\nfor already-correct migrations and the relative order of unrelated statements.\n\n### Schema registry output is byte-reproducible\n\n`schema-registry.json` no longer includes the wall-clock `generatedAt` field.\nIts remaining metadata and schema content are derived entirely from compiler\ninputs, so consecutive compiles of identical logical input now produce the\nsame registry bytes. This makes artifact hashes, caches, and deployment diffs\nstable without timestamp normalization.\n\n### Generated auth and discovery surfaces now remain truthful and type-safe\n\nAtomic email-OTP generation now imports and invokes\n`before-email-otp-activate.ts` exactly once and preserves the transaction's\nreal Drizzle `select` capability in the hook context. Strict generated\nTypeScript therefore accepts both the base Neon service database and its\ninteractive transaction without erasing the hook's read contract.\n\nContract-v2 projects that omit `auth.jwt` no longer advertise the disabled\nQuickback JWT fast path in `llms.txt` or RFC 8414 metadata. Bearer-JWT guidance,\nthe fallback `/api/v2/token` endpoint, and JWT scopes are emitted only when the\ncorresponding JWT surface exists; real Better Auth OAuth-provider discovery is\nunchanged.\n\nCloudflare Email callbacks now all enter the shared credential-delivery\nscheduler exactly once. The scheduler anchors the observed rejection with\n`waitUntil`, emits the metadata-only `auth.credential_delivery_failed` event,\nand never leaks the provider error. Generated CRUD routes also keep delegated\nprincipal and account authority disjoint: `?organizationId=` is rejected for a\ndelegated principal instead of synthesizing `activeOrgId` on its context. This\ncloses both the authority ambiguity and the generated `AppContext` union type\nerrors.\n\n### Email-OTP activation can be admitted atomically in the API layer\n\nContract-v2 Cloudflare projects using one Neon Hyperdrive database can opt the\nexact Better Auth `POST /sign-in/email-otp` handler into an interactive\ntransaction with `atomicAuthRoutes: [\"emailOtpSignIn\"]`. The paired recognized\nhook, `quickback/hooks/before-email-otp-activate.ts`, receives a proven dormant\nuser `{ userId, email, user }` plus transaction-bound `db` / full `schema` and\n`authDb` / `authSchema` handles. Quickback owns only identity proof and atomic\norchestration; application admission, status, event, pass, and eligibility\nrules remain authored in the project API hook.\n\nThe hook executes after OTP validation but in Better Auth's\n`databaseHooks.user.update.before`, before the user update lock. This preserves\napplication-first lock ordering and avoids the user-to-application inversion a\nsession-create hook would introduce. Unknown-email signup must be disabled;\nalready-verified users do not rerun dormant activation.\n\nThe generated handler rebuilds Better Auth over the transaction handle, so OTP\nconsumption, project hook writes, the `emailVerified` update, and session insert\ncommit together. Admission denial, a non-ok response after activation starts,\nand any 5xx response throw a private rollback sentinel. Expected policy denial\nreturns a generic 403. Operational rollback emits the metadata-only\n`auth.atomic_email_otp_operational_rollback` event and returns a generic 503,\nwithout exposing raw errors. Ordinary invalid-OTP 4xx responses still commit\nBetter Auth's attempt accounting, and the OTP-send route remains outside the\ntransaction. Unsupported contracts, runtimes, database modes,\nmissing/duplicated config, enabled signup,\nand a hook/config mismatch now fail at compile time.\n\n### Neon migrations can declare cross-schema foreign keys\n\nNeon projects can now declare fully qualified, single-column or composite\nforeign keys under `compiler.migrations.foreignKeys`. Each entry names the\nconstraint, source and target schema/table/column tuples, and explicit\n`onDelete` / `onUpdate` actions. The compiler rejects unsafe identifiers,\nmismatched tuple arity, duplicate or ambiguous declarations, unknown keys,\nand non-Neon providers before generating SQL.\n\nDeclared constraints are sorted deterministically and folded into Quickback's\ncontent-addressed Postgres journal after the Drizzle schema migration. A new\nconstraint is added `NOT VALID` and then validated, so existing orphan rows\nfail the migration; replay verifies an exact catalog match and rejects a\nsame-named constraint with different semantics. This surface enforces\nrelational integrity only—business rules remain in generated or authored API\nactions, not database triggers.\n\n### Compile completion steps honor the Neon connection mode\n\nThe CLI's successful-compile footer now distinguishes Neon HTTP from\nHyperdrive. HTTP projects retain the direct `DATABASE_URL` Worker setup.\nHyperdrive projects show `DATABASE_MIGRATION_URL` only as a local or CI\nmigration input, point local development at the configured Hyperdrive\n`localConnectionString`, and never recommend deploying `DATABASE_URL` as a\nWorker secret.\n\nNamed Hyperdrive environments also show their configured Neon branches,\nrequired-secret inventories, and explicit Wrangler `--env` targets. The footer\nno longer suggests the unnamed `.env.neon` / `.dev.vars` workflow or a bare\ndeploy for an isolated `dev` / `prod` setup.\n\n### Cloudflare email delivery and named Neon targets fail visibly and deploy explicitly\n\nGenerated Cloudflare email code now uses the native Workers `SendEmail`,\n`EmailAddress`, attachment, and `EmailSendResult` contracts. The Workers\nbuilder keeps its camel-case fields and `{ email, name }` address shape, while\nthe REST transport retains its separate snake-case fields and `{ address,\nname }` shape. Generated projects move to `@cloudflare/workers-types` v5 with\nWrangler 4.110 so the binding and result types agree without `any` casts.\n\nEvery Better Auth email callback now creates an observed delivery promise. On\nWorkers, the callback hands that still-rejecting promise to\n`executionCtx.waitUntil(...)` and returns after the task is accepted; outside a\nrequest lifecycle it returns the promise for the caller to await. Failures emit\nonly a structured generic event, never provider error content, and remain\nrejected instead of being detached or swallowed. SES and SNS background sends\nuse the same lifecycle rule.\n\nNeon Hyperdrive's generated postgres.js client now caps each request-scoped\npool at five connections. Named environments gain explicit `deploy:dev` and\n`deploy:prod` package scripts (mapped to their configured Wrangler environment\nnames), while the unsafe bare `deploy` script remains absent and migrations\nremain a separate target-owned step.\n\n### Contract v2 auth and Neon authority boundaries are fail-closed\n\nContract-v2 projects no longer emit Quickback's generic JWT mint endpoint,\nJWT helper, middleware verification/mint fast-path, or related imports unless\nthe project explicitly declares `auth.jwt`. Contract v1 retains its existing\ndefault for compatibility. Adding `auth.jwt: {}` to a v2 config opts back into\nthe custom Quickback JWT with its normal default settings.\n\nConfigured delegated authenticators now produce closed TypeScript unions in\nboth generated `AppContext` and Neon RLS context. Request contexts contain only\nresolved principal variants; the compiler-internal credential-lookup variants\nexist only in the database context. Delegated standalone actions do not require\nBetter Auth `activeOrgId` / `activeTeamId` before their declared principal\naccess tree runs, and their context cannot acquire account, organization, team,\nmembership, or scope authority.\n\nOn Cloudflare + Neon, the API-key organization membership lookup now runs with\nrequest-scoped user/org RLS claims before it stamps verified organization and\nrole authority into `AppContext`. Generated security migrations also converge\ndirect privilege drift: the audit schema/table revoke all direct grants from\n`PUBLIC`, the runtime, and admin before restoring their exact write-only/admin\nsets, while the Drizzle journal schema/table/sequences and database `CREATE`\ncapability explicitly revoke `PUBLIC` and runtime access before granting the\nmigration role.\n\n### Standalone action routes preserve their exact authority context\n\nGenerated standalone routes now pass each action the context and scoped\ndatabase types inferred from that action's own `execute` signature. Account actions therefore receive a\nrequired account identity, while `event_pass`, `event_delegate`, and other\ndelegated-principal actions retain their exact principal literal at the route\nboundary. Relationship `loads` / `exposeAs` hydration is intersected with that\nauthority context, including required shared targets and optional distinct\nmulti-lane targets, instead of replacing it with the broad application\ncontext.\n\nThe same boundary keeps ordinary request databases and temporary\nservice-role-backed scoped databases assignable to the generated Hyperdrive\naction helper without widening the handler's schema-aware `db` type.\n\nGenerated principal-auth identity guards also emit explicit strict TypeScript\nparameter and return types. Contract-v2 Cloudflare + Neon output no longer\nfails `tsc` on implicit-`any` guard parameters.\n\n### Parameterized actions keep complete v2 schema harvests\n\nThe action-input harvest plan now converts Hono-style `:param` segments to the\nOpenAPI `{param}` form for standalone actions and parameterized resource paths.\nPreviously the CLI could harvest every schema successfully, but the compiler\ncould apply only parameter-free actions because it looked up parameterized\noperations under the wrong OpenAPI key. Contract v2 now counts and patches the\nsame canonical path emitted by OpenAPI and MCP.\n\nGenerated standalone-action routes also remove template-only trailing spaces\nwhen optional audit blocks are absent, keeping regenerated source diffs clean.\n\n### Action-schema harvest uses the generated runtime dependency tree\n\nThe CLI now resolves action-harvest dependencies from the configured\n`build.outputDir/node_modules` before unrelated ancestor installs. This fixes\nisolated projects that keep authored definitions under `quickback/` and the\ngenerated runtime under a sibling directory such as `src/`: their actions can\nuse the runtime's Zod 4 and Drizzle installation without adding workspace-root\nsymlinks. An older user-level or monorepo-level Zod can no longer shadow the\nruntime's declared version during schema evaluation.\n\nSchema-only evaluation also emits inert named table proxies for authored\nDrizzle exports. Shared input/DTO modules may therefore construct top-level\nselection objects such as `{ id: records.id }` without executing a database\noperation or losing the action's Zod schema.\n\nHarvest failures now retain the exact action key, failing phase (`bundle` or\n`evaluation`), and bounded underlying error. Contract v2 includes those\nper-action diagnostics in its fail-closed compile error; v1 retains its\nbest-effort static-schema fallback.\n\n### Contract v2 delegated principals and RLS-only action tables\n\nCloudflare + Neon Hyperdrive projects on `contract.version: \"v2\"` can now\ndeclare framework-generic delegated authenticators under `auth.principals`.\nEach named principal owns an exact, non-`Bearer` Authorization scheme, a\nproject hook that proves the credential and returns only `{ digest }`, and one\ncompiler-owned indexed lookup that resolves the actor, optional session/family,\nstring claims, and active status. The hook receives no database handle. Proof\nhooks authored under `quickback/lib` are staged into generated `src/lib`, even\nwhen no action imports them directly.\n\nDelegated authority is structurally disjoint from Better Auth accounts:\n`ctx.principal` is populated while user, organization, team, and membership\nfields remain absent. Access arms may use `principals: [...]`; fields inside an\narm are ANDed and sibling arms are ORed. Generated action helpers preserve\nthat boundary in TypeScript, including the anonymous possibility of a\n`PUBLIC` sibling arm. Mixed credential transport rejects Authorization plus an\nAPI key or an actual Better Auth session cookie, while unrelated analytics\ncookies do not create a false conflict. `Bearer` remains reserved for account\nauthentication.\n\nResources can also declare operation-specific `databaseAccess` policies for\nauthored actions and support tables. This is an RLS-only surface: it emits no\ngeneric route or OpenAPI operation and is accepted only on Cloudflare + Neon\nHyperdrive. Every authorization path must contain a nonempty SQL-lowerable\nrecord equality; unbounded principal/role leaves, any unbounded OR arm, empty\nrecords, ambiguous mixed boolean nodes, app-only predicates, and unsupported\nproviders fail compilation. This keeps business logic in authored API actions\nwhile Postgres independently enforces the same event/person or account/org row\nboundary.\n\nPrincipal claims use the same transaction-local Hyperdrive preamble as account\nclaims, with query caching disabled. Restrictive per-operation principal\nfences prevent a public, exception, or legacy permissive policy from admitting\nthe wrong principal type. Credential lookup indexes and RLS journal entries are\ncontent-addressed and converge when a table, digest column, or definition\nchanges; generated Postgres identifiers include collision-resistant hashes and\nstay within the 63-byte limit. Each security migration also drops the complete\ncompiler-owned `databaseAccess` policy family before recreating the current\noperations, so removing or moving an operation revokes the old permissive\npolicy instead of leaving it active. Record fields resolve through authoritative\nDrizzle metadata to exact quoted physical identifiers, unknown fields fail the\ncompile, and DB-only pseudo-roles follow the same ADMIN/SYSADMIN/INTERNAL\ncontract as the application surface.\n\n### Action execute helpers preserve their typed boundary\n\nGenerated per-feature `defineAction` helpers no longer erase `services`, the\nHono request context, record predicates, or the action's return value to\n`any`. Zod input and record inference remain intact, `whereRecord` and\n`whereTransition` accept only the helper's bound table, and the existing D1 /\nNeon Hyperdrive scoped `db` and interactive `tx` types now flow through the\nsame execute boundary. The returned value is inferred exactly; this does not\nadd a response schema, invalid-return rule, or new output contract.\n\nHTTP/WebSocket Neon retains its intentionally dynamic `db`, and `AppContext`\nretains its open index signature for runtime-hydrated namespace fields.\n\n### Neon Hyperdrive is now the only Worker database lane, including Better Auth\n\nFor `connectionMode: \"hyperdrive\"`, generated Better Auth code now uses the\nsame HYPERDRIVE-backed, service-role-scoped database handle as the rest of the\ngenerated API. `DATABASE_URL` is no longer emitted or required as a Worker\nsecret in Hyperdrive mode; migration credentials remain inputs to the compiler\nor CI environment. HTTP-mode Neon retains its existing `DATABASE_URL` runtime\ncontract.\n\n### Public contract v2 now compiles as one coherent API/auth surface\n\nProjects may set `contract: { version: \"v2\" }` to select `/api/v2/*` feature\nroutes and `/auth/v2/*` Better Auth routes. The compiler now threads that\nselection through generated route mounts, Better Auth configuration and\nmiddleware, OpenAPI paths and server metadata, MCP internal tool calls, OAuth\ndiscovery, `llms.txt`, schema/embeddings/system routes, live views, namespace\nactions, and dedicated-domain `/v2/*` shortcuts. The option is no longer\nfail-closed. Omitting `contract` or selecting `v1` preserves the existing v1\noutput.\n\nBundled CMS and Account clients now receive the selected API and auth base\npaths through both their Vite build environment and the Worker-injected runtime\nconfig. CMS CRUD, schema, sysadmin, and live-view requests and Account auth,\ndata, and live-view requests therefore stay on `/api/v2` and `/auth/v2` for a\nv2 project instead of falling back to client-side v1 literals. V1 SPA config\nretains its historical byte shape.\n\nV2 compiles also require a complete client-side action input-schema harvest.\nThe current CLI reports the exact action files that failed to produce a JSON\nSchema, and the compiler independently rejects missing, invalid, or partial\nmaps at the shared parse boundary used by both complete and validation-only\ncompiles. `POST /compile?complete=false` can no longer bypass the v2 gate. For\nrecord actions with `bulkVariant: true`, the harvested schema now patches both\nthe single-record request body and the bulk operation's nested `input`; the\naction is counted complete only when both OpenAPI targets exist. Harvest\nplanning also normalizes filename-based action bindings to the table's declared\nname and resource path, so kebab-case filenames exporting snake/camel-case\ntables are not silently omitted. V1 remains best-effort for backward\ncompatibility.\n\n### Complete, isolated Wrangler targets for named Neon environments\n\n`providers.database.environments` now defines deployable Neon Hyperdrive\ntargets instead of emitting empty `[env.*]` shells. Because Wrangler does not\ninherit vars or bindings into named environments, each target must explicitly\nown its generated vars, required-secret contract, Hyperdrive and KV IDs,\nrate-limit namespace IDs, and Cloudflare Email binding. The compiler rejects\nmissing overrides, shared stateful IDs, optional secret declarations, invalid\ntarget semantics, and unsupported binding families rather than generating a\nWorker that starts without part of its runtime.\n\nThe required-secret inventory is now centralized and includes generated\ncredentials as well as custom declarations: `BETTER_AUTH_SECRET`, a configured\n`auth.jwt.secretEnv`, `ENCRYPTION_KEK` when envelope encryption is present, and\nevery `bindings.secrets` entry marked `required`. Generated Better Auth SES/SNS\ncredentials, AWS-backed anonymous-upgrade credentials, enabled social-provider\nclient id/secret pairs, and R2 presign credential env names are included as\nwell. Cloudflare social auth now reads those credentials from the Worker `env`\nbinding instead of relying on `process.env` compatibility behavior. Named\ntargets also reject every generated top-level custom-domain source — including\nruntime routes, the primary/CMS/Account/Admin/Auth/API domains, and app domains\nor aliases — until routes can be declared with explicit per-environment\nownership; top-level routes can no longer produce an ambiguous deployment\ntarget.\n\nNamed targets are currently limited to Neon Hyperdrive with Better Auth.\nExternal auth remains fail-closed until its service binding can be declared\nindependently for every named environment.\n\nFor named-environment projects, the base Worker has no deployable stateful\nbindings, local development selects a named target, and that selected target\nis always the required logical `dev` environment, which must own an explicit\ndevelopment-only Hyperdrive `localConnectionString`. Quickback emits it only\nin the selected named binding, rejects a top-level\noverride when named environments exist, and rejects local URLs on staging or\nproduction targets; deployed targets continue to resolve the remote\nHyperdrive configuration by ID. The generated package omits the unsafe bare\ndeploy script. Existing projects that omit\n`environments` keep byte-identical Wrangler output and the existing dev/deploy\nscripts. See [Neon → Named Cloudflare deployment environments](/compiler/targets/hono-api/database/neon#named-cloudflare-deployment-environments).\n\n### Local compiler trust boundary and deterministic Drizzle commands\n\nThe supported Docker launcher now opts into unauthenticated local compilation\nexplicitly and publishes the compiler only on `127.0.0.1`; missing or unknown\ncompiler modes retain hosted authentication. The CLI recognizes only exact\nloopback hostnames as local. Migration post-commands now use the configured\npackage manager's local binary execution form, with npm forced offline and its\nimplicit install prompt disabled, so a missing `drizzle-kit` fails clearly\ninstead of fetching an unpinned package.\n\n### Action rate limits now emit — documented since the rate-limit pillar, wired now\n\nThe [rate-limit docs](/compiler/definitions/rate-limit#actions) have described\nper-action rate limiting since the pillar shipped: record-based actions inherit\nthe resource's `update` bucket, standalone actions inherit the project-default\n`update` bucket, and actions may declare a `rateLimit` override or opt out with\n`rateLimit: false`. The generated routes never contained the checks. They now\ndo, exactly per the documented contract:\n\n- Record-based actions (and their bulk variants, which share the same counter —\n one token per batch request) are keyed\n `<resource>:action:<name>:<user>`; standalone actions are keyed\n `standalone:<declaredPath>:<user>`. The `:action:`/`standalone:` infixes mean\n action counters never collide with CRUD counters.\n- `rateLimit: { limit, period }` on an action emits its own binding\n (deduped by tuple, same `RL_<limit>_<period>` scheme); `rateLimit: false`\n opts the action out entirely.\n- Record-based action routes are now **exempted** from the per-resource CRUD\n catch-all middleware. Previously a `POST /:id/approve` was incidentally\n counted against the resource's `create` bucket — wrong bucket, wrong key.\n- Actions-only (tableless) projects now provision the project-default binding;\n previously they shipped with none.\n\n**Behavior change:** standalone actions were previously *unlimited*; they now\ninherit the project-default `update` bucket (200 requests / 60s per user/IP\nwith shipped defaults). PUBLIC webhook-style endpoints that absorb provider\nbursts should declare their own budget (`rateLimit: { limit: 1000, period: 10 }`)\nor opt out (`rateLimit: false`). The compiler emits a warning when a PUBLIC\nstandalone action silently inherits the default, so affected actions are\nflagged at compile time.\n\n### Better Auth CLI pinned and shipped as a generated devDependency\n\nThe generated `auth:schema` script runs `npx better-auth generate`, but the\n`better-auth` runtime package ships no executable — the `better-auth` bin\nlives in the npm package `auth` (the official Better Auth CLI; the team took\nover that name at 1.5.0, superseding the frozen `@better-auth/cli`). Generated\nprojects now declare `auth` as a devDependency pinned to the runtime's minor\nline, so `npm run auth:schema` resolves the CLI locally instead of requiring a\nglobal install. The compiler image's global CLI is pinned to the same version,\neliminating silent skew between the CLI on `latest` and the pinned runtime.\n\n### Compile warning when an action's input schema degrades to untyped\n\nWhen action input schemas aren't harvested client-side (older CLI, or a direct\n`/compile` API call), the static Zod parser supplies OpenAPI/MCP input schemas\n— and silently degrades unrecognized constructs (discriminated unions,\nrefinements, `z.record`, transforms) to the accept-anything `{}`. That\ndegradation is no longer silent: the compile result now carries a warning per\naffected action naming the route, source file, and the exact untyped field\npaths. Actions covered by the CLI harvest are never warned on, and actions\nthat declare no input are skipped.\n\n### Auth docs: JWT security posture stated up front\n\nThe [Auth & JWT page](/compiler/config/auth) now leads with the posture\nsummary instead of burying it: the default 180-second auto-refreshed TTL plus\n`revocationCheck: 'kv'` (seconds-level revocation, auto-stamped on ban /\nmember removal / role change / scope-conferring row changes) is the\nrecommended configuration and covers the vast majority of deployments — with\nthe residual trade-offs (per-principal granularity, fail-open on KV outage,\n~60s cross-PoP propagation) stated explicitly for strict threat models.\n\n### Neon via-user reads: generated list handlers now typecheck against the concretely-typed service handle\n\nOn Neon, a read firewall carrying a via-user multi-hop relationship predicate\nroutes the generated read handlers to `createServiceDb(c.env)` — a genuine\n`NeonHttpDatabase<typeof schema>` — instead of the loosely-typed request db.\nThe list handler's query construction declared drizzle select builders with\n`let` and reassigned them (`query = query.where(…)`, `.orderBy(…)`,\n`.limit(…).offset(…)`, and the count/aggregation/group-by variants), which is\na type error against drizzle's immutable builder typing: `.where()` returns\n`Omit\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
7
7
  },
8
8
  "compiler/claude-code-skill": {
9
9
  "title": "AI Developer Tools",
@@ -83,7 +83,7 @@ export const DOCS = {
83
83
  },
84
84
  "compiler/definitions/actions": {
85
85
  "title": "Actions",
86
- "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment, and\nit must be a valid **camelCase identifier** — `sendMessage.ts`, not\n`send-message.ts` (hyphenated names are a compile error, since the name becomes\na generated identifier).\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper. It infers `record` and Zod `input`, exposes the generated\n> `Services`, types `c` as a Hono request context, binds `whereRecord` and\n> `whereTransition` to the feature table, and preserves the exact value\n> returned by `execute` without imposing an action-output schema. Scoped\n> `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;\n> HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`\n> also retains its open index for namespace-hydrated fields. Audit fields\n> (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Local input-schema harvest\n\nBefore sending a compile request, the CLI loads each action in an isolated\nlocal bundle and converts `action.input` with Zod 4's `z.toJSONSchema`. It does\nnot call `execute`; the hosted compiler never evaluates project code. Under\ncontract v2, every action must produce a schema. A failure names the exact\naction, whether bundling or evaluation failed, and the underlying local error.\nV1 can still fall back to the lower-fidelity static schema parser.\n\nBare imports are resolved from the generated runtime's configured\n`build.outputDir/node_modules` first. If definitions live in `quickback/` and\nthe generated Worker lives in `src/`, install runtime dependencies in `src/`\nas usual; no project-root dependency symlink is required. Shared schema or DTO\nmodules may also declare top-level Drizzle selection objects. Quickback\nreplaces authored table exports with inert proxies during this schema-only\nevaluation, so reading `records.id` to build a projection does not execute\napplication or database logic.\n\nParameterized standalone paths use Hono's `:param` syntax in authored source,\nfor example `path: \"/events/:eventId/check-in\"`. The harvest planner converts\nthose segments to the OpenAPI `{param}` form before applying the schema, so\ncontract-v2 completeness uses the same route key as the emitted OpenAPI and MCP\nsurfaces. The same normalization applies when a record resource path contains\nnamespace parameters.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair. Lives on a record-based action, or on a standalone action paired with a `record:` binding. See [Transitions](/compiler/definitions/transitions) |\n| `record` | Standalone only | Feature-area transition adapter binding: `{ table, idFrom: \"path.<param>\", matchScope? }`. Binds + firewalls the record a `transition` operates on from a proven route param. See [Feature-area transition adapter](#feature-area-transition-adapter) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/stack/webhooks/inbound) |\n| `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/stack/api-contract) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\nThe generated OpenAPI document and MCP tools reuse that exact action schema\nin both places: as the single-record request body and as the bulk wrapper's\nnested `input` property. Under contract v2, Quickback considers the action's\nschema harvest complete only after both operations are patched. This also\nholds when the table filename and declared table name use different casing or\nseparators (for example, `event-guests.ts` exporting `event_guests`); the\noperations follow the table's declared resource path.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (the driver has no `db.transaction`; `drizzle-orm/neon-http` throws at runtime) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\nPaths are absolute (`/...`). Inside a [feature area](/compiler/definitions/feature-areas)\nwith a mounted prefix, two more forms apply:\n\n- **Relative** — `path: './tasks/add'` resolves against the area's prefix\n (`/project/:projectId/tasks/add`). Plain descending segments only; `.` / `..` segments are\n rejected at compile time.\n- **Self-gated** — an absolute path *outside* the area's prefix opts the action out of the\n area's admission gate and MUST carry `route: 'self'` (fail-closed; the marker is rejected\n where it would be dead). The action is then gated solely by its own `access:` and listed in\n `quickback/authz-manifest.json`.\n\nAn action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —\nand never vocabulary of an area the feature is not inside (compile error).\n\n### Feature-area transition adapter\n\nA record [state transition](/compiler/definitions/transitions) normally lives on a\ntable-bound record action (`POST /:id/{action}`). When your clients call a nested\n**feature-area** route instead, you can attach the same compiler-owned transition to\nan explicit (`path:`) action by adding a `record:` binding. The binding is what lets a\n`transition` ride a standalone action — without it, `transition` on a `path:` action is\na compile error.\n\n```typescript\n// features/events/event_documents/actions/publishEventDocument.ts\nexport default defineAction({\n path: \"/events/:eventId/documents/:documentId/publish\",\n method: \"POST\",\n description: \"Publish one completed event document.\",\n input: z.object({ idempotencyKey: z.string().min(8) }),\n access: { roles: [\"member+\"] },\n // The compiler — not the action body — binds and firewalls the record.\n record: {\n table: \"event_documents\",\n idFrom: \"path.documentId\", // MUST be a route param, never a body field\n matchScope: \"event\", // row.eventId === ctx.event.id (area-proven)\n },\n transition: {\n field: \"status\",\n to: \"published\",\n fromTo: { draft: [\"published\"] },\n idempotent: \"noop\",\n stamp: { at: \"publishedAt\" },\n },\n async execute({ record, invalidate }) {\n // `record` is already bound, firewalled, area-matched, and transitioned.\n // Own the response projection + invalidations here.\n return { success: true as const, document: record };\n },\n});\n```\n\nSecurity semantics (all enforced by the compiler, fail-closed):\n\n- The record id is bound from the **proven route param** named in `idFrom` (`path.<param>`);\n a request-body source is rejected at compile time.\n- The row is loaded through the **scoped db**, so the table's full firewall\n (org / owner / team + soft-delete) applies — a cross-tenant id is a `404`, never a leak.\n- `matchScope` asserts the row belongs to the **area-proven** scope (e.g. `:eventId`\n hydrated onto `ctx.event`); an unhydrated scope fails closed (`500`), and a row under a\n different scope is a `404` (no cross-scope existence oracle).\n- The transition keeps its **TOCTOU-safe guarded UPDATE** — the from-state is re-validated\n in the `WHERE`, and a lost race returns `409` `ACCESS_TRANSITION_LOST`.\n- Area admission **and** the action's own `access:` still AND-compose; the adapter widens neither.\n- `idempotent: \"noop\"` short-circuits **before** `execute`, so a no-op never fires the\n action's invalidations. Existing record actions and table-level transitions are unchanged.\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\n[Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.\n\n**A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Delegated principals and `databaseAccess`\n\nOn a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a\nconfigured delegated principal with `access.principals`:\n\n```typescript\nexport default defineAction({\n description: \"Confirm attendance from an event session\",\n path: \"/attendance/confirm\",\n input: z.object({ response: z.enum([\"yes\", \"no\"]) }),\n access: { principals: [\"event_delegate\"] },\n async execute({ ctx, db, input }) {\n // ctx.principal is guaranteed and narrowed by the generated helper.\n const { eventId, personId } = ctx.principal.claims;\n return confirmAttendance(db, { eventId, personId, response: input.response });\n },\n});\n```\n\nThis is a separate authority lane, not an account impersonation. A delegated\naction context has no `userId`, active organization/team, or membership roles.\nIf access has a `PUBLIC` sibling arm, the generated type includes the anonymous\nlane and code must narrow `ctx.principal` before reading it.\n\nFor an organization- or team-scoped host feature, the standalone route does\nnot run the Better Auth `activeOrgId` / `activeTeamId` precondition before a\nprincipal access tree. Authentication and `evaluateAccessPreRecord` still run;\nthe declared `principals` arm is the authority decision. This avoids turning an\naccount-session field into an accidental prerequisite for delegated callers.\n\nThe generated standalone route reuses that action-specific `execute` context\nafter its runtime access gates. Account, `event_pass`, and `event_delegate`\nactions therefore keep distinct compile-time authority types all the way into\nthe handler. The route also reuses the action's schema-aware scoped `db` type,\nincluding when an unsafe/service-role client is wrapped before the call. If a\nrelationship uses `loads` / `exposeAs`, the loaded row type is\nintersected with the same authority context: a single or shared hydration\ntarget is required, while targets selected by distinct relationship lanes are\noptional and must be narrowed by the handler.\n\nFor tables queried by authored actions, `resource.databaseAccess` adds an\nindependent Postgres RLS policy without adding HTTP surface. It never mounts a\nread/CRUD route and never adds an OpenAPI operation. The action remains the API\nlayer where validation, state transitions, side effects, and business logic\nbelong; `databaseAccess` is only the database's row-level upper bound.\n\n```typescript\nexport default defineTable(attendanceEvidence, {\n // Ordinary account CRUD remains organization-scoped.\n firewall: [\n { field: \"organizationId\", equals: \"ctx.activeOrgId\" },\n ],\n\n // Authored actions can use their caller-scoped db under one of two exact\n // row lanes. Sibling arms OR; fields in each arm AND.\n databaseAccess: {\n select: {\n or: [\n {\n roles: [\"AUTHENTICATED\"],\n record: {\n organizationId: { equals: \"$ctx.activeOrgId\" },\n },\n },\n {\n principals: [\"event_delegate\"],\n record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n personId: { equals: \"$ctx.principal.claims.personId\" },\n },\n },\n ],\n },\n },\n});\n```\n\n`databaseAccess` supports `select`, `insert`, `update`, and `delete`. Its rule\nlanguage is intentionally smaller than application access: `principals`,\n`roles`, recursive `or`/`and`, and record `equals` against a DB-visible account\nor principal context value. `userRole`, functions, request/body values, and\nother predicate operators are compile errors.\n\nEvery authorization path must contain at least one nonempty record equality.\nA principal-only or role-only leaf is rejected; every `or` arm must be bounded.\nAn `and` group is bounded when at least one child bounds every expansion (for\nexample, a principal child AND an event-id record child). A node cannot mix\nleaf fields with `or`/`and`, because the boolean node is the complete rule.\nThis mandatory shape prevents an action declaration from accidentally granting\nthe delegated principal an entire table.\n\nThe supported equality sources are `ctx.userId`, `ctx.activeOrgId`,\n`ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family\nids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The\nrecord keys are Drizzle/JavaScript table field names; Quickback resolves them\nthrough the table metadata and quotes the exact physical PostgreSQL identifier,\nso a field such as `eventId: text(\"event-id\")` is safe. Unknown fields fail the\ncompile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB\nsurface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The\nfeature is rejected outside Cloudflare + Neon Hyperdrive because those targets\ncannot guarantee request-scoped Postgres claims.\n\n### Relational queries are blocked (fail-closed)\n\nDrizzle's relational query API — `db.query.<table>.findFirst()` /\n`findMany()` (including nested `with:` relations) — builds its SQL from the\nrelations config and your `where` alone, so the scoped wrapper cannot inject\nthe org/owner/team firewall into it. Rather than silently returning rows from\nevery tenant, the scoped `db` **throws** on any `db.query.<table>` access:\n\n```typescript\nasync execute({ db, input }) {\n // ❌ Throws: relational queries aren't org-scoped\n const item = await db.query.media.findFirst({ where: eq(media.id, input.id) });\n\n // ✅ Scoped builder — firewall conditions injected automatically\n const [item] = await db.select().from(media).where(eq(media.id, input.id));\n}\n```\n\nIf you genuinely need the relational API, declare the action `unsafe: true`\nand query `unsafeDb.query` with an **explicit** scope predicate in the WHERE\n(e.g. `eq(media.organizationId, ctx.activeOrgId)`), exactly like any other\nunsafe read.\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n**Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query\nbypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An\nunsafe action with `crossTenant: false` receives a raw Drizzle handle backed by\nthe request database, so the caller's organization or delegated-principal\nclaims remain active—including inside `db.transaction()`. Its code must still\nprovide every intended scope predicate explicitly.\n\nOnly an action with `crossTenant: true` acquires the dedicated service-role\nhandle (`createServiceDb`). That handle sets the `quickback.service_role`\ntransaction marker instead of caller claims, and generated RLS grants it an\nexplicit per-table bypass policy. The sysadmin guard and mandatory audit log\ntherefore protect the same boundary that receives the RLS bypass. The\naudit-logging contract is otherwise identical to D1. Neon with\n`connectionMode: 'websocket'` does not support unsafe actions yet and fails\nthe compile with a descriptive error.\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\nTransitions grew a v2 surface — guards, timestamp/actor stamps, idempotent\nno-ops, compiler-applied writes with optional `execute`, `undo` pairs, and\ntable-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.\n\n## After-commit hooks\n\n> For typed realtime *\"this changed — refresh\"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.\n\nSecondary effects — activity feeds, notification nudges, cache warmers — must\nnever roll back or delay the primary write. Instead of hand-wrapping each leg\nin `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:\n\n```typescript\nexport default defineAction({\n // ...\n execute: async ({ db, record, ctx, now }) => {\n await db.update(guests).set({ checkedInAt: now }).where(/* … */);\n return { success: true, checkedInAt: now };\n },\n afterCommit: {\n // Named hooks run after execute returns successfully, in declared order.\n activityFeed: async ({ db, env, record, ctx }, result) => {\n await recordActivity(db, env, { verb: \"guest.checked_in\", /* … */ });\n },\n // blocking: true is awaited before the response (client depends on it).\n issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },\n },\n});\n```\n\nThe contract:\n\n- Hooks receive `(actx, result)` — the same context `execute` got, plus its\n return value.\n- Each hook is **independently wrapped**: a throw is logged as\n `[<action>] afterCommit:<hook> failed` and never affects the response or\n other hooks.\n- Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking\n hooks are awaited before responding.\n- If `execute` throws, no hooks run. A result carrying `dryRun: true` also\n skips them (preview branches never fire side effects).\n- Bulk twins run hooks **once per invocation** with the bulk envelope as\n `result` — per-record fan-out is the hook author's job.\n\nFor effects that need mid-execute data, the context carries an imperative\nescape hatch with the same semantics:\n\n```typescript\nexecute: async ({ db, effects }) => {\n // …\n effects.enqueue(\"cohortRecalc\", () => recalculate(/* … */));\n return { success: true };\n}\n```\n\nEffects enqueued by an `execute` that later throws are dropped. The context\nalso carries `now` — one ISO timestamp per invocation; prefer it over\n`new Date().toISOString()`.\n\n## Realtime emit from actions\n\nTables that lock auto-CRUD but mutate through custom actions no longer need\nhand-written `realtime.insert/update/delete` blocks. Opt the table in:\n\n```typescript\nrealtime: {\n enabled: true,\n access: { roles: [\"member+\"] },\n scopeKeyFrom: \"events:{eventId}\", // sugar for scopeTable + scopeField\n emitFromActions: true, // scoped-db writes auto-emit after commit\n}\n```\n\nWrites to the table through the scoped `db` inside record-bound and bulk\nactions emit frames byte-compatible with auto-CRUD (same envelope, masking,\naudience), after commit, best-effort. For projections, standalone actions, or\ncross-feature targets, declare an action-level `emit:` to get a pre-bound\n`emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in\nthe [realtime docs](/stack/realtime/durable-objects).\n\n## Refs (scoped foreign-key inputs)\n\nThe most common action preamble — load an input id, 404 if missing, assert it\nbelongs to the caller's event/org — becomes declarative:\n\n```typescript\nexport default defineAction({\n input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),\n refs: {\n agendaItemId: { table: \"agendaItems\", as: \"agendaItem\",\n matchScope: \"event\", // row.eventId === ctx.event.id\n notFound: { code: \"ITEM_NOT_FOUND\" } }, // status defaults to 404\n guestId: { table: \"guests\", as: \"guest\",\n matchWith: { ref: \"agendaItem\", on: \"eventId\" }, // cross-input parenthood\n mismatch: { code: \"EVENT_MISMATCH\", status: 400 } },\n locationId: { table: \"locations\", as: \"location\", optional: true, matchScope: \"event\" },\n },\n execute: async ({ input, agendaItem, guest, location }) => { /* … */ },\n});\n```\n\n- Loads run **through the scoped db** before `execute` — the org firewall and\n soft-delete filter apply by construction, so a cross-org id 404s with zero\n hand-written tenancy checks. All loads batch into one `Promise.all`.\n- `matchScope: \"<scope>\"` asserts `row.<scope>Id === ctx.<scope>.id` and\n fail-closes (500) if the scope object isn't hydrated. The explicit form\n `{ column, equals: \"ctx.activeOrgId\" }` is also accepted.\n- `matchWith` compares a column against an earlier-declared ref — declaration\n order defines resolution order; forward references are compile errors.\n- Ref keys must exist on the inline `z.object` input with agreeing\n optionality; `as` names can't shadow reserved context keys. Injected rows\n are the **unmasked** DB rows (masking remains a read-projection concern).\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
86
+ "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment, and\nit must be a valid **camelCase identifier** — `sendMessage.ts`, not\n`send-message.ts` (hyphenated names are a compile error, since the name becomes\na generated identifier).\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper. It infers `record` and Zod `input`, exposes the generated\n> `Services`, types `c` as a Hono request context, binds `whereRecord` and\n> `whereTransition` to the feature table, and preserves the exact value\n> returned by `execute` without imposing an action-output schema. Scoped\n> `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;\n> HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`\n> also retains its open index for namespace-hydrated fields. Audit fields\n> (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n> **Your editor is typed too.** `quickback compile` writes the same typed\n> helpers into `quickback/features/<feature>/.quickback/` (plus a\n> `quickback/tsconfig.json`), so the import above resolves — and typechecks —\n> in the tree you actually edit, not just in the generated output. The helper\n> also **re-exports the feature's table** typed with the generated schema, so\n> compiler-managed columns (`createdAt`, `modifiedBy`, `deletedAt`,\n> `organizationId`) are visible on it without casts:\n>\n> ```typescript\n> import { defineAction, applications } from \"../.quickback/define-action\";\n> ```\n>\n> Prefer this single import over the older\n> `import { applications } from \"../applications\"` — that path resolves to\n> your authored file at edit time, which has no named export and none of the\n> injected columns. The helper files are regenerated on every compile; keep\n> `quickback/features/*/.quickback/` in `.gitignore` (new projects get this\n> automatically).\n\n### Local input-schema harvest\n\nBefore sending a compile request, the CLI loads each action in an isolated\nlocal bundle and converts `action.input` with Zod 4's `z.toJSONSchema`. It does\nnot call `execute`; the hosted compiler never evaluates project code. Under\ncontract v2, every action must produce a schema. A failure names the exact\naction, whether bundling or evaluation failed, and the underlying local error.\nV1 can still fall back to the lower-fidelity static schema parser.\n\nBare imports are resolved from the generated runtime's configured\n`build.outputDir/node_modules` first. If definitions live in `quickback/` and\nthe generated Worker lives in `src/`, install runtime dependencies in `src/`\nas usual; no project-root dependency symlink is required. Shared schema or DTO\nmodules may also declare top-level Drizzle selection objects. Quickback\nreplaces authored table exports with inert proxies during this schema-only\nevaluation, so reading `records.id` to build a projection does not execute\napplication or database logic.\n\nParameterized standalone paths use Hono's `:param` syntax in authored source,\nfor example `path: \"/events/:eventId/check-in\"`. The harvest planner converts\nthose segments to the OpenAPI `{param}` form before applying the schema, so\ncontract-v2 completeness uses the same route key as the emitted OpenAPI and MCP\nsurfaces. The same normalization applies when a record resource path contains\nnamespace parameters.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair. Lives on a record-based action, or on a standalone action paired with a `record:` binding. See [Transitions](/compiler/definitions/transitions) |\n| `record` | Standalone only | Feature-area transition adapter binding: `{ table, idFrom: \"path.<param>\", matchScope? }`. Binds + firewalls the record a `transition` operates on from a proven route param. See [Feature-area transition adapter](#feature-area-transition-adapter) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/stack/webhooks/inbound) |\n| `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/stack/api-contract) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\nThe generated OpenAPI document and MCP tools reuse that exact action schema\nin both places: as the single-record request body and as the bulk wrapper's\nnested `input` property. Under contract v2, Quickback considers the action's\nschema harvest complete only after both operations are patched. This also\nholds when the table filename and declared table name use different casing or\nseparators (for example, `event-guests.ts` exporting `event_guests`); the\noperations follow the table's declared resource path.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (the driver has no `db.transaction`; `drizzle-orm/neon-http` throws at runtime) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\nPaths are absolute (`/...`). Inside a [feature area](/compiler/definitions/feature-areas)\nwith a mounted prefix, two more forms apply:\n\n- **Relative** — `path: './tasks/add'` resolves against the area's prefix\n (`/project/:projectId/tasks/add`). Plain descending segments only; `.` / `..` segments are\n rejected at compile time.\n- **Self-gated** — an absolute path *outside* the area's prefix opts the action out of the\n area's admission gate and MUST carry `route: 'self'` (fail-closed; the marker is rejected\n where it would be dead). The action is then gated solely by its own `access:` and listed in\n `quickback/authz-manifest.json`.\n\nAn action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —\nand never vocabulary of an area the feature is not inside (compile error).\n\n### Feature-area transition adapter\n\nA record [state transition](/compiler/definitions/transitions) normally lives on a\ntable-bound record action (`POST /:id/{action}`). When your clients call a nested\n**feature-area** route instead, you can attach the same compiler-owned transition to\nan explicit (`path:`) action by adding a `record:` binding. The binding is what lets a\n`transition` ride a standalone action — without it, `transition` on a `path:` action is\na compile error.\n\n```typescript\n// features/events/event_documents/actions/publishEventDocument.ts\nexport default defineAction({\n path: \"/events/:eventId/documents/:documentId/publish\",\n method: \"POST\",\n description: \"Publish one completed event document.\",\n input: z.object({ idempotencyKey: z.string().min(8) }),\n access: { roles: [\"member+\"] },\n // The compiler — not the action body — binds and firewalls the record.\n record: {\n table: \"event_documents\",\n idFrom: \"path.documentId\", // MUST be a route param, never a body field\n matchScope: \"event\", // row.eventId === ctx.event.id (area-proven)\n },\n transition: {\n field: \"status\",\n to: \"published\",\n fromTo: { draft: [\"published\"] },\n idempotent: \"noop\",\n stamp: { at: \"publishedAt\" },\n },\n async execute({ record, invalidate }) {\n // `record` is already bound, firewalled, area-matched, and transitioned.\n // Own the response projection + invalidations here.\n return { success: true as const, document: record };\n },\n});\n```\n\nSecurity semantics (all enforced by the compiler, fail-closed):\n\n- The record id is bound from the **proven route param** named in `idFrom` (`path.<param>`);\n a request-body source is rejected at compile time.\n- The row is loaded through the **scoped db**, so the table's full firewall\n (org / owner / team + soft-delete) applies — a cross-tenant id is a `404`, never a leak.\n- `matchScope` asserts the row belongs to the **area-proven** scope (e.g. `:eventId`\n hydrated onto `ctx.event`); an unhydrated scope fails closed (`500`), and a row under a\n different scope is a `404` (no cross-scope existence oracle).\n- The transition keeps its **TOCTOU-safe guarded UPDATE** — the from-state is re-validated\n in the `WHERE`, and a lost race returns `409` `ACCESS_TRANSITION_LOST`.\n- Area admission **and** the action's own `access:` still AND-compose; the adapter widens neither.\n- `idempotent: \"noop\"` short-circuits **before** `execute`, so a no-op never fires the\n action's invalidations. Existing record actions and table-level transitions are unchanged.\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\n[Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.\n\n**A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Delegated principals and `databaseAccess`\n\nOn a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a\nconfigured delegated principal with `access.principals`:\n\n```typescript\nexport default defineAction({\n description: \"Confirm attendance from an event session\",\n path: \"/attendance/confirm\",\n input: z.object({ response: z.enum([\"yes\", \"no\"]) }),\n access: { principals: [\"event_delegate\"] },\n async execute({ ctx, db, input }) {\n // ctx.principal is guaranteed and narrowed by the generated helper.\n const { eventId, personId } = ctx.principal.claims;\n return confirmAttendance(db, { eventId, personId, response: input.response });\n },\n});\n```\n\nThis is a separate authority lane, not an account impersonation. A delegated\naction context has no `userId`, active organization/team, or membership roles.\nIf access has a `PUBLIC` sibling arm, the generated type includes the anonymous\nlane and code must narrow `ctx.principal` before reading it.\n\nFor an organization- or team-scoped host feature, the standalone route does\nnot run the Better Auth `activeOrgId` / `activeTeamId` precondition before a\nprincipal access tree. Authentication and `evaluateAccessPreRecord` still run;\nthe declared `principals` arm is the authority decision. This avoids turning an\naccount-session field into an accidental prerequisite for delegated callers.\n\nThe generated standalone route reuses that action-specific `execute` context\nafter its runtime access gates. Account, `event_pass`, and `event_delegate`\nactions therefore keep distinct compile-time authority types all the way into\nthe handler. The route also reuses the action's schema-aware scoped `db` type,\nincluding when an unsafe/service-role client is wrapped before the call. If a\nrelationship uses `loads` / `exposeAs`, the loaded row type is\nintersected with the same authority context: a single or shared hydration\ntarget is required, while targets selected by distinct relationship lanes are\noptional and must be narrowed by the handler.\n\nFor tables queried by authored actions, `resource.databaseAccess` adds an\nindependent Postgres RLS policy without adding HTTP surface. It never mounts a\nread/CRUD route and never adds an OpenAPI operation. The action remains the API\nlayer where validation, state transitions, side effects, and business logic\nbelong; `databaseAccess` is only the database's row-level upper bound.\n\n```typescript\nexport default defineTable(attendanceEvidence, {\n // Ordinary account CRUD remains organization-scoped.\n firewall: [\n { field: \"organizationId\", equals: \"ctx.activeOrgId\" },\n ],\n\n // Authored actions can use their caller-scoped db under one of two exact\n // row lanes. Sibling arms OR; fields in each arm AND.\n databaseAccess: {\n select: {\n or: [\n {\n roles: [\"AUTHENTICATED\"],\n record: {\n organizationId: { equals: \"$ctx.activeOrgId\" },\n },\n },\n {\n principals: [\"event_delegate\"],\n record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n personId: { equals: \"$ctx.principal.claims.personId\" },\n },\n },\n ],\n },\n },\n});\n```\n\n`databaseAccess` supports `select`, `insert`, `update`, and `delete`. Its rule\nlanguage is intentionally smaller than application access: `principals`,\n`roles`, recursive `or`/`and`, and record `equals` against a DB-visible account\nor principal context value. `userRole`, functions, request/body values, and\nother predicate operators are compile errors.\n\nEvery authorization path must contain at least one nonempty record equality.\nA principal-only or role-only leaf is rejected; every `or` arm must be bounded.\nAn `and` group is bounded when at least one child bounds every expansion (for\nexample, a principal child AND an event-id record child). A node cannot mix\nleaf fields with `or`/`and`, because the boolean node is the complete rule.\nThis mandatory shape prevents an action declaration from accidentally granting\nthe delegated principal an entire table.\n\nThe supported equality sources are `ctx.userId`, `ctx.activeOrgId`,\n`ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family\nids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The\nrecord keys are Drizzle/JavaScript table field names; Quickback resolves them\nthrough the table metadata and quotes the exact physical PostgreSQL identifier,\nso a field such as `eventId: text(\"event-id\")` is safe. Unknown fields fail the\ncompile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB\nsurface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The\nfeature is rejected outside Cloudflare + Neon Hyperdrive because those targets\ncannot guarantee request-scoped Postgres claims.\n\n### Relational queries are blocked (fail-closed)\n\nDrizzle's relational query API — `db.query.<table>.findFirst()` /\n`findMany()` (including nested `with:` relations) — builds its SQL from the\nrelations config and your `where` alone, so the scoped wrapper cannot inject\nthe org/owner/team firewall into it. Rather than silently returning rows from\nevery tenant, the scoped `db` **throws** on any `db.query.<table>` access:\n\n```typescript\nasync execute({ db, input }) {\n // ❌ Throws: relational queries aren't org-scoped\n const item = await db.query.media.findFirst({ where: eq(media.id, input.id) });\n\n // ✅ Scoped builder — firewall conditions injected automatically\n const [item] = await db.select().from(media).where(eq(media.id, input.id));\n}\n```\n\nIf you genuinely need the relational API, declare the action `unsafe: true`\nand query `unsafeDb.query` with an **explicit** scope predicate in the WHERE\n(e.g. `eq(media.organizationId, ctx.activeOrgId)`), exactly like any other\nunsafe read.\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n**Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query\nbypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An\nunsafe action with `crossTenant: false` receives a raw Drizzle handle backed by\nthe request database, so the caller's organization or delegated-principal\nclaims remain active—including inside `db.transaction()`. Its code must still\nprovide every intended scope predicate explicitly.\n\nOnly an action with `crossTenant: true` acquires the dedicated service-role\nhandle (`createServiceDb`). That handle sets the `quickback.service_role`\ntransaction marker instead of caller claims, and generated RLS grants it an\nexplicit per-table bypass policy. The sysadmin guard and mandatory audit log\ntherefore protect the same boundary that receives the RLS bypass. The\naudit-logging contract is otherwise identical to D1. Neon with\n`connectionMode: 'websocket'` does not support unsafe actions yet and fails\nthe compile with a descriptive error.\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()` —\nand on the conflict branch of an `onConflictDoUpdate({...})` upsert.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\nWho the stamped actor is depends on the verified principal, never on\nanything the handler passes:\n\n| Caller | `createdBy` / `modifiedBy` value |\n|---|---|\n| Signed-in user | the Better Auth `userId` |\n| Delegated principal (API key, service) | `actor:<type>:<id>` |\n| Scope-token principal (no account) | `scope:<kind>:<subjectId>` |\n| Cron schedule via `withInternalContext` | `system:cron-<name>` |\n| Queue handler via `withInternalContext` | `system:queue-<name>` |\n| No verified caller | the write **throws** (fail closed) — system-side code that must write outside a request uses the raw client and owns its own provenance |\n\nDon't hand-build audit timestamps as a \"just in case\" fallback: on the\nwrapped `db` they're dead code, and the idiom is a portability trap —\nPostgres audit columns take `Date` objects while SQLite takes ISO strings\n(the wrapper picks the right one per dialect).\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\nTransitions grew a v2 surface — guards, timestamp/actor stamps, idempotent\nno-ops, compiler-applied writes with optional `execute`, `undo` pairs, and\ntable-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.\n\n## After-commit hooks\n\n> For typed realtime *\"this changed — refresh\"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.\n\nSecondary effects — activity feeds, notification nudges, cache warmers — must\nnever roll back or delay the primary write. Instead of hand-wrapping each leg\nin `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:\n\n```typescript\nexport default defineAction({\n // ...\n execute: async ({ db, record, ctx, now }) => {\n await db.update(guests).set({ checkedInAt: now }).where(/* … */);\n return { success: true, checkedInAt: now };\n },\n afterCommit: {\n // Named hooks run after execute returns successfully, in declared order.\n activityFeed: async ({ db, env, record, ctx }, result) => {\n await recordActivity(db, env, { verb: \"guest.checked_in\", /* … */ });\n },\n // blocking: true is awaited before the response (client depends on it).\n issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },\n },\n});\n```\n\nThe contract:\n\n- Hooks receive `(actx, result)` — the same context `execute` got, plus its\n return value.\n- Each hook is **independently wrapped**: a throw is logged as\n `[<action>] afterCommit:<hook> failed` and never affects the response or\n other hooks.\n- Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking\n hooks are awaited before responding.\n- If `execute` throws, no hooks run. A result carrying `dryRun: true` also\n skips them (preview branches never fire side effects).\n- Bulk twins run hooks **once per invocation** with the bulk envelope as\n `result` — per-record fan-out is the hook author's job.\n\nFor effects that need mid-execute data, the context carries an imperative\nescape hatch with the same semantics:\n\n```typescript\nexecute: async ({ db, effects }) => {\n // …\n effects.enqueue(\"cohortRecalc\", () => recalculate(/* … */));\n return { success: true };\n}\n```\n\nEffects enqueued by an `execute` that later throws are dropped. The context\nalso carries `now` — one ISO timestamp per invocation; prefer it over\n`new Date().toISOString()`.\n\n## Realtime emit from actions\n\nTables that lock auto-CRUD but mutate through custom actions no longer need\nhand-written `realtime.insert/update/delete` blocks. Opt the table in:\n\n```typescript\nrealtime: {\n enabled: true,\n access: { roles: [\"member+\"] },\n scopeKeyFrom: \"events:{eventId}\", // sugar for scopeTable + scopeField\n emitFromActions: true, // scoped-db writes auto-emit after commit\n}\n```\n\nWrites to the table through the scoped `db` inside record-bound and bulk\nactions emit frames byte-compatible with auto-CRUD (same envelope, masking,\naudience), after commit, best-effort. For projections, standalone actions, or\ncross-feature targets, declare an action-level `emit:` to get a pre-bound\n`emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in\nthe [realtime docs](/stack/realtime/durable-objects).\n\n## Refs (scoped foreign-key inputs)\n\nThe most common action preamble — load an input id, 404 if missing, assert it\nbelongs to the caller's event/org — becomes declarative:\n\n```typescript\nexport default defineAction({\n input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),\n refs: {\n agendaItemId: { table: \"agendaItems\", as: \"agendaItem\",\n matchScope: \"event\", // row.eventId === ctx.event.id\n notFound: { code: \"ITEM_NOT_FOUND\" } }, // status defaults to 404\n guestId: { table: \"guests\", as: \"guest\",\n matchWith: { ref: \"agendaItem\", on: \"eventId\" }, // cross-input parenthood\n mismatch: { code: \"EVENT_MISMATCH\", status: 400 } },\n locationId: { table: \"locations\", as: \"location\", optional: true, matchScope: \"event\" },\n },\n execute: async ({ input, agendaItem, guest, location }) => { /* … */ },\n});\n```\n\n- Loads run **through the scoped db** before `execute` — the org firewall and\n soft-delete filter apply by construction, so a cross-org id 404s with zero\n hand-written tenancy checks. All loads batch into one `Promise.all`.\n- `matchScope: \"<scope>\"` asserts `row.<scope>Id === ctx.<scope>.id` and\n fail-closes (500) if the scope object isn't hydrated. The explicit form\n `{ column, equals: \"ctx.activeOrgId\" }` is also accepted.\n- `matchWith` compares a column against an earlier-declared ref — declaration\n order defines resolution order; forward references are compile errors.\n- Ref keys must exist on the inline `z.object` input with agreeing\n optionality; `as` names can't shadow reserved context keys. Injected rows\n are the **unmasked** DB rows (masking remains a read-projection concern).\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
87
87
  },
88
88
  "compiler/definitions/arrows": {
89
89
  "title": "Arrows",
@@ -151,7 +151,7 @@ export const DOCS = {
151
151
  },
152
152
  "compiler/definitions/schema": {
153
153
  "title": "Database Schema",
154
- "content": "There is **one way to write a feature**: `feature()` — one file, one export, the table and its security contract in a single call. See [feature()](/compiler/definitions/feature) for the full reference.\n\nTwo lower-level forms exist for specific situations, not as alternatives to choose between — both compile to exactly the same runtime, and `feature()` itself is sugar over the first:\n\n- **`q.table()` + `defineTable()`** — the two-export form `feature()` expands into. Reach for it only when another file needs to import the table identifier directly (e.g. an action file referencing the table before the default export).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop for bringing an existing Drizzle schema forward, or for dialect-specific column options.\n\nIf you're starting fresh — or you're an agent defining a user's features — use `feature()` for every table.\n\n## feature() — the one-call form (default)\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // \"draft\" | \"open\" | \"closed\"\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n },\n // firewall block omitted — q.scope('organization') triggers auto-derivation\n // of [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'deletedAt', isNull: true }].\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the expanded form\n\nThis is what `feature()` compiles into. Write it by hand only when another file needs the table identifier as a named export.\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n});\n\nexport default defineTable(jobs, {\n guards: { /* ... */ },\n read: { /* ... */ },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/compiler/definitions/changesets) on the root to generate the atomic aggregate write path.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |\n| `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |\n\n`q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.\n\nFor `generateId: \"cuid\"`, there is one important nuance: import-capable runtime\npaths can emit real `createId()` usage, but compiler-managed schema\nauto-injection may keep the same `createId()` call site and back it with a\nfile-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not\ndepend on project `node_modules`.\n\n### q.scope() — tenant scope columns\n\n`q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:\n\n1. **Auto-derive the firewall predicate** — `q.scope('organization')` produces `[{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` so you can omit the explicit `firewall:` block. (If `deletedAt` is present — and it is whenever the resource uses soft delete, which is the default — the `isNull(deletedAt)` predicate is appended automatically.)\n2. **Reject the column from client input** — scope fields land in `GUARDS_CONFIG.systemManaged` alongside the audit fields, so `POST { organizationId: 'org_other' }` returns 400 even if guards aren't otherwise configured.\n3. **Auto-populate on create / upsert** — the value is taken from the request context, not the request body.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nOverride the context source for non-default sources:\n\n```typescript\nownerId: q.scope('owner', { source: 'ctx.userId' }),\n```\n\n`q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.\n\n### q.stamp() — proven-principal identity columns\n\n`q.stamp({ fromScope, claim })` server-stamps a column from a **proven** scope claim — the caller's own identity within a relationship they were cryptographically proven to hold (e.g. an event attendee's own guest id). It is the identity sibling of `q.scope`:\n\n| | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |\n|---|---|---|\n| **Purpose** | tenant isolation column | proven-principal **identity** column |\n| **Value** | `ctx.scope.<kind>.id` / `activeOrgId` / `userId` | `ctx.scope.<kind>.<claim>` (`id` \\| `subjectId` \\| a scalar sub-key) |\n| **Firewall arm?** | **yes** — it is the tenant `WHERE` | **never** — identity is not a tenant scope |\n| **Guarantee** | \"stamp **and verify**\" (firewall re-checks on read/patch/delete) | \"stamp **and prove**\" (un-spoofable by token provenance) |\n\n```typescript\ncolumns: {\n eventId: q.scope('event'), // tenant firewall column\n authorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }), // proven identity — un-spoofable\n}\n```\n\n**Runtime precedence — the org/admin hierarchy takes priority.** The stamp fires **only when the caller is admitted as a scope-only principal** (a scope-token holder, `ctx.scopePrincipal === true`): the column is force-stamped from the proven claim and any client-sent value is ignored. A caller admitted via the **org role hierarchy** (member / admin / owner) writes the column through the **org path** — a normal client-settable value, bounded by the org firewall (this is legitimate org-admin capability over their own org's rows). So a table whose `create` admits *both* org roles and a scope role needs **no split**: each identity writes the column the way its principal allows. The invariant that always holds is that a scope-only principal can never set a scope-stamped column to anything but its proven token.\n\n**Fail-closed.** If a scope-only caller reaches the write without the required claim (`ctx.scope.<kind>.<claim>` absent) the write is refused with **403** *before* the insert — never a `NULL` identity row — for nullable stamp columns too. A `q.stamp` column may not also be a firewall arm, live on an `exception: true` table, or be sourced from a set-valued sub-key; each is a compile error.\n\n`optional: true` makes the DDL column nullable (an org caller may then omit it); it does **not** relax the scope-principal 403.\n\n**Set-on-insert, immutable thereafter.** A `q.stamp` column is a **create-time identity** — it is never re-derived on update. On every update-shaped write (`PATCH`, `PUT`, batch update, upsert, and a changeset root/child patch) the column is **systemManaged**: a client value for it is **rejected** (400), regardless of your `guards.updatable` list. Re-keying a proven identity is not an operation. (The force-stamp and the org-writable-on-create allowance apply to the create path only.)\n\n**A non-nullable stamp on the org path must be supplied by the caller.** The force-stamp fires for scope-only principals; an org-admitted caller writes the column as normal client input. So a `NOT NULL` `q.stamp` column (the default) that an org caller *omits* lands on the database `NOT NULL` constraint (a deterministic field-named 400), not a NULL row. Add the column to `guards.createable` so org callers can supply it, or mark it `optional: true` if an org-created row may legitimately have no identity.\n\n**The scope-only lane needs a scope-reachable write.** The force-stamp only runs once the scope-only principal actually *reaches* the insert. A table with a **hard organization firewall arm** (an `organizationId` sourced from `ctx.activeOrgId`) emits an `ORG_REQUIRED` gate that denies a sessionless scope principal (who has no active org) *before* the stamp — so on such tables the stamp serves the **org-admitted** caller, and the scope-only principal writes these rows as a **changeset child** that *inherits* `organizationId` from a firewall-verified parent. For a plain create/batch by a scope-only principal, firewall the table on the **scope** arm only (e.g. `firewall: { any: [{ field: 'eventId', equals: 'ctx.scope.event' }] }`, no org column) so no `ORG_REQUIRED` gate is emitted.\n\n**Idempotency (at-least-once).** The stamp rides inside the write, so it inherits the endpoint's replay semantics: a **keyed** replay (a repeated `Idempotency-Key` whose handler is skipped) neither re-writes nor re-stamps; a **keyless** retry re-writes and therefore re-stamps from the caller's then-current proven claim.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'cloudflare-d1',\n config: {\n namingConvention: 'camelCase', // keep JS-style names in the SQL\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'\n```\n\n## Drizzle interop\n\nIf you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\nWhen using Drizzle (rather than `q.scope()`), declare the firewall as a predicate array. Auto-detection still works on column names (`organizationId`, `ownerId`, `teamId`) so you can omit `firewall:` entirely if exactly one isolation column is present.\n\n### When Drizzle interop is the right call\n\nDefault to `feature()`. Drop to Drizzle only when:\n\n- You already have Drizzle schemas to bring forward\n- You need a Drizzle-specific column option not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types)\n\nFeatures in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.\n\nOne dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (Neon, Supabase), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get resource routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with generated API routes\n- **`defineResource`** — Deprecated and scheduled for removal. Still compiles with a warning; do not write new code with it — migrate to `feature()` (or `defineTable`).\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all generated routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export. Add a `// @quickback-internal` marker so the compiler skips the \"no defineTable found\" warning:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// @quickback-internal — child table, no routes intentionally.\n\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Scope junction tables for cascade soft-deletes\n});\n\n// No default export = no routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration. Without the `@quickback-internal` marker the compiler emits a warning per table, since the missing `defineTable` is more often a bug than a deliberate choice.\n\nThe compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set on insert |\n| `createdBy` | text | Actor that performed the insert (`ctx.userId`) |\n| `modifiedAt` | timestamp | Set on every insert and update |\n| `modifiedBy` | text | Actor that performed the latest insert/update (`ctx.userId`) |\n\nAudit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`) — they're always present, regardless of delete mode. See [Soft-Delete Fields](#soft-delete-fields) below.\n\nOpt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)\n\n### How auto-injection works (two layers)\n\n\"Auto-injection\" covers two distinct steps. Conflating them is the most common source of confusion:\n\n1. **Schema injection (compile-time)** — the compiler adds the four columns to every Drizzle table. Idempotent: if you've authored a column with the same name yourself, the compiler leaves yours alone.\n2. **Runtime injection (per-write)** — a Proxy around the request-context `db` (`createAuditDb`, generated to `src/lib/audit-wrapper.ts`) intercepts `.insert(...).values(...)` and `.update(...).set(...)` and writes the audit columns from `ctx.userId` and the actual write moment.\n\nThe runtime layer **hard-stamps** every audit field on every write. Caller-supplied values for `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` are silently overwritten. This is intentional: the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.\n\n```ts\n// In a custom action handler — caller cannot fake audit attribution\nawait db.insert(records).values({\n id: createId(),\n status: 'active',\n createdBy: 'admin', // ← ignored; wrapper writes ctx.userId\n modifiedAt: '1999-01-01', // ← ignored; wrapper writes \"now\"\n});\n```\n\nWhat the caller is responsible for: `id` (the framework doesn't mint ids for you) and the domain fields.\n\nWhat the caller does *not* need to set: any of the four audit fields, ever.\n\n### Actors: who shows up in `createdBy` / `modifiedBy`\n\nThe wrapper writes whatever string is in `ctx.userId`. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.\n\n**Inherit before you mint.** If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.\n\nWhen you do mint, use a single namespace and a stable convention:\n\n| Boundary | Actor id |\n|----------|----------|\n| Inbound webhook | `system:webhook-<provider>` (e.g. `system:webhook-stripe`) |\n| Scheduled / cron | `system:cron-<job>` (e.g. `system:cron-cleanup-stale`) |\n| Queue worker | `system:queue-<queue>` (e.g. `system:queue-embeddings-retry`) |\n| Quickback platform-internal write with no user upstream | `system:quickback` |\n| Out-of-band operator script | `system:script-<name>` |\n\nThe `system:` prefix marks \"not a real user\" — readable by anyone joining the audit columns to `users`, and cheap to filter on. Don't use `tenant:admin` or `quickback:admin`: those imply a human role nobody is actually playing. The tenant context is already on the row (in `organizationId`); the actor id is purely about *source*.\n\n### Failure mode: missing `ctx.userId`\n\nIf a write reaches the wrapper without a `ctx.userId`, the wrapper throws:\n\n```\naudit-wrapper: insert reached without ctx.userId.\nIf this is an intentional system-side write, use the unwrapped db directly.\n```\n\nTwo paths to fix it, depending on intent:\n\n- **Mint a synthetic actor** (preferred — preserves attribution) — populate `ctx.userId` with one of the conventions above before calling into your handler.\n- **Bypass the wrapper entirely** — use the unwrapped `createDb` instead of the request-context `db`. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. The audit columns will fall back to DB defaults (`createdAt`/`modifiedAt` populate from `defaultNow()`; `createdBy`/`modifiedBy` end up `NULL`).\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\nThis turns off both layers — schema injection and the runtime wrapper.\n\n## Soft-Delete Fields\n\n`deletedAt` and `deletedBy` are **not** audit fields. They're a separate, per-table mechanism for soft delete:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `deletedAt` | timestamp | Set when the record is soft-deleted |\n| `deletedBy` | text | Actor that performed the soft delete (`ctx.userId`) |\n\nThe compiler injects them only when the resource uses soft delete — i.e. when neither `delete.mode` nor `delete.batch.mode` is explicitly `'hard'`. Soft is the default, so most tables get the columns. Tables with both delete paths set to `'hard'` skip them entirely, which also drops the `isNull(deletedAt)` predicate from the firewall WHERE clause.\n\n```typescript\n// soft delete (default) — table gets deletedAt + deletedBy\ndelete: {}\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ndelete: { mode: 'hard', batch: { mode: 'hard' } }\n```\n\n### Caller contract\n\nIn custom-action handlers, **passing `deletedAt` in `.set({})` is the signal** that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both `deletedAt` and `deletedBy` with `now` and `ctx.userId`:\n\n```ts\nawait db.update(records)\n .set({ deletedAt: new Date() }) // signal — value is overwritten\n .where(eq(records.id, id));\n```\n\nYou don't set `deletedBy` yourself; the wrapper pairs it with the `deletedAt` signal.\n\n### Protected system fields\n\nThe audit and soft-delete columns are always protected from client input, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy` *(audit — always present)*\n- `modifiedAt`, `modifiedBy` *(audit — always present)*\n- `deletedAt`, `deletedBy` *(soft-delete — present when delete mode allows soft)*\n\nProtection is enforced by the runtime wrapper — even if a request body passes one of these, it gets overwritten before the SQL is built.\n\n## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\n\n## Ownership Fields\n\nFor the firewall to work, declare a tenant-scope column. With `q.scope()` (recommended), the compiler auto-derives the firewall predicate, marks the column as system-managed, and auto-populates it on create:\n\n```typescript\n// q DSL (recommended)\norganizationId: q.scope('organization') // → ctx.activeOrgId\nownerId: q.scope('owner') // → ctx.userId\nteamId: q.scope('team') // → ctx.activeTeamId\n```\n\nWhen using Drizzle directly, declare a regular column. Auto-detection picks it up by name; `q.scope()` semantics (systemManaged, auto-populate) still apply because they're keyed off the firewall predicate, not the column DSL:\n\n```typescript\n// Drizzle interop\norganizationId: text('organization_id').notNull()\nownerId: text('owner_id').notNull()\nteamId: text('team_id').notNull()\n```\n\nThose three are **tenant** auto-stamps (org / owner / team). To auto-stamp a **proven-principal identity** column instead — the caller's own id within a relationship, not a tenant key — use [`q.stamp()`](#qstamp--proven-principal-identity-columns). It sources from `ctx.scope.<kind>.<claim>` for scope-only principals and, unlike the tenant stamps, is never a firewall arm.\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n read: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: [{ exception: true }],\n read: { access: { roles: [\"PUBLIC\"] } },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\nDrizzle `relations(...)` describe application-side joins; they do not always\ncreate a database foreign-key constraint. On Neon, use\n[`compiler.migrations.foreignKeys`](/compiler/config#neon-foreign-key-migrations)\nfor fully qualified cross-schema or composite constraints that cannot be\ndeclared alongside a table. The ordered source and target column tuples must\nhave equal arity, and the referenced target tuple must have a matching unique\nor primary-key constraint before the foreign key migration runs.\n\nUse these constraints for relational integrity only. Authorization, pass\nconsumption, state transitions, and other business logic belong in the API\naction layer.\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (Cloudflare D1)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for read and write operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
154
+ "content": "There is **one way to write a feature**: `feature()` — one file, one export, the table and its security contract in a single call. See [feature()](/compiler/definitions/feature) for the full reference.\n\nTwo lower-level forms exist for specific situations, not as alternatives to choose between — both compile to exactly the same runtime, and `feature()` itself is sugar over the first:\n\n- **`q.table()` + `defineTable()`** — the two-export form `feature()` expands into. Reach for it only when another file needs to import the table identifier directly (e.g. an action file referencing the table before the default export).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop for bringing an existing Drizzle schema forward, or for dialect-specific column options.\n\nIf you're starting fresh — or you're an agent defining a user's features — use `feature()` for every table.\n\n## feature() — the one-call form (default)\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // \"draft\" | \"open\" | \"closed\"\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n },\n // firewall block omitted — q.scope('organization') triggers auto-derivation\n // of [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'deletedAt', isNull: true }].\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the expanded form\n\nThis is what `feature()` compiles into. Write it by hand only when another file needs the table identifier as a named export.\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n});\n\nexport default defineTable(jobs, {\n guards: { /* ... */ },\n read: { /* ... */ },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/compiler/definitions/changesets) on the root to generate the atomic aggregate write path.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |\n| `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |\n\n`q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.\n\nFor `generateId: \"cuid\"`, there is one important nuance: import-capable runtime\npaths can emit real `createId()` usage, but compiler-managed schema\nauto-injection may keep the same `createId()` call site and back it with a\nfile-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not\ndepend on project `node_modules`.\n\n### q.scope() — tenant scope columns\n\n`q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:\n\n1. **Auto-derive the firewall predicate** — `q.scope('organization')` produces `[{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` so you can omit the explicit `firewall:` block. (If `deletedAt` is present — and it is whenever the resource uses soft delete, which is the default — the `isNull(deletedAt)` predicate is appended automatically.)\n2. **Reject the column from client input** — scope fields land in `GUARDS_CONFIG.systemManaged` alongside the audit fields, so `POST { organizationId: 'org_other' }` returns 400 even if guards aren't otherwise configured.\n3. **Auto-populate on create / upsert** — the value is taken from the request context, not the request body.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nOverride the context source for non-default sources:\n\n```typescript\nownerId: q.scope('owner', { source: 'ctx.userId' }),\n```\n\n`q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.\n\n### q.stamp() — proven-principal identity columns\n\n`q.stamp({ fromScope, claim })` server-stamps a column from a **proven** scope claim — the caller's own identity within a relationship they were cryptographically proven to hold (e.g. an event attendee's own guest id). It is the identity sibling of `q.scope`:\n\n| | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |\n|---|---|---|\n| **Purpose** | tenant isolation column | proven-principal **identity** column |\n| **Value** | `ctx.scope.<kind>.id` / `activeOrgId` / `userId` | `ctx.scope.<kind>.<claim>` (`id` \\| `subjectId` \\| a scalar sub-key) |\n| **Firewall arm?** | **yes** — it is the tenant `WHERE` | **never** — identity is not a tenant scope |\n| **Guarantee** | \"stamp **and verify**\" (firewall re-checks on read/patch/delete) | \"stamp **and prove**\" (un-spoofable by token provenance) |\n\n```typescript\ncolumns: {\n eventId: q.scope('event'), // tenant firewall column\n authorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }), // proven identity — un-spoofable\n}\n```\n\n**Runtime precedence — the org/admin hierarchy takes priority.** The stamp fires **only when the caller is admitted as a scope-only principal** (a scope-token holder, `ctx.scopePrincipal === true`): the column is force-stamped from the proven claim and any client-sent value is ignored. A caller admitted via the **org role hierarchy** (member / admin / owner) writes the column through the **org path** — a normal client-settable value, bounded by the org firewall (this is legitimate org-admin capability over their own org's rows). So a table whose `create` admits *both* org roles and a scope role needs **no split**: each identity writes the column the way its principal allows. The invariant that always holds is that a scope-only principal can never set a scope-stamped column to anything but its proven token.\n\n**Fail-closed.** If a scope-only caller reaches the write without the required claim (`ctx.scope.<kind>.<claim>` absent) the write is refused with **403** *before* the insert — never a `NULL` identity row — for nullable stamp columns too. A `q.stamp` column may not also be a firewall arm, live on an `exception: true` table, or be sourced from a set-valued sub-key; each is a compile error.\n\n`optional: true` makes the DDL column nullable (an org caller may then omit it); it does **not** relax the scope-principal 403.\n\n**Set-on-insert, immutable thereafter.** A `q.stamp` column is a **create-time identity** — it is never re-derived on update. On every update-shaped write (`PATCH`, `PUT`, batch update, upsert, and a changeset root/child patch) the column is **systemManaged**: a client value for it is **rejected** (400), regardless of your `guards.updatable` list. Re-keying a proven identity is not an operation. (The force-stamp and the org-writable-on-create allowance apply to the create path only.)\n\n**A non-nullable stamp on the org path must be supplied by the caller.** The force-stamp fires for scope-only principals; an org-admitted caller writes the column as normal client input. So a `NOT NULL` `q.stamp` column (the default) that an org caller *omits* lands on the database `NOT NULL` constraint (a deterministic field-named 400), not a NULL row. Add the column to `guards.createable` so org callers can supply it, or mark it `optional: true` if an org-created row may legitimately have no identity.\n\n**The scope-only lane needs a scope-reachable write.** The force-stamp only runs once the scope-only principal actually *reaches* the insert. A table with a **hard organization firewall arm** (an `organizationId` sourced from `ctx.activeOrgId`) emits an `ORG_REQUIRED` gate that denies a sessionless scope principal (who has no active org) *before* the stamp — so on such tables the stamp serves the **org-admitted** caller, and the scope-only principal writes these rows as a **changeset child** that *inherits* `organizationId` from a firewall-verified parent. For a plain create/batch by a scope-only principal, firewall the table on the **scope** arm only (e.g. `firewall: { any: [{ field: 'eventId', equals: 'ctx.scope.event' }] }`, no org column) so no `ORG_REQUIRED` gate is emitted.\n\n**Idempotency (at-least-once).** The stamp rides inside the write, so it inherits the endpoint's replay semantics: a **keyed** replay (a repeated `Idempotency-Key` whose handler is skipped) neither re-writes nor re-stamps; a **keyless** retry re-writes and therefore re-stamps from the caller's then-current proven claim.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'cloudflare-d1',\n config: {\n namingConvention: 'camelCase', // keep JS-style names in the SQL\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'\n```\n\n## Drizzle interop\n\nIf you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\nWhen using Drizzle (rather than `q.scope()`), declare the firewall as a predicate array. Auto-detection still works on column names (`organizationId`, `ownerId`, `teamId`) so you can omit `firewall:` entirely if exactly one isolation column is present.\n\n### When Drizzle interop is the right call\n\nDefault to `feature()`. Drop to Drizzle only when:\n\n- You already have Drizzle schemas to bring forward\n- You need a Drizzle-specific column option not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types)\n\nFeatures in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.\n\nOne dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (Neon, Supabase), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get resource routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with generated API routes\n- **`defineResource`** — Deprecated and scheduled for removal. Still compiles with a warning; do not write new code with it — migrate to `feature()` (or `defineTable`).\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all generated routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export. Add a `// @quickback-internal` marker so the compiler skips the \"no defineTable found\" warning:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// @quickback-internal — child table, no routes intentionally.\n\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Scope junction tables for cascade soft-deletes\n});\n\n// No default export = no routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration. Without the `@quickback-internal` marker the compiler emits a warning per table, since the missing `defineTable` is more often a bug than a deliberate choice.\n\nThe compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback maintains four audit columns on **every table** (including child/junction tables without `defineTable`):\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set on insert |\n| `createdBy` | text | Actor that performed the insert (`ctx.userId`) |\n| `modifiedAt` | timestamp | Set on every insert and update |\n| `modifiedBy` | text | Actor that performed the latest insert/update (`ctx.userId`) |\n\nAudit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`) — they're always present, regardless of delete mode. See [Soft-Delete Fields](#soft-delete-fields) below.\n\nOpt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)\n\n### Declaring them visibly — `...q.audit()` / `...q.softDelete()`\n\nHistorically these columns were invisible: injected into the *generated* schema only, so the table object in your editor didn't have them. They are now declared **visibly** (required by default — see below) so `$infer`, your editor, and the emitted schema all agree:\n\n```ts\nexport default feature(\"candidates\", {\n columns: {\n id: q.id(),\n name: q.text({ maxLength: 200 }).required(),\n organizationId: q.scope(\"organization\"),\n ...q.audit(), // createdAt / modifiedAt / createdBy / modifiedBy\n ...q.softDelete(), // deletedAt / deletedBy — matches crud.delete.mode\n },\n})\n```\n\nThe spreads are **declarative, not definitional**: the compiler expands them to the exact canonical column lines it would otherwise inject, so emitted output is identical either way. Raw Drizzle tables declare the canonical column lines literally instead (under a `── quickback:audit (compiler-managed) ──` marker). Run **`quickback migrate visible-columns`** to add either form across an existing project in one shot.\n\nTwo rules keep this safe:\n\n- **The compiler validates managed columns against canon — on by default.** A `createdAt` missing its default chain, a `.notNull()` `createdBy`, a defaulted `deletedAt`, a renamed SQL name — each breaks a security pillar (audit integrity, ownership predicates, the Firewall's soft-delete ridge, name-keyed guards/RLS), so divergence is a **compile error**, and every feature table must declare the audit quartet visibly (soft-delete pair iff the resource soft-deletes). Never silently normalized. `compiler.features.visibleAuditColumns: false` opts out — invisible injection returns and divergence downgrades to a warning.\n- **Unknown spreads are a compile error.** The columns object is compiled from source, so `...someSharedCols` can't be resolved — it fails the build rather than silently dropping columns.\n\nNote `$insert` types the audit keys as `never` — the wrapper hard-stamps them (below), so supplying one is a type error rather than a silently discarded value.\n\n### How auto-injection works (two layers)\n\n\"Auto-injection\" covers two distinct steps. Conflating them is the most common source of confusion:\n\n1. **Schema injection (compile-time)** — the compiler adds the four columns to every Drizzle table. Idempotent: if you've authored a column with the same name yourself, the compiler leaves yours alone.\n2. **Runtime injection (per-write)** — a Proxy around the request-context `db` (`createAuditDb`, generated to `src/lib/audit-wrapper.ts`) intercepts `.insert(...).values(...)` and `.update(...).set(...)` and writes the audit columns from `ctx.userId` and the actual write moment.\n\nThe runtime layer **hard-stamps** every audit field on every write. Caller-supplied values for `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` are silently overwritten. This is intentional: the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.\n\n```ts\n// In a custom action handler — caller cannot fake audit attribution\nawait db.insert(records).values({\n status: 'active',\n createdBy: 'admin', // ← ignored; wrapper writes ctx.userId\n modifiedAt: '1999-01-01', // ← ignored; wrapper writes \"now\"\n});\n```\n\nWhat the caller is responsible for: the domain fields. (`id` auto-fills via the column's `$defaultFn` — `q.id()` and injected ids both carry one.)\n\nWhat the caller does *not* need to set: `id`, the scope column, or any of the audit fields, ever.\n\n### Actors: who shows up in `createdBy` / `modifiedBy`\n\nThe wrapper writes whatever string is in `ctx.userId`. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.\n\n**Inherit before you mint.** If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.\n\nWhen you do mint, use a single namespace and a stable convention:\n\n| Boundary | Actor id |\n|----------|----------|\n| Inbound webhook | `system:webhook-<provider>` (e.g. `system:webhook-stripe`) |\n| Scheduled / cron | `system:cron-<job>` (e.g. `system:cron-cleanup-stale`) |\n| Queue worker | `system:queue-<queue>` (e.g. `system:queue-embeddings-retry`) |\n| Quickback platform-internal write with no user upstream | `system:quickback` |\n| Out-of-band operator script | `system:script-<name>` |\n\nThe `system:` prefix marks \"not a real user\" — readable by anyone joining the audit columns to `users`, and cheap to filter on. Don't use `tenant:admin` or `quickback:admin`: those imply a human role nobody is actually playing. The tenant context is already on the row (in `organizationId`); the actor id is purely about *source*.\n\n### Failure mode: missing `ctx.userId`\n\nIf a write reaches the wrapper without a `ctx.userId`, the wrapper throws:\n\n```\naudit-wrapper: insert reached without ctx.userId.\nIf this is an intentional system-side write, use the unwrapped db directly.\n```\n\nTwo paths to fix it, depending on intent:\n\n- **Mint a synthetic actor** (preferred — preserves attribution) — populate `ctx.userId` with one of the conventions above before calling into your handler.\n- **Bypass the wrapper entirely** — use the unwrapped `createDb` instead of the request-context `db`. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. The audit columns will fall back to DB defaults (`createdAt`/`modifiedAt` populate from `defaultNow()`; `createdBy`/`modifiedBy` end up `NULL`).\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\nThis turns off both layers — schema injection and the runtime wrapper.\n\n## Soft-Delete Fields\n\n`deletedAt` and `deletedBy` are **not** audit fields. They're a separate, per-table mechanism for soft delete:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `deletedAt` | timestamp | Set when the record is soft-deleted |\n| `deletedBy` | text | Actor that performed the soft delete (`ctx.userId`) |\n\nThe compiler injects them only when the resource uses soft delete — i.e. when neither `delete.mode` nor `delete.batch.mode` is explicitly `'hard'`. Soft is the default, so most tables get the columns. Tables with both delete paths set to `'hard'` skip them entirely, which also drops the `isNull(deletedAt)` predicate from the firewall WHERE clause.\n\n```typescript\n// soft delete (default) — table gets deletedAt + deletedBy\ndelete: {}\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ndelete: { mode: 'hard', batch: { mode: 'hard' } }\n```\n\n### Caller contract\n\nIn custom-action handlers, **passing `deletedAt` in `.set({})` is the signal** that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both `deletedAt` and `deletedBy` with `now` and `ctx.userId`:\n\n```ts\nawait db.update(records)\n .set({ deletedAt: new Date() }) // signal — value is overwritten\n .where(eq(records.id, id));\n```\n\nYou don't set `deletedBy` yourself; the wrapper pairs it with the `deletedAt` signal.\n\n### Protected system fields\n\nThe audit and soft-delete columns are always protected from client input, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy` *(audit — always present)*\n- `modifiedAt`, `modifiedBy` *(audit — always present)*\n- `deletedAt`, `deletedBy` *(soft-delete — present when delete mode allows soft)*\n\nProtection is enforced by the runtime wrapper — even if a request body passes one of these, it gets overwritten before the SQL is built.\n\n## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\n\n## Ownership Fields\n\nFor the firewall to work, declare a tenant-scope column. With `q.scope()` (recommended), the compiler auto-derives the firewall predicate, marks the column as system-managed, and auto-populates it on create:\n\n```typescript\n// q DSL (recommended)\norganizationId: q.scope('organization') // → ctx.activeOrgId\nownerId: q.scope('owner') // → ctx.userId\nteamId: q.scope('team') // → ctx.activeTeamId\n```\n\nWhen using Drizzle directly, declare a regular column. Auto-detection picks it up by name; `q.scope()` semantics (systemManaged, auto-populate) still apply because they're keyed off the firewall predicate, not the column DSL:\n\n```typescript\n// Drizzle interop\norganizationId: text('organization_id').notNull()\nownerId: text('owner_id').notNull()\nteamId: text('team_id').notNull()\n```\n\nThose three are **tenant** auto-stamps (org / owner / team). To auto-stamp a **proven-principal identity** column instead — the caller's own id within a relationship, not a tenant key — use [`q.stamp()`](#qstamp--proven-principal-identity-columns). It sources from `ctx.scope.<kind>.<claim>` for scope-only principals and, unlike the tenant stamps, is never a firewall arm.\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n read: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: [{ exception: true }],\n read: { access: { roles: [\"PUBLIC\"] } },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\nDrizzle `relations(...)` describe application-side joins; they do not always\ncreate a database foreign-key constraint. On Neon, use\n[`compiler.migrations.foreignKeys`](/compiler/config#neon-foreign-key-migrations)\nfor fully qualified cross-schema or composite constraints that cannot be\ndeclared alongside a table. The ordered source and target column tuples must\nhave equal arity, and the referenced target tuple must have a matching unique\nor primary-key constraint before the foreign key migration runs.\n\nUse these constraints for relational integrity only. Authorization, pass\nconsumption, state transitions, and other business logic belong in the API\naction layer.\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (Cloudflare D1)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for read and write operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
155
155
  },
156
156
  "compiler/definitions/scopes": {
157
157
  "title": "Scopes & Capability Grants",
@@ -159,7 +159,7 @@ export const DOCS = {
159
159
  },
160
160
  "compiler/definitions/sealed-protocol": {
161
161
  "title": "Sealed protocol (qbseal:1)",
162
- "content": "This is the **protocol reference** for the [SEALED tier](/compiler/definitions/encryption#sealed-tier--end-to-end-encryption) — the on-the-wire contract a client speaks to the generated `/seal/v1` surface. Quickback ships first-party clients — TypeScript (emitted into your project), **Swift, and Kotlin** — so you usually don't implement this yourself; jump to [Client SDKs](#client-sdks). The format is also **language-agnostic and versioned**, so you can build a Go or server-side client against this spec and the [conformance vectors](#conformance-vectors) instead of reading emitted source.\n\n## Key model\n\nThree nested keys; a breach of any layer above plaintext yields only more wrapped keys.\n\n```\nUSER key ──unwrap──▶ SCOPE private key ──unwrap──▶ content key ──decrypt──▶ plaintext\n```\n\n| Key | Lives | Derivation |\n|---|---|---|\n| **USER** | client only | `Argon2id(vault passphrase, salt)` → HKDF-split into an Ed25519 signing key + an X25519 wrap key. **Never** the login password. |\n| **SCOPE** | private half wrapped per-user; public half on the server | random X25519 keypair, one per scope (per org). |\n| **Content (CK)** | wrapped to the scope | random AES-256-GCM key, one per sealed value. |\n\nA **writer** needs only the scope *public* key. A **reader** needs a grant of the scope private key, wrapped to their USER key.\n\n## Crypto primitives\n\nAll standard; no hand-rolled constructions. A conforming port maps each to its platform library (CryptoKit, BouncyCastle, WebCrypto, …).\n\n| Purpose | Primitive | Parameters |\n|---|---|---|\n| USER-key KDF | **Argon2id** | floor below; output 32 bytes |\n| KDF domain split | **HKDF-SHA256** | `info = \"qbseal-ed25519-v1\"` and `\"qbseal-x25519-v1\"`, no salt, L=32 |\n| Signing key | **Ed25519** | seed = HKDF ed25519 output |\n| Wrap key | **X25519** | seed = HKDF x25519 output |\n| Step-up proof | **Ed25519** sign/verify | over the [step-up message](#step-up-message) |\n| Sealed box (wrap a key to a pubkey) | **X25519 ECDH → HKDF-SHA256 → AES-256-GCM** | see below |\n| Content / key encryption | **AES-256-GCM** | 12-byte IV, 16-byte tag appended to ciphertext |\n\n### Argon2id floor\n\nThe server **rejects** enrollment params below this floor (a weak-KDF verifier is offline-brute-forceable, and the public key is stored). These are the OWASP Argon2id minimums:\n\n```json\n{ \"memoryKiB\": 19456, \"iterations\": 2, \"parallelism\": 1 }\n```\n\nA client MAY choose stronger params; it MUST send the params it used (the server re-derives nothing — it only verifies the Ed25519 proof and stores the params for the client to re-derive at reveal time).\n\n### Sealed box\n\nWrapping a key (a content key, or a scope private key) to an X25519 public key — the analogue of libsodium's `crypto_box_seal`:\n\n1. Generate an ephemeral X25519 keypair `eph`.\n2. `shared = X25519(eph.secret, recipientPub)`.\n3. `wrapKey = HKDF-SHA256(ikm = shared, salt = eph.pub ‖ recipientPub, info = \"qbseal-box-v1\", L = 32)`.\n4. `ct = AES-256-GCM(wrapKey, iv, plaintext)`.\n5. Envelope: `{ alg: \"x25519-aesgcm\", eph, iv, ct }` (all base64url).\n\nTo open: recompute `shared = X25519(recipientSecret, eph.pub)`, re-derive `wrapKey` (salt uses the same `eph.pub ‖ recipientPub`), AES-GCM-decrypt.\n\n### Step-up message\n\nThe message an Ed25519 step-up proof signs. Each field is **independently SHA-256-hashed then joined** — fixed-width, delimiter-free, so the `scope:<kind>:<id>` colons in `scopeRef` can't be re-segmented to forge a proof for a different target:\n\n```\nmessage = utf8(\n \"qbseal-stepup:v1:\" +\n b64url(sha256(utf8(scopeRef))) + \":\" +\n b64url(sha256(utf8(vaultItemId))) + \":\" +\n b64url(sha256(utf8(nonce)))\n)\n```\n\nThe `nonce` is the server-issued [challenge](#3-challenge). The proof is `Ed25519.sign(message, userEd25519Secret)`, sent base64url.\n\n## Envelope wire format\n\nEvery sealed blob is `qbseal:<version>:<base64url(json)>`. Three payload shapes:\n\n```jsonc\n// a key wrapped to an X25519 public key\n{ \"alg\": \"x25519-aesgcm\", \"eph\": \"<b64url>\", \"iv\": \"<b64url>\", \"ct\": \"<b64url>\" }\n\n// content encrypted under a content key\n{ \"alg\": \"aes-256-gcm\", \"iv\": \"<b64url>\", \"ct\": \"<b64url>\" }\n\n// a SEALED CELL — the compound value written into a .sealed() column.\n// The server STRUCTURALLY SPLITS this (decode only, never decrypts) into\n// vault_items.ct (content) + wrapped_ck_owner (wrappedCk).\n{ \"alg\": \"sealed-cell\",\n \"content\": { \"alg\": \"aes-256-gcm\", ... },\n \"wrappedCk\": { \"alg\": \"x25519-aesgcm\", ... } }\n```\n\nThe decoder rejects a non-`qbseal:` string, an unknown version, an envelope over 64 KiB, or a malformed body — all fail-closed.\n\n## The `/seal/v1` lifecycle\n\nAll routes are `POST`, JSON in/out, mounted at `/seal/v1`, and require an authenticated session with an **active organization** (`requireOrg` → 401/403). Errors use the standard Quickback error envelope. Most write routes accept `\"dryRun\": true` to validate + preview without persisting.\n\n`scopeRef` grammar is `scope:<kind>:<id>` (org/event/relationship) or `user:<id>`; the server validates it (`assertRefGrammar`).\n\n### Key-admin authorization (who may enroll / grant / rotate / revoke)\n\n`enroll`, `grant`, `rotate`, and `revoke` are gated by **`hasKeyAdminForScope`**:\n\n- `userRole === \"sysadmin\"` always passes; **or**\n- a verified `ctx.scope.seal` claim **for the exact `scopeRef`** carrying a key-admin-tier scoped role (configurable via `encryption.seal.keyAdminRoles`; the literal `\"key-admin\"` scoped role always qualifies).\n\nScoped roles live **only** on `ctx.scope.seal`, never `ctx.roles` — a forged `ctx.roles` entry can't satisfy the gate. There is **no automatic** role→grant: the server holds no key material, so it cannot wrap the scope key to a new reader itself. Instead a reader self-publishes their public key via [`/grant-request`](#10-grant-request) and a key-admin fulfils it via [`/grant`](#5-grant) — see [role→grant](#rolegrant-readers-request-key-admins-fulfil). Minting the key-admin scope claim is done through the normal [scopes](/compiler/definitions/scopes) machinery — that policy (which role becomes key-admin for which scope) is yours to declare.\n\n---\n\n### 1. `/scope-key` — get a scope's public key (writers)\n\nAny tenant member who can write the scope needs it. Returns the **current** (highest `keyVersion`) public key.\n\n```jsonc\n// → { scopeRef }\n// ← { scopeRef, publicKey: \"<b64url X25519>\", keyVersion: 1 }\n```\n404 (existence-oracle parity) if the scope is unknown *or* has no key yet.\n\n### 2. `/enroll` — create a scope's seal key (key-admin)\n\nTrust-on-first-use: **first write wins**, never overwrites. Persists `seal_keys` (the scope public key). `organizationId` is stamped server-side.\n\n```jsonc\n// → { scopeRef, publicKey: \"<b64url X25519>\" } // client generated the keypair\n// ← { enrolled: true, scopeRef, keyVersion: 1 }\n```\n409 if a key already exists for the scope (use `/rotate`).\n\n### 3. `/challenge` — issue a step-up nonce (any member)\n\nA single-use, **(issuing-user, scopeRef, vaultItemId)-bound** nonce, stored in KV (`expirationTtl` **120 s**). Bound to the item's owning scopeRef so it can only answer a reveal for *that* item; bound to the issuing user so another user can't burn it.\n\n```jsonc\n// → { vaultItemId }\n// ← { nonce: \"<b64url 32B>\", scopeRef, vaultItemId, expiresIn: 120 }\n```\n503 fail-closed if no KV binding (sealed deployments require it).\n\n### 4. `/reveal` — prove step-up, mint a reveal token (reader)\n\nVerifies the step-up proof, writes a **committed** append-only reveal-log row, then mints a short-lived capability. The proof is consumed (single-use); the token is **not** the key.\n\n```jsonc\n// → { vaultItemId, fieldRef?, stepUp: <StepUpProof> }\n// ← { revealToken: \"<JWT ≤180s>\", scope, vaultItemId, expiresIn: 180 }\n```\n`StepUpProof` is one of:\n```jsonc\n{ \"kind\": \"passphrase\", \"nonce\": \"<from /challenge>\",\n \"argon2\": { \"proof\": \"<b64url Ed25519 sig over the step-up message>\",\n \"memoryKiB\": 19456, \"iterations\": 2, \"parallelism\": 1 } }\n\n{ \"kind\": \"passkey\", \"nonce\": \"<from /challenge>\",\n \"assertion\": <WebAuthn AuthenticationResponseJSON> } // see Passkey step-up\n```\nGates, all fail-closed and in order: **(a)** tenant load, **(b)** any presented `ctx.scope.seal` claim must match the item's scopeRef, **(c)** structural step-up (single-use nonce, bound message), **(d)** `assertGrantLive` (D1 read — owner reveal needs no grant; otherwise a live `seal_key_grant` for the scope, or an audience `vault_grant`).\n\n### 5. `/key` — fetch the wrapped key (bearer the reveal token)\n\nThe **separate** post-mint route (never folded into `/reveal`). Re-runs three independent gates — tenant, capability (`ctx.scope.seal` only), `assertGrantLive` (D1, **prior to and independent of** any KV revocation check, which fails *open*) — writes a committed `delivered` reveal-log row, and returns the still-wrapped material.\n\n```jsonc\n// → { vaultItemId } (Authorization: Bearer <revealToken>)\n// ← { wrappedKey: \"<qbseal envelope>\", ct: \"<qbseal content envelope>\",\n// wrapMethod: \"owner\" | \"scope\" | \"audience\" }\n```\nThe client unwraps per `wrapMethod` (see [`/my-grant`](#6-my-grant)) and decrypts `ct`. **No readable key ever touches the server.**\n\n### 6. `/my-grant` — the caller's own wrapped scope private key (reader)\n\nFor `wrapMethod: \"scope\"`, the client first unwraps the scope private key with its USER key, then the CK. User-scoped; 404 if not granted.\n\n```jsonc\n// → { scopeRef }\n// ← { wrappedPrivateKey: \"<qbseal envelope>\", wrapMethod: \"scope\" }\n```\n\n### 7. `/grant` — enroll a reader + store their wrapped scope key (key-admin)\n\nThe combined **enrollment + grant** endpoint. The server **never wraps** — it persists the client-supplied opaque blob. Exactly one live grant per `(scopeRef, userId)` (it revokes any prior live grant first).\n\n```jsonc\n// → { scopeRef, userId, wrappedPrivateKey: \"<qbseal envelope>\", wrapMethod: \"scope\",\n// wrapMeta?,\n// // OPTIONAL passphrase-reveal enrollment (the step-up verifier):\n// stepUp?: { kind: \"passphrase\", publicKey: \"<b64url Ed25519>\",\n// salt: \"<b64url>\", argon2: { memoryKiB, iterations, parallelism } } }\n// ← { granted: true, scopeRef, userId, stepUpEnrolled: boolean }\n```\n`stepUp.argon2` is floor-checked **at enrollment** (a weak verifier is rejected here, not just at reveal). The `stepUpPublicKey` + params are stored zero-knowledge; the passphrase never leaves the client.\n\n### 8. `/revoke` — sever future access (key-admin)\n\nTwo forms: `{ scopeRef, userId }` (revoke a scope-key grant) or `{ vaultItemId, audienceRef }` (revoke an audience grant). Severs the future D1 key-fetch **and** kills in-flight tokens via KV revocation. It does **not** recall an already-unwrapped key — the response surfaces `rotationRecommended` when that matters.\n\n### 9. `/rotate` — add a new key version + re-grant worklist (key-admin)\n\nAppend-only `INSERT` of a new `seal_keys` version, and returns the **re-grant worklist** — the live readers and their X25519 public keys.\n\n```jsonc\n// → { scopeRef, publicKey: \"<new b64url X25519>\" } // client generated the new keypair\n// ← { rotated: true, scopeRef, keyVersion: 2,\n// regrant: [{ userId, userPublicKey }, …], // re-wrap the NEW scope key to each\n// missingPublicKey: [userId, …] } // readers granted before key capture\n```\nThe key-admin's client wraps the **new** scope private key to each `regrant[].userPublicKey` and calls [`/grant`](#5-grant) per reader (which revokes the stale grant and inserts the fresh one). The server holds no key material, so it can only hand back the wrap targets — it never re-wraps. Older `seal_keys` versions remain readable, so existing sealed values keep decrypting until re-sealed. Readers in `missingPublicKey` re-request via [`/grant-request`](#10-grant-request).\n\n### 10. `/grant-request` — request access to a scope (any member)\n\nA reader who has a role for a scope but no grant publishes their X25519 USER public key. Requesting only publishes public material + intent; **fulfilling is the key-admin-gated action**. One pending request per `(scope, user)`; a fresh request replaces the pending key.\n\n```jsonc\n// → { scopeRef, userPublicKey: \"<b64url X25519>\" }\n// ← { requested: true, scopeRef }\n```\n\n### 11. `/grant-requests` — list pending requests (key-admin)\n\n```jsonc\n// → { scopeRef }\n// ← { scopeRef, requests: [{ userId, userPublicKey, requestedAt }, …] }\n```\nThe key-admin wraps the scope key to each `userPublicKey` and calls [`/grant`](#5-grant), which **auto-resolves** the matching pending request.\n\n### 12. `/recovery/enroll` — escrow the scope key under a recovery code (key-admin)\n\nA key-admin (holding the scope private key) wraps it to a key derived from a **recovery code** and escrows the blob. The server stores only the opaque recovery-wrapped material — the recovery code, held by the client, is what makes it usable; the server can never unwrap it. One live recovery per scope key version.\n\n```jsonc\n// → { scopeRef, wrappedPrivateKey: \"<qbseal envelope, scope key wrapped to the recovery key>\" }\n// ← { enrolled: true, scopeRef, keyVersion: 1 }\n```\n\n### 13. `/recovery/use` — retrieve the recovery blob (key-admin)\n\nReturns the live recovery-wrapped scope key (and appends a `recovery` entry to the reveal log). The client unwraps it with the recovery-code key to recover the scope private key, then re-grants readers. The returned blob is **useless without the recovery code** — the server gates *who* may fetch it, the code gates whether it can be unwrapped.\n\n```jsonc\n// → { scopeRef }\n// ← { scopeRef, keyVersion, wrappedPrivateKey: \"<qbseal envelope>\" } // 404 parity if none\n```\n\n#### role→grant: readers request, key-admins fulfil\n\nBecause the server holds no key material, it cannot mint a grant when a user gains a role. The supported pattern: the reader calls `/grant-request` (publishing their public key); a key-admin lists pending requests with `/grant-requests`, wraps the scope key to each, and `/grant`s them — which auto-resolves the request. Who is allowed to *request* (the \"role\" half) is your access policy; the cryptographic *fulfilment* is always key-admin-gated.\n\n## Passkey step-up\n\nWhen the passkey plugin is enabled, `/reveal` verifies a WebAuthn assertion whose **challenge is the server nonce** (not Better Auth's login challenge). The native ceremony must produce an `AuthenticationResponseJSON` (the `@simplewebauthn/browser` `startAuthentication` shape) for these expectations:\n\n| Field | Value |\n|---|---|\n| `challenge` | the `/challenge` `nonce` **as the base64url string** (the client signs the b64url text, the server passes `expectedChallenge = nonce`) |\n| `rpID` | the passkey plugin's `rpID` — i.e. `crossSubDomainCookies.domain` (leading dot stripped) when configured, else the host of `env.ACCOUNT_URL` |\n| `userVerification` | **required** (`requireUserVerification: true` — a reveal is a deliberate re-auth) |\n| origin | the resolved account origin (mirrors the `passkey({ rpID, origin })` plugin) |\n\nThe credential is looked up in the **auth** database (`passkey` table) and the signature counter is clone-checked. Conformance for passkey is **verify-based** at the server; the client's job is to bind `challenge = nonce` exactly.\n\n## Conformance vectors\n\nCanonical vectors live at **`packages/seal-client/vectors/qbseal-v1.json`**, generated from the reference TS SDK (`bun packages/seal-client/scripts/generate-vectors.ts`) and self-validated against it (`src/vectors.test.ts`). Every input (passphrase, salt, key seeds, IVs, ephemerals) is fixed, so the file is byte-stable and each vector reproduces from its inputs alone.\n\n| Group | Pins | Determinism |\n|---|---|---|\n| `kdf` | passphrase + salt + params → Ed25519/X25519 public keys | full |\n| `stepUpMessage` | `(scopeRef, vaultItemId, nonce)` → signed message | full |\n| `stepUpSign` | a signature that **verifies** against the message + pubkey | verify-based (signing may be randomized) |\n| `aesGcm` | key + IV + plaintext → ciphertext (+tag) | full |\n| `sealedBoxOpen` | recipient secret + box → plaintext | open-direction (canonical) |\n| `reveal` | passphrase → keys; owner + scope unwrap paths → plaintext | open-direction (canonical) |\n| `envelope` | `qbseal:1:` sealed-cell decodes structurally | full |\n\nA port verifies the open-direction vectors exactly, and proves its *seal* direction by round-tripping through its own open. Vectors are the **cross-language byte-for-byte guarantee** — CI runs every client (TypeScript, Swift, and Kotlin) against this one file and fails on drift.\n\n## Client SDKs\n\nYou don't have to implement the crypto. Quickback ships first-party clients, each gated in CI against the conformance vectors above — so they agree byte-for-byte with the server and with each other.\n\n| Platform | Package | Distribution | Crypto |\n|---|---|---|---|\n| Web / Worker / Node | `@quickback-dev/seal-client` | **emitted** into your project at `src/lib/seal-client/` (for any project with a `.sealed()` column) | `@noble` + WebCrypto |\n| iOS / macOS | **`QuickbackSeal`** | SwiftPM — `apps/seal-sdk/swift` | CryptoKit + vendored Argon2 |\n| JVM / Android | **`dev.quickback.seal`** | Gradle — `apps/seal-sdk/kotlin` | BouncyCastle |\n\nAll three expose the same shape: a `SealClient` over a transport you implement on your HTTP client (URLSession / OkHttp / Ktor / fetch). The transport just POSTs to `/seal/v1/*`; the SDK does the crypto and the reveal handshake.\n\n### Swift (iOS / macOS)\n\n```swift\n// Package.swift\n.package(url: \"https://github.com/paulstenhouse/quickback-compiler.git\", branch: \"main\")\n// target dependency: .product(name: \"QuickbackSeal\", package: \"quickback-compiler\")\n```\n```swift\n\nlet seal = SealClient(transport: myTransport) // POSTs to /seal/v1/*\nlet sealed = try await seal.sealField(scopeRef: scope, // WRITE — no key needed\n plaintext: Data(\"Background check: clear\".utf8))\n\nlet session = try seal.session(passphrase: vaultPass, saltB64url: salt, argon2: .defaults)\nlet plaintext = try await seal.reveal(session: session, scopeRef: scope, vaultItemId: id)\n```\n\n### Kotlin (JVM / Android)\n\n```kotlin\n// build.gradle.kts — composite build or a published artifact from apps/seal-sdk/kotlin\n\nval seal = SealClient(myTransport)\nval sealed = seal.sealField(scope, \"Background check: clear\".toByteArray()) // WRITE\n\nval session = seal.session(vaultPass, saltB64url, Argon2Params.DEFAULTS)\nval plaintext = seal.reveal(session, scope, vaultItemId) // REVEAL\n```\n\nPasskey reveal is the same call as `revealWithPasskey(…, getAssertion)`, where `getAssertion(nonce)` runs the platform WebAuthn ceremony with `challenge = nonce`. Full details, the transport contract, and the conformance harness live in [`apps/seal-sdk/README`](https://github.com/paulstenhouse/quickback-compiler/tree/main/apps/seal-sdk). The SDKs are versioned **with** the compiler in the same repo, so the wire format never drifts from the server you're talking to.\n\n## Not yet wired\n\nHonest gaps, fail-closed until built — a client should not assume these exist:\n\n- **Content-key re-encryption on rotation** — `/rotate` versions the scope key and re-grants *readers*, and older key versions stay readable, so nothing breaks. But existing sealed *values* keep their content keys wrapped to the old scope key until a client re-seals them; there's no bulk re-encrypt-and-crypto-shred-the-old-version flow yet.\n- **Audience grants beyond reveal** — `vault_grant` audience reveals are honored at `/reveal`/`/key`, but there's no first-class management surface yet.\n\nThese will arrive as additive `:1` routes (no wire-format break) with their own vectors."
162
+ "content": "This is the **protocol reference** for the [SEALED tier](/compiler/definitions/encryption#sealed-tier--end-to-end-encryption) — the on-the-wire contract a client speaks to the generated `/seal/v1` surface. Quickback ships first-party clients — TypeScript (emitted into your project), **Swift, and Kotlin** — so you usually don't implement this yourself; jump to [Client SDKs](#client-sdks). The format is also **language-agnostic and versioned**, so you can build a Go or server-side client against this spec and the [conformance vectors](#conformance-vectors) instead of reading emitted source.\n\n## Key model\n\nThree nested keys; a breach of any layer above plaintext yields only more wrapped keys.\n\n```\nUSER key ──unwrap──▶ SCOPE private key ──unwrap──▶ content key ──decrypt──▶ plaintext\n```\n\n| Key | Lives | Derivation |\n|---|---|---|\n| **USER** | client only | `Argon2id(vault passphrase, salt)` → HKDF-split into an Ed25519 signing key + an X25519 wrap key. **Never** the login password. |\n| **SCOPE** | private half wrapped per-user; public half on the server | random X25519 keypair, one per scope (per org). |\n| **Content (CK)** | wrapped to the scope | random AES-256-GCM key, one per sealed value. |\n\nA **writer** needs only the scope *public* key. A **reader** needs a grant of the scope private key, wrapped to their USER key.\n\n## Crypto primitives\n\nAll standard; no hand-rolled constructions. A conforming port maps each to its platform library (CryptoKit, BouncyCastle, WebCrypto, …).\n\n| Purpose | Primitive | Parameters |\n|---|---|---|\n| USER-key KDF | **Argon2id** | floor below; output 32 bytes |\n| KDF domain split | **HKDF-SHA256** | `info = \"qbseal-ed25519-v1\"` and `\"qbseal-x25519-v1\"`, no salt, L=32 |\n| Signing key | **Ed25519** | seed = HKDF ed25519 output |\n| Wrap key | **X25519** | seed = HKDF x25519 output |\n| Step-up proof | **Ed25519** sign/verify | over the [step-up message](#step-up-message) |\n| Sealed box (wrap a key to a pubkey) | **X25519 ECDH → HKDF-SHA256 → AES-256-GCM** | see below |\n| Content / key encryption | **AES-256-GCM** | 12-byte IV, 16-byte tag appended to ciphertext |\n\n### Argon2id floor\n\nThe server **rejects** enrollment params below this floor (a weak-KDF verifier is offline-brute-forceable, and the public key is stored). These are the OWASP Argon2id minimums:\n\n```json\n{ \"memoryKiB\": 19456, \"iterations\": 2, \"parallelism\": 1 }\n```\n\nA client MAY choose stronger params; it MUST send the params it used (the server re-derives nothing — it only verifies the Ed25519 proof and stores the params for the client to re-derive at reveal time).\n\n### Sealed box\n\nWrapping a key (a content key, or a scope private key) to an X25519 public key — the analogue of libsodium's `crypto_box_seal`:\n\n1. Generate an ephemeral X25519 keypair `eph`.\n2. `shared = X25519(eph.secret, recipientPub)`.\n3. `wrapKey = HKDF-SHA256(ikm = shared, salt = eph.pub ‖ recipientPub, info = \"qbseal-box-v1\", L = 32)`.\n4. `ct = AES-256-GCM(wrapKey, iv, plaintext)`.\n5. Envelope: `{ alg: \"x25519-aesgcm\", eph, iv, ct }` (all base64url).\n\nTo open: recompute `shared = X25519(recipientSecret, eph.pub)`, re-derive `wrapKey` (salt uses the same `eph.pub ‖ recipientPub`), AES-GCM-decrypt.\n\n### Step-up message\n\nThe message an Ed25519 step-up proof signs. Each field is **independently SHA-256-hashed then joined** — fixed-width, delimiter-free, so the `scope:<kind>:<id>` colons in `scopeRef` can't be re-segmented to forge a proof for a different target:\n\n```\nmessage = utf8(\n \"qbseal-stepup:v1:\" +\n b64url(sha256(utf8(scopeRef))) + \":\" +\n b64url(sha256(utf8(vaultItemId))) + \":\" +\n b64url(sha256(utf8(nonce)))\n)\n```\n\nThe `nonce` is the server-issued [challenge](#3-challenge). The proof is `Ed25519.sign(message, userEd25519Secret)`, sent base64url.\n\n## Envelope wire format\n\nEvery sealed blob is `qbseal:<version>:<base64url(json)>`. Three payload shapes:\n\n```jsonc\n// a key wrapped to an X25519 public key\n{ \"alg\": \"x25519-aesgcm\", \"eph\": \"<b64url>\", \"iv\": \"<b64url>\", \"ct\": \"<b64url>\" }\n\n// content encrypted under a content key\n{ \"alg\": \"aes-256-gcm\", \"iv\": \"<b64url>\", \"ct\": \"<b64url>\" }\n\n// a SEALED CELL — the compound value written into a .sealed() column.\n// The server STRUCTURALLY SPLITS this (decode only, never decrypts) into\n// vault_items.ct (content) + wrapped_ck_owner (wrappedCk).\n{ \"alg\": \"sealed-cell\",\n \"content\": { \"alg\": \"aes-256-gcm\", ... },\n \"wrappedCk\": { \"alg\": \"x25519-aesgcm\", ... } }\n```\n\nThe decoder rejects a non-`qbseal:` string, an unknown version, an envelope over 64 KiB, or a malformed body — all fail-closed.\n\n### The `SealedValue` type brand (server-side code)\n\nA `.sealed()` / `q.vaultRef()` column is typed as an opaque **`SealedValue`**\nbrand in the generated Drizzle schema, not `string`. Any server-side code that\ntries to *use* the value as a string — `JSON.parse(row.backgroundCheck)`,\n`.length`, string interpolation — is a **TypeScript compile error**, on reads\nand on `.returning()` alike. That's the type-level face of \"the server is\nstructurally unable to read it\": at rest the column only ever holds a\n`{ __vaultRef }` marker, and the brand keeps action code from string-processing\nor hand-forwarding that marker. Sealed values leave the system exclusively\nthrough the `/seal/v1` reveal rails below. (Envelope `.encrypted()` columns are\ndeliberately *not* branded — they type as `string` because the server can\ndecrypt that tier; an action reading one gets `qbenc:` ciphertext.)\n\n## The `/seal/v1` lifecycle\n\nAll routes are `POST`, JSON in/out, mounted at `/seal/v1`, and require an authenticated session with an **active organization** (`requireOrg` → 401/403). Errors use the standard Quickback error envelope. Most write routes accept `\"dryRun\": true` to validate + preview without persisting.\n\n`scopeRef` grammar is `scope:<kind>:<id>` (org/event/relationship) or `user:<id>`; the server validates it (`assertRefGrammar`).\n\n### Key-admin authorization (who may enroll / grant / rotate / revoke)\n\n`enroll`, `grant`, `rotate`, and `revoke` are gated by **`hasKeyAdminForScope`**:\n\n- `userRole === \"sysadmin\"` always passes; **or**\n- a verified `ctx.scope.seal` claim **for the exact `scopeRef`** carrying a key-admin-tier scoped role (configurable via `encryption.seal.keyAdminRoles`; the literal `\"key-admin\"` scoped role always qualifies).\n\nScoped roles live **only** on `ctx.scope.seal`, never `ctx.roles` — a forged `ctx.roles` entry can't satisfy the gate. There is **no automatic** role→grant: the server holds no key material, so it cannot wrap the scope key to a new reader itself. Instead a reader self-publishes their public key via [`/grant-request`](#10-grant-request) and a key-admin fulfils it via [`/grant`](#5-grant) — see [role→grant](#rolegrant-readers-request-key-admins-fulfil). Minting the key-admin scope claim is done through the normal [scopes](/compiler/definitions/scopes) machinery — that policy (which role becomes key-admin for which scope) is yours to declare.\n\n---\n\n### 1. `/scope-key` — get a scope's public key (writers)\n\nAny tenant member who can write the scope needs it. Returns the **current** (highest `keyVersion`) public key.\n\n```jsonc\n// → { scopeRef }\n// ← { scopeRef, publicKey: \"<b64url X25519>\", keyVersion: 1 }\n```\n404 (existence-oracle parity) if the scope is unknown *or* has no key yet.\n\n### 2. `/enroll` — create a scope's seal key (key-admin)\n\nTrust-on-first-use: **first write wins**, never overwrites. Persists `seal_keys` (the scope public key). `organizationId` is stamped server-side.\n\n```jsonc\n// → { scopeRef, publicKey: \"<b64url X25519>\" } // client generated the keypair\n// ← { enrolled: true, scopeRef, keyVersion: 1 }\n```\n409 if a key already exists for the scope (use `/rotate`).\n\n### 3. `/challenge` — issue a step-up nonce (any member)\n\nA single-use, **(issuing-user, scopeRef, vaultItemId)-bound** nonce, stored in KV (`expirationTtl` **120 s**). Bound to the item's owning scopeRef so it can only answer a reveal for *that* item; bound to the issuing user so another user can't burn it.\n\n```jsonc\n// → { vaultItemId }\n// ← { nonce: \"<b64url 32B>\", scopeRef, vaultItemId, expiresIn: 120 }\n```\n503 fail-closed if no KV binding (sealed deployments require it).\n\n### 4. `/reveal` — prove step-up, mint a reveal token (reader)\n\nVerifies the step-up proof, writes a **committed** append-only reveal-log row, then mints a short-lived capability. The proof is consumed (single-use); the token is **not** the key.\n\n```jsonc\n// → { vaultItemId, fieldRef?, stepUp: <StepUpProof> }\n// ← { revealToken: \"<JWT ≤180s>\", scope, vaultItemId, expiresIn: 180 }\n```\n`StepUpProof` is one of:\n```jsonc\n{ \"kind\": \"passphrase\", \"nonce\": \"<from /challenge>\",\n \"argon2\": { \"proof\": \"<b64url Ed25519 sig over the step-up message>\",\n \"memoryKiB\": 19456, \"iterations\": 2, \"parallelism\": 1 } }\n\n{ \"kind\": \"passkey\", \"nonce\": \"<from /challenge>\",\n \"assertion\": <WebAuthn AuthenticationResponseJSON> } // see Passkey step-up\n```\nGates, all fail-closed and in order: **(a)** tenant load, **(b)** any presented `ctx.scope.seal` claim must match the item's scopeRef, **(c)** structural step-up (single-use nonce, bound message), **(d)** `assertGrantLive` (D1 read — owner reveal needs no grant; otherwise a live `seal_key_grant` for the scope, or an audience `vault_grant`).\n\n### 5. `/key` — fetch the wrapped key (bearer the reveal token)\n\nThe **separate** post-mint route (never folded into `/reveal`). Re-runs three independent gates — tenant, capability (`ctx.scope.seal` only), `assertGrantLive` (D1, **prior to and independent of** any KV revocation check, which fails *open*) — writes a committed `delivered` reveal-log row, and returns the still-wrapped material.\n\n```jsonc\n// → { vaultItemId } (Authorization: Bearer <revealToken>)\n// ← { wrappedKey: \"<qbseal envelope>\", ct: \"<qbseal content envelope>\",\n// wrapMethod: \"owner\" | \"scope\" | \"audience\" }\n```\nThe client unwraps per `wrapMethod` (see [`/my-grant`](#6-my-grant)) and decrypts `ct`. **No readable key ever touches the server.**\n\n### 6. `/my-grant` — the caller's own wrapped scope private key (reader)\n\nFor `wrapMethod: \"scope\"`, the client first unwraps the scope private key with its USER key, then the CK. User-scoped; 404 if not granted.\n\n```jsonc\n// → { scopeRef }\n// ← { wrappedPrivateKey: \"<qbseal envelope>\", wrapMethod: \"scope\" }\n```\n\n### 7. `/grant` — enroll a reader + store their wrapped scope key (key-admin)\n\nThe combined **enrollment + grant** endpoint. The server **never wraps** — it persists the client-supplied opaque blob. Exactly one live grant per `(scopeRef, userId)` (it revokes any prior live grant first).\n\n```jsonc\n// → { scopeRef, userId, wrappedPrivateKey: \"<qbseal envelope>\", wrapMethod: \"scope\",\n// wrapMeta?,\n// // OPTIONAL passphrase-reveal enrollment (the step-up verifier):\n// stepUp?: { kind: \"passphrase\", publicKey: \"<b64url Ed25519>\",\n// salt: \"<b64url>\", argon2: { memoryKiB, iterations, parallelism } } }\n// ← { granted: true, scopeRef, userId, stepUpEnrolled: boolean }\n```\n`stepUp.argon2` is floor-checked **at enrollment** (a weak verifier is rejected here, not just at reveal). The `stepUpPublicKey` + params are stored zero-knowledge; the passphrase never leaves the client.\n\n### 8. `/revoke` — sever future access (key-admin)\n\nTwo forms: `{ scopeRef, userId }` (revoke a scope-key grant) or `{ vaultItemId, audienceRef }` (revoke an audience grant). Severs the future D1 key-fetch **and** kills in-flight tokens via KV revocation. It does **not** recall an already-unwrapped key — the response surfaces `rotationRecommended` when that matters.\n\n### 9. `/rotate` — add a new key version + re-grant worklist (key-admin)\n\nAppend-only `INSERT` of a new `seal_keys` version, and returns the **re-grant worklist** — the live readers and their X25519 public keys.\n\n```jsonc\n// → { scopeRef, publicKey: \"<new b64url X25519>\" } // client generated the new keypair\n// ← { rotated: true, scopeRef, keyVersion: 2,\n// regrant: [{ userId, userPublicKey }, …], // re-wrap the NEW scope key to each\n// missingPublicKey: [userId, …] } // readers granted before key capture\n```\nThe key-admin's client wraps the **new** scope private key to each `regrant[].userPublicKey` and calls [`/grant`](#5-grant) per reader (which revokes the stale grant and inserts the fresh one). The server holds no key material, so it can only hand back the wrap targets — it never re-wraps. Older `seal_keys` versions remain readable, so existing sealed values keep decrypting until re-sealed. Readers in `missingPublicKey` re-request via [`/grant-request`](#10-grant-request).\n\n### 10. `/grant-request` — request access to a scope (any member)\n\nA reader who has a role for a scope but no grant publishes their X25519 USER public key. Requesting only publishes public material + intent; **fulfilling is the key-admin-gated action**. One pending request per `(scope, user)`; a fresh request replaces the pending key.\n\n```jsonc\n// → { scopeRef, userPublicKey: \"<b64url X25519>\" }\n// ← { requested: true, scopeRef }\n```\n\n### 11. `/grant-requests` — list pending requests (key-admin)\n\n```jsonc\n// → { scopeRef }\n// ← { scopeRef, requests: [{ userId, userPublicKey, requestedAt }, …] }\n```\nThe key-admin wraps the scope key to each `userPublicKey` and calls [`/grant`](#5-grant), which **auto-resolves** the matching pending request.\n\n### 12. `/recovery/enroll` — escrow the scope key under a recovery code (key-admin)\n\nA key-admin (holding the scope private key) wraps it to a key derived from a **recovery code** and escrows the blob. The server stores only the opaque recovery-wrapped material — the recovery code, held by the client, is what makes it usable; the server can never unwrap it. One live recovery per scope key version.\n\n```jsonc\n// → { scopeRef, wrappedPrivateKey: \"<qbseal envelope, scope key wrapped to the recovery key>\" }\n// ← { enrolled: true, scopeRef, keyVersion: 1 }\n```\n\n### 13. `/recovery/use` — retrieve the recovery blob (key-admin)\n\nReturns the live recovery-wrapped scope key (and appends a `recovery` entry to the reveal log). The client unwraps it with the recovery-code key to recover the scope private key, then re-grants readers. The returned blob is **useless without the recovery code** — the server gates *who* may fetch it, the code gates whether it can be unwrapped.\n\n```jsonc\n// → { scopeRef }\n// ← { scopeRef, keyVersion, wrappedPrivateKey: \"<qbseal envelope>\" } // 404 parity if none\n```\n\n#### role→grant: readers request, key-admins fulfil\n\nBecause the server holds no key material, it cannot mint a grant when a user gains a role. The supported pattern: the reader calls `/grant-request` (publishing their public key); a key-admin lists pending requests with `/grant-requests`, wraps the scope key to each, and `/grant`s them — which auto-resolves the request. Who is allowed to *request* (the \"role\" half) is your access policy; the cryptographic *fulfilment* is always key-admin-gated.\n\n## Passkey step-up\n\nWhen the passkey plugin is enabled, `/reveal` verifies a WebAuthn assertion whose **challenge is the server nonce** (not Better Auth's login challenge). The native ceremony must produce an `AuthenticationResponseJSON` (the `@simplewebauthn/browser` `startAuthentication` shape) for these expectations:\n\n| Field | Value |\n|---|---|\n| `challenge` | the `/challenge` `nonce` **as the base64url string** (the client signs the b64url text, the server passes `expectedChallenge = nonce`) |\n| `rpID` | the passkey plugin's `rpID` — i.e. `crossSubDomainCookies.domain` (leading dot stripped) when configured, else the host of `env.ACCOUNT_URL` |\n| `userVerification` | **required** (`requireUserVerification: true` — a reveal is a deliberate re-auth) |\n| origin | the resolved account origin (mirrors the `passkey({ rpID, origin })` plugin) |\n\nThe credential is looked up in the **auth** database (`passkey` table) and the signature counter is clone-checked. Conformance for passkey is **verify-based** at the server; the client's job is to bind `challenge = nonce` exactly.\n\n## Conformance vectors\n\nCanonical vectors live at **`packages/seal-client/vectors/qbseal-v1.json`**, generated from the reference TS SDK (`bun packages/seal-client/scripts/generate-vectors.ts`) and self-validated against it (`src/vectors.test.ts`). Every input (passphrase, salt, key seeds, IVs, ephemerals) is fixed, so the file is byte-stable and each vector reproduces from its inputs alone.\n\n| Group | Pins | Determinism |\n|---|---|---|\n| `kdf` | passphrase + salt + params → Ed25519/X25519 public keys | full |\n| `stepUpMessage` | `(scopeRef, vaultItemId, nonce)` → signed message | full |\n| `stepUpSign` | a signature that **verifies** against the message + pubkey | verify-based (signing may be randomized) |\n| `aesGcm` | key + IV + plaintext → ciphertext (+tag) | full |\n| `sealedBoxOpen` | recipient secret + box → plaintext | open-direction (canonical) |\n| `reveal` | passphrase → keys; owner + scope unwrap paths → plaintext | open-direction (canonical) |\n| `envelope` | `qbseal:1:` sealed-cell decodes structurally | full |\n\nA port verifies the open-direction vectors exactly, and proves its *seal* direction by round-tripping through its own open. Vectors are the **cross-language byte-for-byte guarantee** — CI runs every client (TypeScript, Swift, and Kotlin) against this one file and fails on drift.\n\n## Client SDKs\n\nYou don't have to implement the crypto. Quickback ships first-party clients, each gated in CI against the conformance vectors above — so they agree byte-for-byte with the server and with each other.\n\n| Platform | Package | Distribution | Crypto |\n|---|---|---|---|\n| Web / Worker / Node | `@quickback-dev/seal-client` | **emitted** into your project at `src/lib/seal-client/` (for any project with a `.sealed()` column) | `@noble` + WebCrypto |\n| iOS / macOS | **`QuickbackSeal`** | SwiftPM — `apps/seal-sdk/swift` | CryptoKit + vendored Argon2 |\n| JVM / Android | **`dev.quickback.seal`** | Gradle — `apps/seal-sdk/kotlin` | BouncyCastle |\n\nAll three expose the same shape: a `SealClient` over a transport you implement on your HTTP client (URLSession / OkHttp / Ktor / fetch). The transport just POSTs to `/seal/v1/*`; the SDK does the crypto and the reveal handshake.\n\n### Swift (iOS / macOS)\n\n```swift\n// Package.swift\n.package(url: \"https://github.com/paulstenhouse/quickback-compiler.git\", branch: \"main\")\n// target dependency: .product(name: \"QuickbackSeal\", package: \"quickback-compiler\")\n```\n```swift\n\nlet seal = SealClient(transport: myTransport) // POSTs to /seal/v1/*\nlet sealed = try await seal.sealField(scopeRef: scope, // WRITE — no key needed\n plaintext: Data(\"Background check: clear\".utf8))\n\nlet session = try seal.session(passphrase: vaultPass, saltB64url: salt, argon2: .defaults)\nlet plaintext = try await seal.reveal(session: session, scopeRef: scope, vaultItemId: id)\n```\n\n### Kotlin (JVM / Android)\n\n```kotlin\n// build.gradle.kts — composite build or a published artifact from apps/seal-sdk/kotlin\n\nval seal = SealClient(myTransport)\nval sealed = seal.sealField(scope, \"Background check: clear\".toByteArray()) // WRITE\n\nval session = seal.session(vaultPass, saltB64url, Argon2Params.DEFAULTS)\nval plaintext = seal.reveal(session, scope, vaultItemId) // REVEAL\n```\n\nPasskey reveal is the same call as `revealWithPasskey(…, getAssertion)`, where `getAssertion(nonce)` runs the platform WebAuthn ceremony with `challenge = nonce`. Full details, the transport contract, and the conformance harness live in [`apps/seal-sdk/README`](https://github.com/paulstenhouse/quickback-compiler/tree/main/apps/seal-sdk). The SDKs are versioned **with** the compiler in the same repo, so the wire format never drifts from the server you're talking to.\n\n## Not yet wired\n\nHonest gaps, fail-closed until built — a client should not assume these exist:\n\n- **Content-key re-encryption on rotation** — `/rotate` versions the scope key and re-grants *readers*, and older key versions stay readable, so nothing breaks. But existing sealed *values* keep their content keys wrapped to the old scope key until a client re-seals them; there's no bulk re-encrypt-and-crypto-shred-the-old-version flow yet.\n- **Audience grants beyond reveal** — `vault_grant` audience reveals are honored at `/reveal`/`/key`, but there's no first-class management surface yet.\n\nThese will arrive as additive `:1` routes (no wire-format break) with their own vectors."
163
163
  },
164
164
  "compiler/definitions/transitions": {
165
165
  "title": "Transitions",
@@ -447,7 +447,7 @@ export const DOCS = {
447
447
  },
448
448
  "stack/queues/handlers": {
449
449
  "title": "Custom Queue Handlers",
450
- "content": "Quickback lets you define custom queue handlers that integrate seamlessly with the generated queue consumer. This is useful for background processing like material extraction pipelines, batch jobs, and async workflows.\n\n## Overview\n\nCustom queue handlers are defined in the `services/queues/` directory using the `defineQueue` helper. The compiler extracts your handler logic and generates a unified queue consumer that dispatches messages based on their type.\n\n```\nquickback/\n├── features/ # Data layer (CRUD, actions, security)\n│ ├── materials/\n│ └── claims/\n└── services/ # Infrastructure layer\n └── queues/\n ├── ingest.ts # Material processing\n └── claim-batches.ts # Batch processing\n```\n\n## Defining a Queue Handler\n\nUse `defineQueue` to create a handler:\n\n```typescript\n// services/queues/ingest.ts\n\ninterface ProcessMaterialMessage {\n type: 'process_material';\n materialId: string;\n organizationId: string;\n}\n\nexport default defineQueue<ProcessMaterialMessage>({\n name: 'ingest',\n messageType: 'process_material',\n description: 'Process materials through extraction pipeline',\n\n execute: async ({ message, db, env, services, ack, retry }) => {\n const { materialId, organizationId } = message;\n\n // Dynamic import of schema\n const { materials } = await import('./features/materials/schema');\n\n // Get material from database\n const [material] = await db\n .select()\n .from(materials)\n .where(eq(materials.id, materialId))\n .limit(1);\n\n if (!material) {\n console.error('[IngestQueue] Material not found:', materialId);\n return { success: false, error: 'Material not found' };\n }\n\n // Process the material...\n await db\n .update(materials)\n .set({ extractionStatus: 'processing' })\n .where(eq(materials.id, materialId));\n\n // Your processing logic here\n\n return { success: true };\n },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `name` | `string` | Yes | Handler identifier (used in logs) |\n| `messageType` | `string` | Yes | Message type to match (e.g., `'process_material'`) |\n| `description` | `string` | No | Human-readable description |\n| `execute` | `function` | Yes | Handler function |\n\n## Execute Function\n\nThe `execute` function receives a context object:\n\n```typescript\nexecute: async ({ message, db, env, services, ack, retry }) => {\n // message - The message payload (typed via generic)\n // db - Drizzle database instance\n // env - Cloudflare bindings (AI, queues, etc.)\n // services - Generated services (ai, etc.)\n // ack() - Acknowledge message (auto-called on success)\n // retry() - Retry message (auto-called on failure)\n\n return { success: true }; // or { success: false, error: 'reason' }\n}\n```\n\n## Constants and Imports\n\nThe compiler extracts top-level constants and imports from your handler file and includes them in the generated queue consumer:\n\n```typescript\n// services/queues/ingest.ts\n\nconst TEXT_GENERATION_MODEL = '@cf/meta/llama-3.1-8b-instruct';\n\nconst EXTRACTION_PROMPT = `You are a news analyst. Extract factual claims from this article.\n\nFor each claim, output a JSON object with:\n- content: The claim as a complete, standalone sentence\n- claimType: One of NEWS, QUOTE, OFFICIAL, ALLEGATION, STATISTIC, FINDING\n- urgency: 1-5 (5 = most urgent/breaking)\n\nOutput ONLY a JSON array of claims, no other text.`;\n\nexport default defineQueue({\n // ... handler definition\n});\n```\n\nThe compiler:\n1. Extracts all `import` statements\n2. Extracts top-level `const` declarations (including multi-line template literals)\n3. Inlines them in the generated queue consumer\n\n## Dynamic Schema Imports\n\nSince your schema files are generated by Quickback, use dynamic imports to reference them:\n\n```typescript\nexecute: async ({ message, db }) => {\n // Dynamic import - path is relative to generated src/ directory\n const { materials, claimExtractionBatches } = await import('./features/materials/schema');\n\n const [material] = await db\n .select()\n .from(materials)\n .where(eq(materials.id, message.materialId));\n\n // ...\n}\n```\n\n## Sending to Other Queues\n\nChain queue handlers by sending messages to other queues:\n\n```typescript\nexecute: async ({ message, db, env }) => {\n const { materialId } = message;\n\n // Process and create batch...\n const batchId = generateId('batch');\n\n // Send to next stage\n if (env.CLAIM_BATCHES_QUEUE) {\n await env.CLAIM_BATCHES_QUEUE.send({\n type: 'claim_batch_stage',\n batch_id: batchId,\n material_id: materialId,\n stage: 'subeditor',\n });\n }\n\n return { success: true };\n}\n```\n\n## Generated Output\n\nWhen queue handlers are defined, the compiler generates a unified `queue-consumer.ts`:\n\n```typescript\n// src/queue-consumer.ts (generated)\n\nconst TEXT_GENERATION_MODEL = '@cf/meta/llama-3.1-8b-instruct';\nconst EXTRACTION_PROMPT = `...`;\n\n// Embedding handler (if embeddings configured)\nconst embeddingQueueHandler = async (batch, env) => { ... };\n\n// Custom handler: ingest\nconst ingestQueueHandler = async (batch, env) => {\n const db = drizzle(env.DB);\n const services = createServices(env);\n\n for (const message of batch.messages) {\n try {\n const result = await executeHandler({\n message: message.body,\n env, db, services,\n ack: () => message.ack(),\n retry: () => message.retry(),\n });\n\n if (result.success) message.ack();\n else message.retry();\n } catch (error) {\n message.retry();\n }\n }\n};\n\n// Unified dispatcher\nexport const queue = async (batch, env) => {\n const messageType = batch.messages[0]?.body?.type;\n\n switch (messageType) {\n case 'embedding':\n await embeddingQueueHandler(batch, env);\n break;\n case 'process_material':\n await ingestQueueHandler(batch, env);\n break;\n default:\n console.warn('[Queue] Unknown message type:', messageType);\n for (const msg of batch.messages) msg.ack();\n }\n};\n```\n\n## wrangler.toml Configuration\n\nConfigure your queues in wrangler.toml:\n\n```toml\n# Queue producers (send to queues)\n[[queues.producers]]\nqueue = \"my-app-ingest-queue\"\nbinding = \"INGEST_QUEUE\"\n\n[[queues.producers]]\nqueue = \"my-app-claim-batches-queue\"\nbinding = \"CLAIM_BATCHES_QUEUE\"\n\n# Queue consumers (receive from queues)\n[[queues.consumers]]\nqueue = \"my-app-ingest-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n[[queues.consumers]]\nqueue = \"my-app-claim-batches-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n```\n\n## Deployment\n\nAfter defining queue handlers:\n\n1. **Create the queues:**\n ```bash\n wrangler queues create my-app-ingest-queue\n wrangler queues create my-app-claim-batches-queue\n ```\n\n2. **Compile:**\n ```bash\n quickback compile\n ```\n\n3. **Deploy:**\n ```bash\n wrangler deploy\n ```\n\n## Error Handling\n\nThe queue consumer handles errors automatically:\n\n- **Return `{ success: true }`** - Message is acknowledged\n- **Return `{ success: false, error: '...' }`** - Message is retried\n- **Throw an exception** - Message is retried\n\nAfter `max_retries` (default 3), failed messages are dropped or sent to a dead-letter queue if configured.\n\n```typescript\nexecute: async ({ message, db }) => {\n try {\n // Your processing logic\n return { success: true };\n } catch (error) {\n console.error('[Handler] Failed:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error'\n };\n }\n}\n```\n\n## Combining with Embeddings\n\nCustom queue handlers work alongside automatic embeddings. The compiler generates a single queue consumer that handles both:\n\n```typescript\nswitch (messageType) {\n case 'embedding':\n // Auto-generated embedding handler\n await embeddingQueueHandler(batch, env);\n break;\n case 'process_material':\n // Your custom handler\n await ingestQueueHandler(batch, env);\n break;\n}\n```\n\nSee [Automatic Embeddings](/stack/vector/embeddings) for configuring auto-embedding on CRUD operations."
450
+ "content": "Quickback lets you define custom queue handlers that integrate seamlessly with the generated queue consumer. This is useful for background processing like material extraction pipelines, batch jobs, and async workflows.\n\n## Overview\n\nCustom queue handlers are defined in the `services/queues/` directory using the `defineQueue` helper. The compiler extracts your handler logic and generates a unified queue consumer that dispatches messages based on their type.\n\n```\nquickback/\n├── features/ # Data layer (CRUD, actions, security)\n│ ├── materials/\n│ └── claims/\n└── services/ # Infrastructure layer\n └── queues/\n ├── ingest.ts # Material processing\n └── claim-batches.ts # Batch processing\n```\n\n## Defining a Queue Handler\n\nUse `defineQueue` to create a handler:\n\n```typescript\n// services/queues/ingest.ts\n\ninterface ProcessMaterialMessage {\n type: 'process_material';\n materialId: string;\n organizationId: string;\n}\n\nexport default defineQueue<ProcessMaterialMessage>({\n name: 'ingest',\n messageType: 'process_material',\n description: 'Process materials through extraction pipeline',\n\n execute: async ({ message, db, env, services, ack, retry }) => {\n const { materialId, organizationId } = message;\n\n // Dynamic import of schema\n const { materials } = await import('./features/materials/schema');\n\n // Get material from database\n const [material] = await db\n .select()\n .from(materials)\n .where(eq(materials.id, materialId))\n .limit(1);\n\n if (!material) {\n console.error('[IngestQueue] Material not found:', materialId);\n return { success: false, error: 'Material not found' };\n }\n\n // Process the material...\n await db\n .update(materials)\n .set({ extractionStatus: 'processing' })\n .where(eq(materials.id, materialId));\n\n // Your processing logic here\n\n return { success: true };\n },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `name` | `string` | Yes | Handler identifier (used in logs) |\n| `messageType` | `string` | Yes | Message type to match (e.g., `'process_material'`) |\n| `description` | `string` | No | Human-readable description |\n| `execute` | `function` | Yes | Handler function |\n\n## Execute Function\n\nThe `execute` function receives a context object:\n\n```typescript\nexecute: async ({ message, db, env, services, ack, retry, withInternalContext }) => {\n // message - The message payload (typed via generic)\n // db - Drizzle database instance (raw — you own provenance on writes)\n // env - Cloudflare bindings (AI, queues, etc.)\n // services - Generated services (ai, etc.)\n // ack() - Acknowledge message (auto-called on success)\n // retry() - Retry message (auto-called on failure)\n // withInternalContext - enter the INTERNAL trust zone (see below)\n\n return { success: true }; // or { success: false, error: 'reason' }\n}\n```\n\n### `withInternalContext` — attributable internal writes\n\nQueue runs are server-internal: no authenticated user, no request, no org\nscope. The top-level `db` is the **raw** client — writes through it stamp no\naudit actor, and provenance is your responsibility. When the handler needs to\ntouch `roles: ['INTERNAL']`-gated rows, or you want its writes attributed,\nenter the internal trust zone:\n\n```typescript\nexecute: async ({ message, withInternalContext }) => {\n await withInternalContext(async ({ ctx, db, services }) => {\n // ctx.internal = true, ctx.userId = \"system:queue-<name>\"\n // db is audit-wrapped: createdBy/modifiedBy stamp as system:queue-<name>\n await db.update(pats).set({ lastUsedAt: new Date().toISOString() });\n });\n return { success: true };\n}\n```\n\nThe handle it passes is **audit-wrapped** — `createdBy`/`modifiedBy` land as\n`system:queue-<name>`, matching the cron schedules' `system:cron-<name>`\nconvention, so internal writes are attributable in the audit trail. There is\nno `activeOrgId`: tenant scoping happens at the row level via the message\npayload (e.g. `message.body.organizationId`).\n\n## Constants and Imports\n\nThe compiler extracts top-level constants and imports from your handler file and includes them in the generated queue consumer:\n\n```typescript\n// services/queues/ingest.ts\n\nconst TEXT_GENERATION_MODEL = '@cf/meta/llama-3.1-8b-instruct';\n\nconst EXTRACTION_PROMPT = `You are a news analyst. Extract factual claims from this article.\n\nFor each claim, output a JSON object with:\n- content: The claim as a complete, standalone sentence\n- claimType: One of NEWS, QUOTE, OFFICIAL, ALLEGATION, STATISTIC, FINDING\n- urgency: 1-5 (5 = most urgent/breaking)\n\nOutput ONLY a JSON array of claims, no other text.`;\n\nexport default defineQueue({\n // ... handler definition\n});\n```\n\nThe compiler:\n1. Extracts all `import` statements\n2. Extracts top-level `const` declarations (including multi-line template literals)\n3. Inlines them in the generated queue consumer\n\n## Dynamic Schema Imports\n\nSince your schema files are generated by Quickback, use dynamic imports to reference them:\n\n```typescript\nexecute: async ({ message, db }) => {\n // Dynamic import - path is relative to generated src/ directory\n const { materials, claimExtractionBatches } = await import('./features/materials/schema');\n\n const [material] = await db\n .select()\n .from(materials)\n .where(eq(materials.id, message.materialId));\n\n // ...\n}\n```\n\n## Sending to Other Queues\n\nChain queue handlers by sending messages to other queues:\n\n```typescript\nexecute: async ({ message, db, env }) => {\n const { materialId } = message;\n\n // Process and create batch...\n const batchId = generateId('batch');\n\n // Send to next stage\n if (env.CLAIM_BATCHES_QUEUE) {\n await env.CLAIM_BATCHES_QUEUE.send({\n type: 'claim_batch_stage',\n batch_id: batchId,\n material_id: materialId,\n stage: 'subeditor',\n });\n }\n\n return { success: true };\n}\n```\n\n## Generated Output\n\nWhen queue handlers are defined, the compiler generates a unified `queue-consumer.ts`:\n\n```typescript\n// src/queue-consumer.ts (generated)\n\nconst TEXT_GENERATION_MODEL = '@cf/meta/llama-3.1-8b-instruct';\nconst EXTRACTION_PROMPT = `...`;\n\n// Embedding handler (if embeddings configured)\nconst embeddingQueueHandler = async (batch, env) => { ... };\n\n// Custom handler: ingest\nconst ingestQueueHandler = async (batch, env) => {\n const db = drizzle(env.DB);\n const services = createServices(env);\n\n for (const message of batch.messages) {\n try {\n const result = await executeHandler({\n message: message.body,\n env, db, services,\n ack: () => message.ack(),\n retry: () => message.retry(),\n });\n\n if (result.success) message.ack();\n else message.retry();\n } catch (error) {\n message.retry();\n }\n }\n};\n\n// Unified dispatcher\nexport const queue = async (batch, env) => {\n const messageType = batch.messages[0]?.body?.type;\n\n switch (messageType) {\n case 'embedding':\n await embeddingQueueHandler(batch, env);\n break;\n case 'process_material':\n await ingestQueueHandler(batch, env);\n break;\n default:\n console.warn('[Queue] Unknown message type:', messageType);\n for (const msg of batch.messages) msg.ack();\n }\n};\n```\n\n## wrangler.toml Configuration\n\nConfigure your queues in wrangler.toml:\n\n```toml\n# Queue producers (send to queues)\n[[queues.producers]]\nqueue = \"my-app-ingest-queue\"\nbinding = \"INGEST_QUEUE\"\n\n[[queues.producers]]\nqueue = \"my-app-claim-batches-queue\"\nbinding = \"CLAIM_BATCHES_QUEUE\"\n\n# Queue consumers (receive from queues)\n[[queues.consumers]]\nqueue = \"my-app-ingest-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n[[queues.consumers]]\nqueue = \"my-app-claim-batches-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n```\n\n## Deployment\n\nAfter defining queue handlers:\n\n1. **Create the queues:**\n ```bash\n wrangler queues create my-app-ingest-queue\n wrangler queues create my-app-claim-batches-queue\n ```\n\n2. **Compile:**\n ```bash\n quickback compile\n ```\n\n3. **Deploy:**\n ```bash\n wrangler deploy\n ```\n\n## Error Handling\n\nThe queue consumer handles errors automatically:\n\n- **Return `{ success: true }`** - Message is acknowledged\n- **Return `{ success: false, error: '...' }`** - Message is retried\n- **Throw an exception** - Message is retried\n\nAfter `max_retries` (default 3), failed messages are dropped or sent to a dead-letter queue if configured.\n\n```typescript\nexecute: async ({ message, db }) => {\n try {\n // Your processing logic\n return { success: true };\n } catch (error) {\n console.error('[Handler] Failed:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error'\n };\n }\n}\n```\n\n## Combining with Embeddings\n\nCustom queue handlers work alongside automatic embeddings. The compiler generates a single queue consumer that handles both:\n\n```typescript\nswitch (messageType) {\n case 'embedding':\n // Auto-generated embedding handler\n await embeddingQueueHandler(batch, env);\n break;\n case 'process_material':\n // Your custom handler\n await ingestQueueHandler(batch, env);\n break;\n}\n```\n\nSee [Automatic Embeddings](/stack/vector/embeddings) for configuring auto-embedding on CRUD operations."
451
451
  },
452
452
  "stack/queues": {
453
453
  "title": "Queues",