@quickback-dev/cli 0.56.6 → 0.56.7

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.
@@ -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 (record-based actions). See [Transitions](#transition-state-machine-policy) |\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### 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### 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```"
87
87
  },
88
88
  "compiler/definitions/arrows": {
89
89
  "title": "Arrows",
@@ -163,7 +163,7 @@ export const DOCS = {
163
163
  },
164
164
  "compiler/definitions/transitions": {
165
165
  "title": "Transitions",
166
- "content": "## Overview\n\nMost state changes follow the same shape: check the row is in a legal state,\nflip a column, stamp who/when, maybe cascade. Before transitions v2 every one\nof those was a hand-written action file — a podcast app had **ten files that\nwere byte-identical except the table name** (`publish.ts` / `revertToDraft.ts`\nacross five entities), and an events app had eight near-identical\ncheck-in/check-out files.\n\nTransitions v2 collapses both patterns:\n\n- **Action-level extensions** on `defineAction({ transition })` — guards,\n stamps, idempotency, compiler-applied writes.\n- **Table-level `transitions`** on `defineTable` — the compiler *generates*\n the action files, including `undo` inverses and `onEnter` cascades.\n\n## The marquee example: 10 files → 2 lines each\n\nBefore (×10 files across episodes/shows/seasons/collections/profiles):\n\n```typescript\n// actions/episodes/publish.ts — and nine siblings like it\nexport default defineAction({\n description: \"Publish an episode\",\n input: z.object({}),\n access: { roles: [\"admin+\"] },\n async execute({ db, record }) {\n const [updated] = await db.update(episodes)\n .set({ isPublished: true })\n .where(eq(episodes.id, record.id)).returning();\n return updated;\n },\n});\n```\n\nAfter — on each entity's `defineTable`:\n\n```typescript\nexport default defineTable(episodes, {\n // ...\n transitions: {\n publish: { field: \"isPublished\", from: false, to: true, access: { roles: [\"admin+\"] } },\n revertToDraft: { field: \"isPublished\", from: true, to: false, access: { roles: [\"admin+\"] } },\n },\n});\n```\n\nThe generated actions mount exactly where the hand-written files did\n(`POST /episodes/:id/publish`, operationId `episodesPublish`, same MCP tool\nname), ride the same OpenAPI/security-contract pipeline, and delete cleanly:\n**an explicit `actions/<name>.ts` file always wins** (the compiler warns about\nthe shadowed transitions entry).\n\n## Action-level extensions\n\nAll new keys are optional — a plain `{ field, fromTo, to|via }` transition\nbehaves exactly as before.\n\n```typescript\ntransition: {\n field: \"status\",\n to: \"confirmed\",\n fromTo: { pending: [\"confirmed\"] },\n // v2:\n guard: { // extra row preconditions\n status: \"confirmed\", // equality\n checkedInAt: { null: true }, // or { notNull: true }\n custom: (record) => record.eventId !== null, // escape hatch; may throw ActionError\n },\n onIllegal: { code: \"GUEST_NOT_CONFIRMED\", status: 409, message: \"Only confirmed guests can be checked in\" },\n idempotent: \"noop\", // already-in-target → { success: true, unchanged: true }\n stamp: { at: \"checkedInAt\", by: \"checkedInById\" }, // now-ISO / ctx.userId\n clears: [\"checkedOutAt\", \"checkedOutById\"], // nulled on transition\n}\n```\n\nSemantics:\n\n- **Guards** run against the fetched record *and* fold into the UPDATE's\n WHERE, so preconditions re-validate atomically at the SQL layer (an empty\n `RETURNING` maps to 409 `ACCESS_TRANSITION_LOST`). Guard failures return\n `onIllegal` (default 409 `TRANSITION_GUARD_FAILED`); on bulk twins they\n report per-id in the batch envelope.\n- **Compiler-applied writes**: declaring `stamp`/`clears` (or\n `applyBefore: true`) makes the compiler execute the UPDATE itself before\n `execute` — and `execute` becomes optional. An omitted `execute` returns\n `{ success: true, <field>: <to>, <stamp.at>: <now> }`. Set\n `applyBefore: false` to keep the write in your own `execute` (today's\n behavior).\n- **`field: null`** declares a pure stamp transition (check-in/check-out\n style) — guards + stamps with no state column.\n- **`actx.now`**: every action's execute context now carries `now` — one ISO\n timestamp per invocation. Prefer it over `new Date().toISOString()`.\n\n## Table-level generation\n\n```typescript\nexport default defineTable(guests, {\n // ...\n transitions: {\n checkIn: {\n field: null, // pure stamp transition\n guard: { status: \"confirmed\", checkedInAt: { null: true } },\n stamp: { at: \"checkedInAt\", by: \"checkedInById\" },\n undo: \"cancelCheckIn\", // generates the inverse\n access: { roles: [\"member+\"] },\n bulkVariant: true,\n },\n cancel: {\n field: \"status\",\n fromTo: { published: [\"cancelled\"] },\n to: \"cancelled\",\n stamp: { at: \"cancelledAt\" },\n access: { roles: [\"admin+\"] },\n onEnter: [\n { update: \"eventGuests\",\n set: { status: \"rescinded\" },\n where: { eventId: \"$record.id\", status: { in: [\"invited\", \"confirmed\"] } } },\n { enqueue: { queue: \"COMMS_QUEUE\",\n message: { kind: \"eventCancelled\", eventId: \"$record.id\", actorId: \"$ctx.userId\" } } },\n ],\n },\n },\n});\n```\n\n- **`undo: \"<name>\"`** generates the inverse action: the guard flips to\n `{ notNull: true }` on the stamp column, the SET nulls the stamp columns,\n and `from`/`to` reverse for field transitions.\n- **`onEnter` steps** run in the generated `execute`, *after* the\n compiler-applied primary write (parent row first). `update` steps go\n through the scoped db — cross-feature targets resolve automatically and\n inherit the firewall. `enqueue` steps ride the after-commit effects queue.\n Substitution values are a strict allowlist — `$record.<col>`,\n `$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id` — always\n parameterized, never interpolated into SQL.\n- **`access` is required** on every transition (fail-closed, like\n `defineAction`).\n- Boolean `from` values match integer-boolean columns too (`from: false`\n matches both `false` and `0`).\n\n### Not yet supported (fail loudly)\n\n`guard.custom` at table level, `onEnter.enqueue` with `perRowOf` or function\nmessages, and via-style (input-driven) targets all error with a pointer to a\nhand-written action. For manual fan-out enqueues, `sendQueueBatched` in\n`lib/effects` chunks at the Cloudflare Queues 100-message cap."
166
+ "content": "## Overview\n\nMost state changes follow the same shape: check the row is in a legal state,\nflip a column, stamp who/when, maybe cascade. Before transitions v2 every one\nof those was a hand-written action file — a podcast app had **ten files that\nwere byte-identical except the table name** (`publish.ts` / `revertToDraft.ts`\nacross five entities), and an events app had eight near-identical\ncheck-in/check-out files.\n\nTransitions v2 collapses both patterns:\n\n- **Action-level extensions** on `defineAction({ transition })` — guards,\n stamps, idempotency, compiler-applied writes.\n- **Table-level `transitions`** on `defineTable` — the compiler *generates*\n the action files, including `undo` inverses and `onEnter` cascades.\n\n## The marquee example: 10 files → 2 lines each\n\nBefore (×10 files across episodes/shows/seasons/collections/profiles):\n\n```typescript\n// actions/episodes/publish.ts — and nine siblings like it\nexport default defineAction({\n description: \"Publish an episode\",\n input: z.object({}),\n access: { roles: [\"admin+\"] },\n async execute({ db, record }) {\n const [updated] = await db.update(episodes)\n .set({ isPublished: true })\n .where(eq(episodes.id, record.id)).returning();\n return updated;\n },\n});\n```\n\nAfter — on each entity's `defineTable`:\n\n```typescript\nexport default defineTable(episodes, {\n // ...\n transitions: {\n publish: { field: \"isPublished\", from: false, to: true, access: { roles: [\"admin+\"] } },\n revertToDraft: { field: \"isPublished\", from: true, to: false, access: { roles: [\"admin+\"] } },\n },\n});\n```\n\nThe generated actions mount exactly where the hand-written files did\n(`POST /episodes/:id/publish`, operationId `episodesPublish`, same MCP tool\nname), ride the same OpenAPI/security-contract pipeline, and delete cleanly:\n**an explicit `actions/<name>.ts` file always wins** (the compiler warns about\nthe shadowed transitions entry).\n\n## Action-level extensions\n\nAll new keys are optional — a plain `{ field, fromTo, to|via }` transition\nbehaves exactly as before.\n\n```typescript\ntransition: {\n field: \"status\",\n to: \"confirmed\",\n fromTo: { pending: [\"confirmed\"] },\n // v2:\n guard: { // extra row preconditions\n status: \"confirmed\", // equality\n checkedInAt: { null: true }, // or { notNull: true }\n custom: (record) => record.eventId !== null, // escape hatch; may throw ActionError\n },\n onIllegal: { code: \"GUEST_NOT_CONFIRMED\", status: 409, message: \"Only confirmed guests can be checked in\" },\n idempotent: \"noop\", // already-in-target → { success: true, unchanged: true }\n stamp: { at: \"checkedInAt\", by: \"checkedInById\" }, // now-ISO / ctx.userId\n clears: [\"checkedOutAt\", \"checkedOutById\"], // nulled on transition\n}\n```\n\nSemantics:\n\n- **Guards** run against the fetched record *and* fold into the UPDATE's\n WHERE, so preconditions re-validate atomically at the SQL layer (an empty\n `RETURNING` maps to 409 `ACCESS_TRANSITION_LOST`). Guard failures return\n `onIllegal` (default 409 `TRANSITION_GUARD_FAILED`); on bulk twins they\n report per-id in the batch envelope.\n- **Compiler-applied writes**: declaring `stamp`/`clears` (or\n `applyBefore: true`) makes the compiler execute the UPDATE itself before\n `execute` — and `execute` becomes optional. An omitted `execute` returns\n `{ success: true, <field>: <to>, <stamp.at>: <now> }`. Set\n `applyBefore: false` to keep the write in your own `execute` (today's\n behavior).\n- **`field: null`** declares a pure stamp transition (check-in/check-out\n style) — guards + stamps with no state column.\n- **`actx.now`**: every action's execute context now carries `now` — one ISO\n timestamp per invocation. Prefer it over `new Date().toISOString()`.\n\n### On a feature-area route\n\nA transition normally lives on a table-bound record action (`POST /:id/{action}`).\nTo attach the same compiler-owned transition to an explicit (`path:`) action mounted\nunder a [feature area](/compiler/definitions/feature-areas) — a nested route like\n`POST /events/:eventId/documents/:documentId/publish` — pair the `transition` with a\n`record:` binding. The compiler binds the record id from the proven route param,\nfirewalls + area-matches the row, then runs the exact machinery above (guarded UPDATE,\nnoop short-circuit, guards, stamps) before the action's own `execute`. See\n[Feature-area transition adapter](/compiler/definitions/actions#feature-area-transition-adapter).\n\n## Table-level generation\n\n```typescript\nexport default defineTable(guests, {\n // ...\n transitions: {\n checkIn: {\n field: null, // pure stamp transition\n guard: { status: \"confirmed\", checkedInAt: { null: true } },\n stamp: { at: \"checkedInAt\", by: \"checkedInById\" },\n undo: \"cancelCheckIn\", // generates the inverse\n access: { roles: [\"member+\"] },\n bulkVariant: true,\n },\n cancel: {\n field: \"status\",\n fromTo: { published: [\"cancelled\"] },\n to: \"cancelled\",\n stamp: { at: \"cancelledAt\" },\n access: { roles: [\"admin+\"] },\n onEnter: [\n { update: \"eventGuests\",\n set: { status: \"rescinded\" },\n where: { eventId: \"$record.id\", status: { in: [\"invited\", \"confirmed\"] } } },\n { enqueue: { queue: \"COMMS_QUEUE\",\n message: { kind: \"eventCancelled\", eventId: \"$record.id\", actorId: \"$ctx.userId\" } } },\n ],\n },\n },\n});\n```\n\n- **`undo: \"<name>\"`** generates the inverse action: the guard flips to\n `{ notNull: true }` on the stamp column, the SET nulls the stamp columns,\n and `from`/`to` reverse for field transitions.\n- **`onEnter` steps** run in the generated `execute`, *after* the\n compiler-applied primary write (parent row first). `update` steps go\n through the scoped db — cross-feature targets resolve automatically and\n inherit the firewall. `enqueue` steps ride the after-commit effects queue.\n Substitution values are a strict allowlist — `$record.<col>`,\n `$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id` — always\n parameterized, never interpolated into SQL.\n- **`access` is required** on every transition (fail-closed, like\n `defineAction`).\n- Boolean `from` values match integer-boolean columns too (`from: false`\n matches both `false` and `0`).\n\n### Not yet supported (fail loudly)\n\n`guard.custom` at table level, `onEnter.enqueue` with `perRowOf` or function\nmessages, and via-style (input-driven) targets all error with a pointer to a\nhand-written action. For manual fan-out enqueues, `sendQueueBatched` in\n`lib/effects` chunks at the Cloudflare Queues 100-message cap."
167
167
  },
168
168
  "compiler/definitions/triggers": {
169
169
  "title": "Triggers - Postgres-Style Table Triggers",
@@ -1 +1 @@
1
- {"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/docs/content.ts"],"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BAAmB;IACnB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,WAAW;IACX,0BAA0B;IAC1B,iBAAiB;IACjB,0BAA0B;IAC1B,yBAAyB;IACzB,2BAA2B;IAC3B,oBAAoB;IACpB,uBAAuB;IACvB,OAAO;IACP,YAAY;IACZ,uBAAuB;IACvB,cAAc;IACd,2BAA2B;IAC3B,gCAAgC;IAChC,gBAAgB;IAChB,2BAA2B;IAC3B,oCAAoC;IACpC,kCAAkC;IAClC,+BAA+B;IAC/B,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,cAAc;IACd,+BAA+B;IAC/B,wBAAwB;IACxB,gBAAgB;IAChB,yBAAyB;CAC1B,CAAC"}
1
+ {"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/docs/content.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,0DAA0D;AAO1D,MAAM,CAAC,MAAM,IAAI,GAA6B;IAC5C,WAAW,EAAE;QACX,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,q3xGAAq3xG;KACj4xG;IACD,4BAA4B,EAAE;QAC5B,OAAO,EAAE,oBAAoB;QAC7B,SAAS,EAAE,giRAAgiR;KAC5iR;IACD,wCAAwC,EAAE;QACxC,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,kmEAAkmE;KAC9mE;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,eAAe;QACxB,SAAS,EAAE,0iUAA0iU;KACtjU;IACD,gCAAgC,EAAE;QAChC,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,2iKAA2iK;KACvjK;IACD,mCAAmC,EAAE;QACnC,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,2jMAA2jM;KACvkM;IACD,yBAAyB,EAAE;QACzB,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,4kFAA4kF;KACxlF;IACD,wCAAwC,EAAE;QACxC,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C,2BAA2B;IAC3B,qDAAqD;IACrD,0DAA0D;IAC1D,iDAAiD;IACjD,8CAA8C;IAC9C,gDAAgD;IAChD,yCAAyC;IACzC,iDAAiD;IACjD,sDAAsD;IACtD,mDAAmD;IACnD,kBAAkB;IAClB,0BAA0B;IAC1B,OAAO;IACP,gCAAgC;IAChC,wCAAwC;IACxC,iCAAiC;IACjC,oCAAoC;IACpC,mCAAmC;IACnC,yCAAyC;IACzC,2BAA2B;IAC3B,yCAAyC;IACzC,oCAAoC;IACpC,wCAAwC;IACxC,oCAAoC;IACpC,wBAAwB;IACxB,kBAAkB;IAClB,iCAAiC;IACjC,oBAAoB;IACpB,qBAAqB;IACrB,wBAAwB;IACxB,YAAY;IACZ,6BAA6B;IAC7B,+BAA+B;IAC/B,4BAA4B;IAC5B,4BAA4B;IAC5B,oBAAoB;IACpB,qBAAqB;IACrB,uBAAuB;IACvB,mBAAmB;IACnB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,WAAW;IACX,0BAA0B;IAC1B,iBAAiB;IACjB,0BAA0B;IAC1B,yBAAyB;IACzB,2BAA2B;IAC3B,oBAAoB;IACpB,uBAAuB;IACvB,OAAO;IACP,YAAY;IACZ,uBAAuB;IACvB,cAAc;IACd,2BAA2B;IAC3B,gCAAgC;IAChC,gBAAgB;IAChB,2BAA2B;IAC3B,oCAAoC;IACpC,kCAAkC;IAClC,+BAA+B;IAC/B,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,cAAc;IACd,+BAA+B;IAC/B,wBAAwB;IACxB,gBAAgB;IAChB,yBAAyB;CAC1B,CAAC"}
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.56.6";
13
+ const CLI_VERSION = "0.56.7";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -166,7 +166,8 @@ namespace parameters.
166
166
  | `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |
167
167
  | `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |
168
168
  | `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |
169
- | `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |
169
+ | `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) |
170
+ | `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) |
170
171
  | `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |
171
172
  | `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) |
