@quickback-dev/cli 0.10.2 → 0.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/commands/compile.d.ts +9 -1
  2. package/dist/commands/compile.d.ts.map +1 -1
  3. package/dist/commands/compile.js +56 -16
  4. package/dist/commands/compile.js.map +1 -1
  5. package/dist/commands/create.js +108 -55
  6. package/dist/commands/create.js.map +1 -1
  7. package/dist/commands/init.d.ts.map +1 -1
  8. package/dist/commands/init.js +22 -0
  9. package/dist/commands/init.js.map +1 -1
  10. package/dist/cursor/quickback.mdc +61 -46
  11. package/dist/docs/content.js +18 -18
  12. package/dist/docs/content.js.map +1 -1
  13. package/dist/index.js +3 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/lib/api-client.d.ts +34 -2
  16. package/dist/lib/api-client.d.ts.map +1 -1
  17. package/dist/lib/api-client.js +31 -2
  18. package/dist/lib/api-client.js.map +1 -1
  19. package/dist/lib/api-client.test.js +58 -0
  20. package/dist/lib/api-client.test.js.map +1 -1
  21. package/dist/lib/config-sync.d.ts +55 -0
  22. package/dist/lib/config-sync.d.ts.map +1 -0
  23. package/dist/lib/config-sync.js +207 -0
  24. package/dist/lib/config-sync.js.map +1 -0
  25. package/dist/lib/config-sync.test.d.ts +2 -0
  26. package/dist/lib/config-sync.test.d.ts.map +1 -0
  27. package/dist/lib/config-sync.test.js +151 -0
  28. package/dist/lib/config-sync.test.js.map +1 -0
  29. package/dist/lib/file-loader.d.ts +39 -5
  30. package/dist/lib/file-loader.d.ts.map +1 -1
  31. package/dist/lib/file-loader.js +226 -63
  32. package/dist/lib/file-loader.js.map +1 -1
  33. package/dist/lib/file-loader.test.js +212 -1
  34. package/dist/lib/file-loader.test.js.map +1 -1
  35. package/dist/lib/prepare-output.d.ts +31 -0
  36. package/dist/lib/prepare-output.d.ts.map +1 -0
  37. package/dist/lib/prepare-output.js +95 -0
  38. package/dist/lib/prepare-output.js.map +1 -0
  39. package/dist/lib/prepare-output.test.d.ts +2 -0
  40. package/dist/lib/prepare-output.test.d.ts.map +1 -0
  41. package/dist/lib/prepare-output.test.js +105 -0
  42. package/dist/lib/prepare-output.test.js.map +1 -0
  43. package/dist/lib/sweep-stale.d.ts +25 -0
  44. package/dist/lib/sweep-stale.d.ts.map +1 -0
  45. package/dist/lib/sweep-stale.js +179 -0
  46. package/dist/lib/sweep-stale.js.map +1 -0
  47. package/dist/lib/sweep-stale.test.d.ts +2 -0
  48. package/dist/lib/sweep-stale.test.d.ts.map +1 -0
  49. package/dist/lib/sweep-stale.test.js +130 -0
  50. package/dist/lib/sweep-stale.test.js.map +1 -0
  51. package/dist/skill/SKILL.md +327 -103
  52. package/dist/skill/agents/quickback-specialist/AGENT.md +93 -81
  53. package/package.json +14 -14
  54. package/src/cursor/quickback.mdc +61 -46
  55. package/src/skill/SKILL.md +327 -103
  56. package/src/skill/agents/quickback-specialist/AGENT.md +93 -81
@@ -58,8 +58,10 @@ my-app/
58
58
  │ └── features/
59
59
  │ └── {feature-name}/
60
60
  │ ├── {table}.ts # Schema + security (defineTable)
61
- │ ├── actions.ts # Custom actions (optional)
62
- │ ├── handlers/ # Action handlers (optional)
61
+ │ ├── actions/ # One file per action — defineAction({...})
62
+ │ │ ├── {action}.ts # Binds to primary table (or standalone if path: is set)
63
+ │ │ └── {table}/{action}.ts # Binds to sibling <table>.ts (multi-table features)
64
+ │ ├── lib/ # Feature-local helpers, copied verbatim (optional)
63
65
  │ └── pages/ # Custom CMS pages (optional)
64
66
  │ └── {slug}.ts # definePage() call
65
67
  ├── src/ # ← compiled output