172
173
  | `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) |
@@ -394,6 +395,59 @@ with a mounted prefix, two more forms apply:
394
395
  An action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —
395
396
  and never vocabulary of an area the feature is not inside (compile error).
396
397
 
398
+ ### Feature-area transition adapter
399
+
400
+ A record [state transition](/compiler/definitions/transitions) normally lives on a
401
+ table-bound record action (`POST /:id/{action}`). When your clients call a nested
402
+ **feature-area** route instead, you can attach the same compiler-owned transition to
403
+ an explicit (`path:`) action by adding a `record:` binding. The binding is what lets a
404
+ `transition` ride a standalone action — without it, `transition` on a `path:` action is
405
+ a compile error.
406
+
407
+ ```typescript
408
+ // features/events/event_documents/actions/publishEventDocument.ts
409
+ export default defineAction({
410
+ path: "/events/:eventId/documents/:documentId/publish",
411
+ method: "POST",
412
+ description: "Publish one completed event document.",
413
+ input: z.object({ idempotencyKey: z.string().min(8) }),
414
+ access: { roles: ["member+"] },
415
+ // The compiler — not the action body — binds and firewalls the record.
416
+ record: {
417
+ table: "event_documents",
418
+ idFrom: "path.documentId", // MUST be a route param, never a body field
419
+ matchScope: "event", // row.eventId === ctx.event.id (area-proven)
420
+ },
421
+ transition: {
422
+ field: "status",
423
+ to: "published",
424
+ fromTo: { draft: ["published"] },
425
+ idempotent: "noop",
426
+ stamp: { at: "publishedAt" },
427
+ },
428
+ async execute({ record, invalidate }) {
429
+ // `record` is already bound, firewalled, area-matched, and transitioned.
430
+ // Own the response projection + invalidations here.
431
+ return { success: true as const, document: record };
432
+ },
433
+ });
434
+ ```
435
+
436
+ Security semantics (all enforced by the compiler, fail-closed):
437
+
438
+ - The record id is bound from the **proven route param** named in `idFrom` (`path.<param>`);
439
+ a request-body source is rejected at compile time.
440
+ - The row is loaded through the **scoped db**, so the table's full firewall
441
+ (org / owner / team + soft-delete) applies — a cross-tenant id is a `404`, never a leak.
442
+ - `matchScope` asserts the row belongs to the **area-proven** scope (e.g. `:eventId`
443
+ hydrated onto `ctx.event`); an unhydrated scope fails closed (`500`), and a row under a
444
+ different scope is a `404` (no cross-scope existence oracle).
445
+ - The transition keeps its **TOCTOU-safe guarded UPDATE** — the from-state is re-validated
446
+ in the `WHERE`, and a lost race returns `409` `ACCESS_TRANSITION_LOST`.
447
+ - Area admission **and** the action's own `access:` still AND-compose; the adapter widens neither.
448
+ - `idempotent: "noop"` short-circuits **before** `execute`, so a no-op never fires the
449
+ action's invalidations. Existing record actions and table-level transitions are unchanged.
450
+
397
451
  ### Example: AI Chat with Streaming
398
452
 
399
453
  ```typescript
@@ -94,6 +94,17 @@ Semantics:
94
94
  - **`actx.now`**: every action's execute context now carries `now` — one ISO
95
95
  timestamp per invocation. Prefer it over `new Date().toISOString()`.
96
96
 
97
+ ### On a feature-area route
98
+
99
+ A transition normally lives on a table-bound record action (`POST /:id/{action}`).
100
+ To attach the same compiler-owned transition to an explicit (`path:`) action mounted
101
+ under a [feature area](/compiler/definitions/feature-areas) — a nested route like
102
+ `POST /events/:eventId/documents/:documentId/publish` — pair the `transition` with a
103
+ `record:` binding. The compiler binds the record id from the proven route param,
104
+ firewalls + area-matches the row, then runs the exact machinery above (guarded UPDATE,
105
+ noop short-circuit, guards, stamps) before the action's own `execute`. See
106
+ [Feature-area transition adapter](/compiler/definitions/actions#feature-area-transition-adapter).
107
+
97
108
  ## Table-level generation
98
109
 
99
110
  ```typescript
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.56.6",
3
+ "version": "0.56.7",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -166,7 +166,8 @@ namespace parameters.
166
166
  | `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |
167
167
  | `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |
168
168
  | `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |
169
- | `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |
169
+ | `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) |
170
+ | `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) |
170
171
  | `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |
171
172
  | `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) |
172
173
  | `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) |
@@ -394,6 +395,59 @@ with a mounted prefix, two more forms apply:
394
395
  An action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —
395
396
  and never vocabulary of an area the feature is not inside (compile error).
396
397
 
398
+ ### Feature-area transition adapter
399
+
400
+ A record [state transition](/compiler/definitions/transitions) normally lives on a
401
+ table-bound record action (`POST /:id/{action}`). When your clients call a nested
402
+ **feature-area** route instead, you can attach the same compiler-owned transition to
403
+ an explicit (`path:`) action by adding a `record:` binding. The binding is what lets a
404
+ `transition` ride a standalone action — without it, `transition` on a `path:` action is
405
+ a compile error.
406
+
407
+ ```typescript
408
+ // features/events/event_documents/actions/publishEventDocument.ts
409
+ export default defineAction({
410
+ path: "/events/:eventId/documents/:documentId/publish",
411
+ method: "POST",
412
+ description: "Publish one completed event document.",
413
+ input: z.object({ idempotencyKey: z.string().min(8) }),
414
+ access: { roles: ["member+"] },
415
+ // The compiler — not the action body — binds and firewalls the record.
416
+ record: {
417
+ table: "event_documents",
418
+ idFrom: "path.documentId", // MUST be a route param, never a body field
419
+ matchScope: "event", // row.eventId === ctx.event.id (area-proven)
420
+ },
421
+ transition: {
422
+ field: "status",
423
+ to: "published",
424
+ fromTo: { draft: ["published"] },
425
+ idempotent: "noop",
426
+ stamp: { at: "publishedAt" },
427
+ },
428
+ async execute({ record, invalidate }) {
429
+ // `record` is already bound, firewalled, area-matched, and transitioned.
430
+ // Own the response projection + invalidations here.
431
+ return { success: true as const, document: record };
432
+ },
433
+ });
434
+ ```
435
+
436
+ Security semantics (all enforced by the compiler, fail-closed):
437
+
438
+ - The record id is bound from the **proven route param** named in `idFrom` (`path.<param>`);
439
+ a request-body source is rejected at compile time.
440
+ - The row is loaded through the **scoped db**, so the table's full firewall
441
+ (org / owner / team + soft-delete) applies — a cross-tenant id is a `404`, never a leak.
442
+ - `matchScope` asserts the row belongs to the **area-proven** scope (e.g. `:eventId`
443
+ hydrated onto `ctx.event`); an unhydrated scope fails closed (`500`), and a row under a
444
+ different scope is a `404` (no cross-scope existence oracle).
445
+ - The transition keeps its **TOCTOU-safe guarded UPDATE** — the from-state is re-validated
446
+ in the `WHERE`, and a lost race returns `409` `ACCESS_TRANSITION_LOST`.
447
+ - Area admission **and** the action's own `access:` still AND-compose; the adapter widens neither.
448
+ - `idempotent: "noop"` short-circuits **before** `execute`, so a no-op never fires the
449
+ action's invalidations. Existing record actions and table-level transitions are unchanged.
450
+
397
451
  ### Example: AI Chat with Streaming
398
452
 
399
453
  ```typescript
@@ -94,6 +94,17 @@ Semantics:
94
94
  - **`actx.now`**: every action's execute context now carries `now` — one ISO
95
95
  timestamp per invocation. Prefer it over `new Date().toISOString()`.
96
96
 
97
+ ### On a feature-area route
98
+
99
+ A transition normally lives on a table-bound record action (`POST /:id/{action}`).
100
+ To attach the same compiler-owned transition to an explicit (`path:`) action mounted
101
+ under a [feature area](/compiler/definitions/feature-areas) — a nested route like
102
+ `POST /events/:eventId/documents/:documentId/publish` — pair the `transition` with a
103
+ `record:` binding. The compiler binds the record id from the proven route param,
104
+ firewalls + area-matches the row, then runs the exact machinery above (guarded UPDATE,
105
+ noop short-circuit, guards, stamps) before the action's own `execute`. See
106
+ [Feature-area transition adapter](/compiler/definitions/actions#feature-area-transition-adapter).
107
+
97
108
  ## Table-level generation
98
109
 
99
110
  ```typescript