@@ -90,11 +92,11 @@ export default defineConfig({
90
92
  tagline: "Build faster, ship sooner",
91
93
  build: true, // Set false to skip SPA rebuild on subsequent compiles
92
94
  auth: {
93
- password: true, // Email/password login (default: false)
94
- emailOTP: true, // Email OTP login (default: true)
95
- passkey: true, // WebAuthn passkeys (default: true)
95
+ password: true, // Email/password login (default: true)
96
+ emailOTP: true, // Email OTP login (default: false)
97
+ passkey: true, // WebAuthn passkeys (default: false)
96
98
  signup: true, // User registration (default: true)
97
- organizations: true, // Multi-tenant org management (default: true)
99
+ organizations: true, // Multi-tenant org management UI (default: false; the orgs plugin itself is enabled by `features.organizations` which defaults true)
98
100
  admin: true, // Admin panel (default: true)
99
101
  emailVerification: true, // Require email verification (default: true)
100
102
  },
@@ -115,6 +117,38 @@ export default defineConfig({
115
117
 
116
118
  Minimal: `account: true` enables with all defaults. `account: { build: false }` skips rebuild on subsequent compiles.
117
119
 
120
+ ### Discoverable options block
121
+
122
+ After the first compile, the file gets a managed comment block bracketed by `// [quickback:options-start]` … `// [quickback:options-end]`. Every option Quickback supports is listed there as a commented-out line. To enable one, lift the line **above** the start sentinel and uncomment — Quickback notices and drops it from the managed block on the next compile to avoid duplicates. Anything outside the sentinels is yours and never touched. Skip with `quickback compile --no-sync-config`.
123
+
124
+ ### Custom bindings (`config.bindings`)
125
+
126
+ Declare additional Cloudflare bindings that flow into `wrangler.toml`. The compiler also auto-wires the `[[send_email]] EMAIL` binding, the `cloudflare-email.ts` helper, and Better Auth's `sendResetPassword` / `sendVerificationEmail` / `sendInvitationEmail` callbacks for any auth surface that needs mail (`emailAndPassword.enabled` OR the `emailOtp` / `magicLink` / `organization` plugins) — you don't need to add `bindings.sendEmail` by hand for the standard cases.
127
+
128
+ ```typescript
129
+ export default defineConfig({
130
+ // ...
131
+ bindings: {
132
+ kv: [{ binding: 'CACHE', id: '...' }],
133
+ r2: [{ binding: 'UPLOADS', bucketName: 'my-uploads' }],
134
+ queues: {
135
+ producers: [{ binding: 'JOBS', queue: 'jobs' }],
136
+ consumers: [{ queue: 'jobs', maxBatchSize: 10 }],
137
+ },
138
+ durableObjects: [{ binding: 'CHAT', className: 'ChatRoom' }],
139
+ vars: { FEATURE_X: 'true' },
140
+ },
141
+ });
142
+ ```
143
+
144
+ ### CMS access default
145
+
146
+ `cms: true` defaults to `access: 'admin'` — only users with `user.role === 'admin'` can enter the CMS. Non-admins are redirected to `/account/profile`. Override with `cms: { access: 'user' }` to open the CMS to all authenticated users.
147
+
148
+ ### Account fileUploads
149
+
150
+ `account.fileUploads: true` shows the avatar upload UI on the profile page. Defaults to `false`; enabling it requires R2 configured for storage.
151
+
118
152
  ## Compile Output and State Artifacts
119
153
 
120
154
  - Runtime code stays in `build.outputDir` (e.g. `src/`, `wrangler.toml`, `package.json`)
@@ -152,15 +186,17 @@ export default feature("todos", {
152
186
  columns: {
153
187
  id: q.id(),
154
188
  title: q.text().required(),
155
- description: q.text().optional(),
189
+ description: q.text({ maxLength: 1000 }).optional(),
156
190
  completed: q.bool().default(false),
157
- userId: q.text().required(),
158
- organizationId: q.text().required(),
191
+ ownerId: q.scope("owner"), // → ctx.userId, auto-firewalled, auto-populated
192
+ organizationId: q.scope("organization"), // → ctx.activeOrgId, same
159
193
  },
160
- firewall: { organization: {}, owner: {} },
194
+ // firewall block omitted — q.scope() auto-derives:
195
+ // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },
196
+ // { field: 'ownerId', equals: 'ctx.userId' },
197
+ // { field: 'deletedAt', isNull: true }]
198
+ read: { access: { roles: ["member", "admin"] } },
161
199
  crud: {
162
- list: { access: { roles: ["member", "admin"] } },
163
- get: { access: { roles: ["member", "admin"] } },
164
200
  create: { access: { roles: ["member", "admin"] } },
165
201
  update: { access: { roles: ["admin"] } },
166
202
  delete: { access: { roles: ["admin"] }, mode: "soft" },
@@ -169,16 +205,53 @@ export default feature("todos", {
169
205
  createable: ["title", "description", "completed"],
170
206
  updatable: ["title", "description", "completed"],
171
207
  },
172
- masking: {
173
- userId: { type: "redact", show: { roles: ["admin"] } },
174
- },
175
208
  });
176
209
  ```
177
210
 
178
- **q DSL quick reference:** column names default to snake_case of the JS key (`organizationId` → `organization_id`). `q.id()` emits a cuid2 primary key. Chainable modifiers: `.required()` / `.optional()` / `.default(v)` / `.unique()` / `.index()` / `.references(() => other.id, { onDelete: 'cascade' })`.
179
-
180
211
  The `feature()` form is compile-time sugar — the compiler expands it to `q.table()` + `defineTable()` internally. Use whichever reads best for the file.
181
212
 
213
+ ### q DSL — column types
214
+
215
+ Column names default to snake_case of the JS key (`organizationId` → `organization_id`). Override with the positional name string or the `sqlName` option.
216
+
217
+ | Builder | SQL | Zod | Notes |
218
+ |---|---|---|---|
219
+ | `q.id()` | `text('id').primaryKey()` | `z.string()` | cuid2 by default; ID style follows `database.generateId` |
220
+ | `q.text(name?)` / `q.text({ sqlName?, maxLength? })` | `text(...)` | `z.string()` (`.max(n)` if `maxLength`) | options form adds zod max-length only — SQL stays unconstrained |
221
+ | `q.url({ sqlName?, maxLength? })` | `text(...)` | `z.string().url()` | rejects `javascript:` / `data:` / non-URL strings at the API edge |
222
+ | `q.int(name?)` | `integer(...)` | `z.number().int()` | |
223
+ | `q.bool(name?)` | `boolean(...)` (sqlite: integer mode) | `z.boolean()` | |
224
+ | `q.uuid(name?)` | `uuid(...)` (sqlite: text) | `z.string().uuid()` | |
225
+ | `q.timestamp(name?)` | `timestamp(...)` (sqlite: text ISO) | `z.coerce.date()` | |
226
+ | `q.json(zodType?)` | `jsonb(...)` (sqlite: text mode) | `z.unknown()` or your zod | pass a zod schema for typed JSON |
227
+ | `q.enum(['a','b'])` | `text(..., { enum })` | `z.enum([...])` | |
228
+ | `q.scope(kind)` | `text(...).notNull()` | `z.string()` | tenant-scope column — see Firewall |
229
+
230
+ **Chainable modifiers:** `.required()` / `.optional()` / `.default(v)` / `.unique()` / `.index()` / `.filterable(false)` / `.searchable(false)` / `.references(() => other.id, { onDelete: 'cascade' })`.
231
+
232
+ `.filterable(false)` and `.searchable(false)` are capability opt-outs — every text column is filter/search-eligible by default; chain `false` to remove a column from `?<col>=` filters or the `?search=` OR'd LIKE scan. Masked columns are always excluded from `?search` regardless (see Masking).
233
+
234
+ ### Composite indexes & uniques on `feature()`
235
+
236
+ Single-column indexes go on the column (`q.text().index()`). Composite ones go at the top level — the sugar forwards them into the same `q.table` opts:
237
+
238
+ ```typescript
239
+ export default feature("memberships", {
240
+ columns: { userId: q.scope("owner"), organizationId: q.scope("organization"), role: q.text() },
241
+ indexes: [{ name: "memberships_user_org_idx", columns: ["userId", "organizationId"] }],
242
+ unique: [{ columns: ["userId", "organizationId"] }],
243
+ // ... read / crud / guards
244
+ });
245
+ ```
246
+
247
+ **Auto-indexes:** the compiler emits the indexes you'd otherwise author by hand. Don't pre-declare these — they'll be deduped:
248
+
249
+ | Trigger | Index emitted |
250
+ |---|---|
251
+ | Tenant col (`organizationId` / `userId`) + `deletedAt` | composite `(<isolation>, deletedAt)` |
252
+ | Any FK (`.references(...)`) | single-col `(<fk>)` (D1/SQLite don't auto-index FKs) |
253
+ | Any column in a view's `read.query.sortable` | single-col `(<col>)` |
254
+
182
255
  ### Example: same todos using the two-export form
183
256
 
184
257
  ```typescript
@@ -188,14 +261,15 @@ export const todos = q.table("todos", {
188
261
  id: q.id(),
189
262
  title: q.text().required(),
190
263
  completed: q.bool().default(false),
191
- userId: q.text().required(),
192
- organizationId: q.text().required(),
264
+ ownerId: q.scope("owner"),
265
+ organizationId: q.scope("organization"),
193
266
  });
194
267
 
195
268
  export default defineTable(todos, {
196
- firewall: { organization: {}, owner: {} },
197
- crud: { /* same as above */ },
198
- guards: { /* same as above */ },
269
+ // firewall auto-derived from q.scope() — same as the feature() example
270
+ read: { /* same as above */ },
271
+ crud: { /* same as above */ },
272
+ guards: { /* same as above */ },
199
273
  });
200
274
 
201
275
  export type Todo = typeof todos.$infer;
@@ -203,6 +277,8 @@ export type Todo = typeof todos.$infer;
203
277
 
204
278
  ### Example: same todos with Drizzle (for interop)
205
279
 
280
+ When bringing forward existing Drizzle code, declare a regular column. Auto-detection by **name** (`organizationId`, `ownerId`, `teamId`, `userId`) still picks it up — `q.scope()` semantics (auto-firewall, systemManaged, auto-populate) apply because they key off the firewall predicate, not the column DSL.
281
+
206
282
  ```typescript
207
283
  import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
208
284
  import { defineTable } from "@quickback/compiler";
@@ -216,9 +292,10 @@ export const todos = sqliteTable("todos", {
216
292
  });
217
293
 
218
294
  export default defineTable(todos, {
219
- firewall: { organization: {}, owner: {} },
220
- crud: { /* same as above */ },
221
- guards: { /* same as above */ },
295
+ // firewall auto-derived from column names; declare explicitly only if names don't match
296
+ read: { /* same as above */ },
297
+ crud: { /* same as above */ },
298
+ guards: { /* same as above */ },
222
299
  });
223
300
  ```
224
301
 
@@ -235,22 +312,28 @@ export const roomAmenities = q.table('roomAmenities', {
235
312
 
236
313
  The compiler warns once per such table so you confirm the opt-out is intentional.
237
314
 
238
- ### Handlers use `q.*` for query helpers too
315
+ ### Action files use `q.*` for query helpers too
239
316
 
240
- Custom action handlers query via the same `q` namespace:
317
+ Action `execute` functions query via the same `q` namespace:
241
318
 
242
319
  ```typescript
243
- // quickback/features/mail/handlers/inbound.ts
320
+ // quickback/features/mail/actions/inbound.ts
321
+ import { defineAction } from "../.quickback/define-action";
244
322
  import { q } from "../../../lib/q";
245
- import mailboxes from "../mailboxes";
246
- import messages from "../messages";
247
-
248
- export const execute = async ({ unsafeDb, input }) => {
249
- const mailbox = await unsafeDb.query.mailboxes.findFirst({
250
- where: q.eq(mailboxes.address, input.mailboxAddress),
251
- });
252
- // …
253
- };
323
+ import { mailboxes } from "../mailboxes";
324
+ import { messages } from "../messages";
325
+
326
+ export default defineAction({
327
+ description: "Process inbound mail",
328
+ path: "/inbound",
329
+ /* ... */
330
+ async execute({ unsafeDb, input }) {
331
+ const mailbox = await unsafeDb.query.mailboxes.findFirst({
332
+ where: q.eq(mailboxes.address, input.mailboxAddress),
333
+ });
334
+ // …
335
+ },
336
+ });
254
337
  ```
255
338
 
256
339
  Available: `q.and`, `q.or`, `q.not`, `q.eq`, `q.ne`, `q.gt`, `q.gte`, `q.lt`, `q.lte`, `q.like`, `q.ilike`, `q.inArray`, `q.notInArray`, `q.isNull`, `q.isNotNull`, `q.between`, `q.desc`, `q.asc`, `q.sql`. Pure re-export of Drizzle's query builder under the Quickback namespace — users can still `import { eq } from "drizzle-orm"` directly if they prefer.
@@ -275,18 +358,18 @@ export const execute = async ({ unsafeDb, input }) => {
275
358
 
276
359
  ### Import style
277
360
 
278
- With `feature()`, tables are **default exports** — use default imports in actions/other files:
361
+ With `feature()`, tables are **default exports** — use default imports:
279
362
 
280
363
  ```typescript
281
- // features/applications/actions.ts
282
- import applications from "./applications";
283
- import { defineActions } from "@quickback/compiler";
364
+ // features/applications/actions/advance.ts
365
+ import applications from "../applications";
366
+ import { defineAction } from "../.quickback/define-action";
284
367
  ```
285
368
 
286
- With the two-export form, tables are **named exports** — use named imports:
369
+ With the two-export form (`defineTable`), tables are **named exports** — use named imports:
287
370
 
288
371
  ```typescript
289
- import { applications } from "./applications";
372
+ import { applications } from "../applications";
290
373
  ```
291
374
 
292
375
  Both produce the same typed handle.
@@ -328,45 +411,82 @@ Request → Firewall → Access → Guards → Database → Masking → Response
328
411
 
329
412
  ### 1. Firewall — Data Isolation
330
413
 
331
- Compiles WHERE clauses to isolate data by ownership. Auto-detects column names.
414
+ Compiles WHERE clauses to isolate data by ownership. Predicates are AND'd together.
415
+
416
+ ```typescript
417
+ firewall: [
418
+ { field: 'organizationId', equals: 'ctx.activeOrgId' }, // WHERE organizationId = ctx.activeOrgId
419
+ { field: 'ownerId', equals: 'ctx.userId' }, // AND ownerId = ctx.userId
420
+ { field: 'teamId', equals: 'ctx.activeTeamId' }, // AND teamId = ctx.activeTeamId
421
+ { field: 'deletedAt', isNull: true }, // AND deletedAt IS NULL (soft-delete filter)
422
+ ]
423
+
424
+ // Public/system resources opt out of tenant scoping (soft-delete still applied):
425
+ firewall: [{ exception: true }]
426
+ ```
427
+
428
+ **Recommended: declare scope columns with `q.scope()`** — auto-derives the firewall predicate AND marks the column `systemManaged` (rejected from client input) AND auto-populates from ctx on insert/upsert. Zero ambiguity in the source:
332
429
 
333
430
  ```typescript
334
- firewall: {
335
- organization: {}, // WHERE organizationId = ctx.activeOrgId
336
- owner: { mode: 'optional' }, // AND (ownerId = ctx.userId OR ownerId IS NULL)
337
- team: {}, // WHERE teamId = ctx.activeTeamId
338
- softDelete: {}, // AND deletedAt IS NULL
339
- exception: true, // No filtering (public resources)
431
+ columns: {
432
+ organizationId: q.scope("organization"), // → ctx.activeOrgId
433
+ ownerId: q.scope("owner"), // → ctx.userId
434
+ teamId: q.scope("team"), // → ctx.activeTeamId
340
435
  }
341
436
  ```
342
437
 
343
- Auto-detection:
344
- - `organization` → looks for `organizationId` or `organization_id`
345
- - `owner` → looks for `userId` or `user_id`
346
- - `team` → looks for `teamId` or `team_id`
438
+ **Auto-derivation by name** (Drizzle interop, when the `firewall:` block is omitted): the compiler scans column names and emits the same predicates.
439
+
440
+ | Column name in schema | Predicate emitted |
441
+ |---|---|
442
+ | `organizationId` / `organisationId` | `{ field: '...', equals: 'ctx.activeOrgId' }` |
443
+ | `userId` (or `ownerId`) | `{ field: '...', equals: 'ctx.userId' }` |
444
+ | `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |
445
+ | `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` |
446
+
447
+ - Exactly one isolation column → auto-derived.
448
+ - Two or more → compile-time error; declare `firewall: [...]` explicitly OR use `q.scope()` to lock semantics in the source.
449
+ - Zero columns AND no PUBLIC route → compile-time error ("missing isolation column").
347
450
 
348
- Column overrides:
451
+ **Custom column / context source**: just write the predicate explicitly.
349
452
 
350
453
  ```typescript
351
- firewall: {
352
- organization: {
353
- column: 'tenant_id',
354
- source: 'ctx.tenant.id',
355
- },
356
- }
454
+ firewall: [
455
+ { field: 'tenantId', equals: 'ctx.activeOrgId' },
456
+ { field: 'status', in: ['active', 'pending'] }, // literal value, not ctx-derived
457
+ ]
357
458
  ```
358
459
 
359
- Owner modes: default = strict (only own records), `optional` = own + NULL owner (admin pattern).
460
+ **Predicate operators**: `equals` (column = ctx.* or literal), `isNull: true` (column IS NULL), `in: [...]` (column IN ...), `{ exception: true }` (opt out of tenant scoping).
360
461
 
361
462
  ### 2. Access — Permission Checks
362
463
 
363
464
  Role-based and record-based access control. Deny by default.
364
465
 
466
+ DSL v2 separates **reads** (collection + per-id GET) from **mutations**. The unified `read` block owns `GET /` AND `GET /:id` AND views; mutations live under `crud.create/update/delete`.
467
+
365
468
  ```typescript
469
+ read: {
470
+ access: { roles: ['member+'] }, // gates GET / and GET /:id
471
+ query: {
472
+ sortable: ['createdAt', 'status'], // ?sort= allowlist (defaults to all cols)
473
+ searchable: ['title', 'body'], // ?search= OR'd LIKE allowlist
474
+ filterable: ['status', 'priority'], // ?<col>= allowlist
475
+ },
476
+ views: {
477
+ summary: {
478
+ fields: ['id', 'title', 'status'],
479
+ access: { roles: ['member+'] },
480
+ query: { sortable: ['title'] }, // per-view overrides allowed
481
+ },
482
+ full: {
483
+ fields: ['id', 'title', 'status', 'body', 'internalNotes'],
484
+ access: { roles: ['admin+'] },
485
+ },
486
+ },
487
+ },
366
488
  crud: {
367
- list: { access: { roles: ['member+'] } }, // member, admin, owner
368
- get: { access: { roles: ['member+'] } },
369
- create: { access: { roles: ['admin+'] } }, // admin, owner
489
+ create: { access: { roles: ['admin+'] } },
370
490
  update: {
371
491
  access: {
372
492
  or: [
@@ -375,10 +495,18 @@ crud: {
375
495
  ],
376
496
  },
377
497
  },
378
- delete: { access: { roles: ['owner'] } }, // owner only
498
+ delete: { access: { roles: ['owner'] } },
379
499
  }
380
500
  ```
381
501
 
502
+ **Generated read endpoints:**
503
+ - `GET /api/v1/{resource}` — gated by `read.access`
504
+ - `GET /api/v1/{resource}/:id` — gated by `read.access` (single-record GET inherits)
505
+ - `GET /api/v1/{resource}?view=summary` — view dispatch under `?view=`
506
+ - `GET /api/v1/{resource}/views/summary` — explicit view path
507
+
508
+ > **DSL v2 migration:** `crud.list` and `crud.get` are rejected at compile time. Move them to `read.access`. A bare `crud: { list: {} }` becomes `read: {}`.
509
+
382
510
  **Role hierarchy**: Configure `auth.roleHierarchy` in your config (e.g., `['member', 'admin', 'owner']`) and use the `+` suffix to mean "this role and above". `"member+"` expands to `["member", "admin", "owner"]` at compile time. Roles without `+` are exact matches.
383
511
 
384
512
  Record condition operators: `equals`, `notEquals`, `in`, `notIn`, `greaterThan`, `lessThan`
@@ -415,6 +543,8 @@ Mask types: `email`, `phone`, `ssn`, `creditCard`, `name`, `redact`, `custom`
415
543
 
416
544
  Auto-detection warns on unmasked sensitive columns (`email`, `phone`, `ssn`, `password`, etc.).
417
545
 
546
+ **Search/filter gating.** Masked columns are dropped from `?search` by default — letting an unauthorized caller substring-search a masked SSN trivially leaks digit positions. To re-enable search on a masked column for callers who *can* see it unmasked, list it under a view's `read.query.searchable`. The compiler validates the intersection at compile time.
547
+
418
548
  ---
419
549
 
420
550
  ## Views — Column-Level Security
@@ -541,62 +671,156 @@ Docs: `quickback docs account-ui` | https://docs.quickback.dev/account-ui
541
671
 
542
672
  ## Actions — Custom Business Logic
543
673
 
544
- Defined in a separate `actions.ts` file using `defineActions()`.
674
+ Defined with `defineAction()` (singular). Per-action permissions live under `access:` (same shape as resource-level access).
675
+
676
+ **One file per action.** Each action is its own module under the feature's `actions/` directory:
677
+
678
+ - `actions/<name>.ts` — binds to the feature's primary table (the `<feature>.ts` file at the feature root). If `path:` is set, becomes a standalone action.
679
+ - `actions/<table>/<name>.ts` — binds to the sibling table file `<table>.ts` at the feature root. Use this in multi-table features.
680
+
681
+ The action's filename (sans `.ts`) is the action name AND the URL segment. Uniqueness is enforced per **`(bound table, name)` pair** — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish`). The compiler errors only when two action files would mount at the same URL.
682
+
683
+ For shared Zod schemas or helpers, put them under `<feature>/lib/` and import from each action file.
684
+
685
+ **Retired layouts** (rejected at load time with migration guidance): `actions.ts` (bundle), `_feature.ts`, `handlers/` directory, `defineActions(table, {...})`, `defineActions(null, {...})`, `*-actions.ts` / `*.actions.ts` filenames.
686
+
687
+ `execute:` must be an **async arrow function** (`async (ctx) => { … }`). `async function` declarations and non-async forms are rejected at parse time.
545
688
 
546
689
  ```typescript
547
- import { todos } from './todos';
548
- import { defineActions } from '@quickback/compiler';
549
- import { z } from 'zod';
690
+ // features/todos/actions/complete.ts
691
+ import { z } from "zod";
692
+ import { defineAction } from "../.quickback/define-action";
693
+ import { q } from "../../../lib/q"; // generated namespace; same as drizzle-orm
694
+ import todos from "../todos"; // default import: feature() exports
695
+ // import { todos } from "../todos"; // named import: two-export form
696
+
697
+ export default defineAction({
698
+ description: "Mark todo as complete",
699
+ input: z.object({ completedAt: z.string().datetime().optional() }),
700
+ access: { roles: ["member", "admin"], record: { completed: { equals: false } } },
701
+ sideEffects: "sync",
702
+ async execute({ db, record, whereRecord, auditFields }) {
703
+ await db.update(todos)
704
+ .set({ completed: true, modifiedAt: auditFields!.modifiedAt })
705
+ .where(whereRecord!(todos)); // firewall + soft-delete + id, in one
706
+ return { success: true };
707
+ },
708
+ });
709
+ ```
710
+
711
+ **Record-based** (no `path:`): `POST /api/v1/{resource}/:id/{action}` — record is loaded, firewall + access checks run, then `execute` is called with `record`, `whereRecord`, scoped `db`.
712
+ **Standalone** (`path:` set): custom `path` and `method`. No record context, no firewall preload.
713
+
714
+ Action options: `path`, `method` (GET/POST/PUT/PATCH/DELETE), `responseType` (json/stream/file), `sideEffects` (sync/async/fire-and-forget), `transition`, `unsafe`, `allowRawSql`, `cms`.
550
715
 
551
- export default defineActions(todos, {
552
- complete: {
553
- description: "Mark todo as complete",
554
- input: z.object({ completedAt: z.string().datetime().optional() }),
555
- guard: { roles: ["member", "admin"], record: { completed: { equals: false } } },
556
- execute: async ({ db, record, ctx, input }) => {
557
- await db.update(todos).set({ completed: true }).where(eq(todos.id, record.id));
558
- return { success: true };
716
+ ### `whereRecord(table)` — explicit, scope-safe WHERE
717
+
718
+ In record-based actions, `whereRecord(table)` returns a Drizzle expression that AND-merges the resource's firewall + soft-delete + `eq(table.id, record.id)`. Use it for protected-field writes — even if a future refactor swaps `db` for an unscoped client, the WHERE stays explicit. `whereRecord` is `undefined` for standalone actions.
719
+
720
+ ### `transition` — state-machine policy on protected fields
721
+
722
+ For protected fields that follow a state machine (status, lifecycle, fulfilment), enforce the *from/to pair*, not just the current state. Without `transition`, an `advance` action whose access allows `status in ['applied', 'screening']` will happily run `applied → offer` (a skip) or `screening → applied` (a regression).
723
+
724
+ ```typescript
725
+ // features/applications/actions/advance.ts
726
+ import { z } from "zod";
727
+ import { defineAction } from "../.quickback/define-action";
728
+ import { applications } from "../applications";
729
+
730
+ export default defineAction({
731
+ description: "Move application forward",
732
+ input: z.object({ nextStatus: z.enum(['screening', 'interview', 'offer']) }),
733
+ access: { roles: ['owner', 'admin'] },
734
+ transition: {
735
+ field: 'status',
736
+ via: 'nextStatus', // read target from input.nextStatus
737
+ fromTo: {
738
+ applied: ['screening'],
739
+ screening: ['interview'],
740
+ interview: ['offer'],
559
741
  },
560
- sideEffects: "sync",
561
742
  },
562
- archive: {
563
- description: "Archive a todo",
564
- input: z.object({}),
565
- guard: { roles: ["admin"] },
566
- handler: "./handlers/archive",
743
+ async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },
744
+ });
745
+ ```
746
+
747
+ ```typescript
748
+ // features/applications/actions/hire.ts
749
+ import { z } from "zod";
750
+ import { defineAction } from "../.quickback/define-action";
751
+ import { applications } from "../applications";
752
+
753
+ export default defineAction({
754
+ description: "Finalize an offer",
755
+ input: z.object({}),
756
+ access: { roles: ['owner'] },
757
+ transition: {
758
+ field: 'status',
759
+ to: 'hired', // fixed target — same value every call
760
+ fromTo: { offer: ['hired'] },
567
761
  },
762
+ async execute({ db, record, auditFields, whereTransition }) { /* … */ },
568
763
  });
569
764
  ```
570
765
 
571
- **Record-based** (default): `POST /api/v1/{resource}/:id/{action}`
572
- **Standalone**: `standalone: true`, custom `path` and `method`
766
+ Exactly one of `via` or `to` must be provided. On a bad transition the runtime returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with `field`, `current`, `target`, `allowedTargets`. The same 409 fires when a plain `access.record` precondition fails (was 403 before — splitting it lets clients tell *"you can't do this"* from *"you can't do this **yet**"*).
573
767
 
574
- Action options: `standalone`, `method` (GET/POST/PUT/PATCH/DELETE), `responseType` (json/stream/file), `sideEffects` (sync/async/fire-and-forget)
768
+ ### `unsafe` — bypass scoped DB filters (object form, with mandatory audit)
769
+
770
+ For platform-level support / cross-tenant operations, opt out of the scoped DB. The object form is required for new code — it makes the policy explicit and forces an audit reason:
771
+
772
+ ```typescript
773
+ // features/admin/actions/admin-report.ts
774
+ import { z } from "zod";
775
+ import { defineAction } from "../.quickback/define-action";
776
+ import { applications } from "../../applications/applications";
777
+
778
+ export default defineAction({
779
+ description: "Cross-org hiring report",
780
+ path: "/admin/cross-org-report",
781
+ input: z.object({ startDate: z.string() }),
782
+ access: { roles: ['owner'] },
783
+ unsafe: {
784
+ reason: "Support investigation for enterprise customer",
785
+ adminOnly: true, // default true — gates on ctx.userRole === 'admin'
786
+ crossTenant: true, // default true — bypasses firewall
787
+ targetScope: 'all', // 'all' | 'organization'
788
+ },
789
+ async execute({ db, unsafeDb, ctx, input }) {
790
+ // db is still scoped (safety net for accidental writes)
791
+ // unsafeDb bypasses scoped filters
792
+ return await unsafeDb.select().from(applications);
793
+ },
794
+ });
795
+ ```
796
+
797
+ Generated runtime auto-injects: Better Auth required, platform admin gate, mandatory audit logging on deny/success/error. Without unsafe mode, `unsafeDb` is `undefined`.
798
+
799
+ ### Soft-delete cascade (cross-feature)
800
+
801
+ When a parent is soft-deleted, every child table that holds an FK to it — both **same-feature** and **cross-feature** children — receives the same `deletedAt` / `deletedBy` stamp. The cascade UPDATE always AND-merges the child's own firewall, so a delete in one tenant never reaches a child row in another tenant. FKs declared with `onDelete: 'cascade'` or `'set null'` participate; FKs without `onDelete` are cascaded for backwards compat.
575
802
 
576
803
  ### Actions-Only Features
577
804
 
578
- Features that only contain standalone actions (no tables). Use `defineActions(null, { ... })`:
805
+ A feature directory with no top-level `*.ts` files is "tableless" — every action under `actions/` must be standalone (have `path:`). Use this for utility endpoints like webhooks, reports, or integrations.
579
806
 
580
807
  ```typescript
581
- // quickback/features/utilities/actions.ts
582
- import { defineActions } from '@quickback/compiler';
583
- import { z } from 'zod';
584
-
585
- export default defineActions(null, {
586
- healthCheck: {
587
- standalone: true,
588
- path: "/health",
589
- method: "GET",
590
- description: "Health check endpoint",
591
- input: z.object({}),
592
- guard: { roles: ["member", "admin"] },
593
- handler: "./handlers/health-check",
808
+ // quickback/features/utilities/actions/health-check.ts
809
+ import { z } from "zod";
810
+ import { defineAction } from "../.quickback/define-action";
811
+
812
+ export default defineAction({
813
+ description: "Health check endpoint",
814
+ path: "/health",
815
+ method: "GET",
816
+ input: z.object({}),
817
+ access: { roles: ["member", "admin"] },
818
+ async execute() {
819
+ return { ok: true };
594
820
  },
595
821
  });
596
822
  ```
597
823
 
598
- All actions in an actions-only feature must have `standalone: true` (since there's no table for record-based actions).
599
-
600
824
  ---
601
825
 
602
826
  ## API Reference