@quickback-dev/cli 0.54.0 → 0.55.1

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 (95) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +41 -4
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/create.d.ts.map +1 -1
  5. package/dist/commands/create.js +5 -1
  6. package/dist/commands/create.js.map +1 -1
  7. package/dist/docs/content.d.ts.map +1 -1
  8. package/dist/docs/content.js +37 -22
  9. package/dist/docs/content.js.map +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/lib/action-harvest.d.ts +16 -1
  12. package/dist/lib/action-harvest.d.ts.map +1 -1
  13. package/dist/lib/action-harvest.js +21 -1
  14. package/dist/lib/action-harvest.js.map +1 -1
  15. package/dist/lib/action-harvest.test.js +122 -3
  16. package/dist/lib/action-harvest.test.js.map +1 -1
  17. package/dist/lib/api-client.d.ts +11 -0
  18. package/dist/lib/api-client.d.ts.map +1 -1
  19. package/dist/lib/api-client.js.map +1 -1
  20. package/dist/lib/artifact-routing.d.ts.map +1 -1
  21. package/dist/lib/artifact-routing.js +3 -0
  22. package/dist/lib/artifact-routing.js.map +1 -1
  23. package/dist/lib/compiler-floor.d.ts +39 -0
  24. package/dist/lib/compiler-floor.d.ts.map +1 -0
  25. package/dist/lib/compiler-floor.js +75 -0
  26. package/dist/lib/compiler-floor.js.map +1 -0
  27. package/dist/lib/compiler-floor.test.d.ts +2 -0
  28. package/dist/lib/compiler-floor.test.d.ts.map +1 -0
  29. package/dist/lib/compiler-floor.test.js +67 -0
  30. package/dist/lib/compiler-floor.test.js.map +1 -0
  31. package/dist/lib/compiler-stubs.d.ts +6 -0
  32. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  33. package/dist/lib/compiler-stubs.js +8 -0
  34. package/dist/lib/compiler-stubs.js.map +1 -1
  35. package/dist/lib/file-loader.d.ts +45 -4
  36. package/dist/lib/file-loader.d.ts.map +1 -1
  37. package/dist/lib/file-loader.js +116 -19
  38. package/dist/lib/file-loader.js.map +1 -1
  39. package/dist/lib/file-loader.test.js +80 -4
  40. package/dist/lib/file-loader.test.js.map +1 -1
  41. package/dist/skill/SKILL.md +3 -1
  42. package/dist/skill/docs/changelog.md +66 -0
  43. package/dist/skill/docs/compiler/config/index.md +14 -1
  44. package/dist/skill/docs/compiler/config/providers.md +13 -9
  45. package/dist/skill/docs/compiler/definitions/access.md +134 -2
  46. package/dist/skill/docs/compiler/definitions/actions.md +22 -0
  47. package/dist/skill/docs/compiler/definitions/changesets.md +375 -0
  48. package/dist/skill/docs/compiler/definitions/feature-areas.md +189 -0
  49. package/dist/skill/docs/compiler/definitions/feature.md +33 -0
  50. package/dist/skill/docs/compiler/definitions/firewall.md +60 -1
  51. package/dist/skill/docs/compiler/definitions/guards.md +14 -0
  52. package/dist/skill/docs/compiler/definitions/index.md +28 -3
  53. package/dist/skill/docs/compiler/definitions/masking.md +8 -0
  54. package/dist/skill/docs/compiler/definitions/read.md +13 -0
  55. package/dist/skill/docs/compiler/definitions/schema.md +36 -1
  56. package/dist/skill/docs/compiler/definitions/scopes.md +23 -1
  57. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +27 -28
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +2 -0
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +49 -17
  60. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +66 -0
  61. package/dist/skill/docs/stack/api-contract/index.md +136 -0
  62. package/dist/skill/docs/stack/realtime/durable-objects.md +7 -0
  63. package/dist/skill/docs/stack/realtime/index.md +22 -0
  64. package/dist/skill/docs/stack/realtime/live-views.md +56 -0
  65. package/dist/skill/docs/stack/realtime/using-realtime.md +53 -0
  66. package/dist/skill/docs/stack/webhooks/inbound.md +79 -0
  67. package/dist/skill/docs/stack/webhooks/outbound.md +33 -0
  68. package/package.json +1 -1
  69. package/src/skill/SKILL.md +3 -1
  70. package/src/skill/docs/changelog.md +66 -0
  71. package/src/skill/docs/compiler/config/index.md +14 -1
  72. package/src/skill/docs/compiler/config/providers.md +13 -9
  73. package/src/skill/docs/compiler/definitions/access.md +134 -2
  74. package/src/skill/docs/compiler/definitions/actions.md +22 -0
  75. package/src/skill/docs/compiler/definitions/changesets.md +375 -0
  76. package/src/skill/docs/compiler/definitions/feature-areas.md +189 -0
  77. package/src/skill/docs/compiler/definitions/feature.md +33 -0
  78. package/src/skill/docs/compiler/definitions/firewall.md +60 -1
  79. package/src/skill/docs/compiler/definitions/guards.md +14 -0
  80. package/src/skill/docs/compiler/definitions/index.md +28 -3
  81. package/src/skill/docs/compiler/definitions/masking.md +8 -0
  82. package/src/skill/docs/compiler/definitions/read.md +13 -0
  83. package/src/skill/docs/compiler/definitions/schema.md +36 -1
  84. package/src/skill/docs/compiler/definitions/scopes.md +23 -1
  85. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +27 -28
  86. package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +2 -0
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +49 -17
  88. package/src/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +66 -0
  89. package/src/skill/docs/stack/api-contract/index.md +136 -0
  90. package/src/skill/docs/stack/realtime/durable-objects.md +7 -0
  91. package/src/skill/docs/stack/realtime/index.md +22 -0
  92. package/src/skill/docs/stack/realtime/live-views.md +56 -0
  93. package/src/skill/docs/stack/realtime/using-realtime.md +53 -0
  94. package/src/skill/docs/stack/webhooks/inbound.md +79 -0
  95. package/src/skill/docs/stack/webhooks/outbound.md +33 -0
@@ -0,0 +1,189 @@
1
+ # Feature Areas - Hierarchical Authz Grouping
2
+
3
+ Group related features under one **area** folder. The area's `_area.ts` file declares a route
4
+ prefix, admission lanes, and an authorization vocabulary — relationships, roles, rules, tenant
5
+ anchors, scope kinds — that every feature **inside the folder** inherits by name. Features
6
+ outside the folder cannot reference any of it: the compiler fails the build.
7
+
8
+ > Naming note: this concept is an **area**. `domain` in Quickback always means a DNS custom
9
+ > domain (see [custom domains](/compiler/config/domains)).
10
+
11
+ ## Why
12
+
13
+ Cross-cutting authz for a concept like a project, an event, or a location used to live in the
14
+ root `quickback.config.ts` and was wired to its consumers by a path-prefix string across a flat
15
+ feature list. An area makes the grouping **structural**: the folder *is* the boundary, the
16
+ `_area.ts` *is* the single declaration site, and the compiler enforces that the vocabulary
17
+ never leaks outside the subtree.
18
+
19
+ ## Layout
20
+
21
+ ```
22
+ quickback/features/
23
+ ├── workspace/ ← AREA (has _area.ts)
24
+ │ ├── _area.ts ← defineArea({...})
25
+ │ ├── projects.ts ← the area folder may itself be a feature
26
+ │ ├── project_collaborators.ts
27
+ │ ├── tasks/ ← child feature
28
+ │ │ ├── tasks.ts
29
+ │ │ └── actions/addTask.ts
30
+ │ └── chat/ ← child feature
31
+ │ └── actions/postMessage.ts
32
+ └── billing/ ← flat feature (unchanged)
33
+ ```
34
+
35
+ Reserved sub-directories (`actions/`, `handlers/`, `lib/`, `pages/`) are never child features. A directory
36
+ **without** `_area.ts` is a leaf feature — its unreserved subdirectories are not loaded, and a
37
+ subdirectory containing `defineTable(...)` / `defineAction(...)` **fails the compile** (silent
38
+ route/table disappearance after a mis-move is the failure mode areas must never introduce).
39
+ Feature leaf names stay globally unique — they key `src/features/<name>/` in the output, so
40
+ moving a feature into an area changes nothing about its generated identity.
41
+
42
+ ## `_area.ts`
43
+
44
+ ```typescript
45
+ // features/workspace/_area.ts
46
+ import { defineArea } from '@quickback/compiler';
47
+
48
+ export default defineArea({
49
+ // Namespace identity — drives the emitted routes file name and errors.
50
+ name: 'projectScope',
51
+
52
+ // Inherited route mount + admission gate. Optional: an area with no
53
+ // prefix contributes shared vocabulary only. A prefix REQUIRES at least
54
+ // one `via` lane (a mounted prefix with no gate would be ungated).
55
+ prefix: '/project/:projectId',
56
+ via: ['collaboratorOf', { roles: ['admin', 'owner'] }],
57
+ mintScope: true,
58
+ acceptScope: 'project',
59
+
60
+ // Area-owned vocabulary — the EXACT same shapes as the root authz blocks.
61
+ relationships: {
62
+ collaboratorOf: {
63
+ from: 'project_collaborators',
64
+ subject: { column: 'collaboratorUserId', equals: 'ctx.userId' },
65
+ resource: { column: 'projectId' },
66
+ where: { status: 'active' },
67
+ loads: 'projects',
68
+ exposeAs: 'project',
69
+ },
70
+ },
71
+ roles: {
72
+ projectStaff: { or: [{ via: 'collaboratorOf' }, { roles: ['admin', 'owner'] }] },
73
+ },
74
+ scopes: {
75
+ project: {
76
+ requestField: 'projectId',
77
+ roles: { collaborator: { via: 'collaboratorOf', subject: 'both' } },
78
+ },
79
+ },
80
+ // Named gates + tenant anchors work too — same shapes as authz.rules /
81
+ // authz.tenants, visible to this subtree only.
82
+ });
83
+ ```
84
+
85
+ A descendant feature references everything by bare name — no imports, no root declaration:
86
+
87
+ ```typescript
88
+ // features/workspace/tasks/actions/addTask.ts
89
+ export default defineAction({
90
+ path: './tasks/add', // relative → /project/:projectId/tasks/add
91
+ access: { roles: ['projectStaff'] }, // resolves against the area
92
+ // ...
93
+ });
94
+ ```
95
+
96
+ ## The visibility contract
97
+
98
+ An area's names are visible to **its own subtree only** (the area folder, its features, and
99
+ nested areas). The compiler checks **every** reference channel — access `roles:` arrays
100
+ (including named gates and both spellings of scoped roles: bare aliases and
101
+ `scope:<kind>:<role>`), action `access` and `anchor:`, firewall `via:` arms,
102
+ `ctx.scope.<kind>` accessors, `{ rule }` and `{ tenant }` firewall references, auth-view
103
+ `tenant:` includes, `realtime.requiredRoles`, table-level `namespace.via` lanes, and other
104
+ `_area.ts` nodes. Referencing an area name from outside is always a compile error:
105
+
106
+ ```
107
+ Feature "billing" ... references role "projectStaff" declared by area "projectScope"
108
+ (features/workspace/_area.ts), but this site is not inside that area. ... move the
109
+ referencing code under the declaring area, or lift the declaration to root authz if it
110
+ is genuinely global.
111
+ ```
112
+
113
+ Two structural rules keep the fold sound:
114
+
115
+ - **No overrides (v1).** Re-declaring an inherited name — in any class, including scope kinds,
116
+ scoped-role aliases, and namespace names — is a compile error. Declare each name in exactly
117
+ one place. (`overrides:` marker syntax is reserved for a future release.)
118
+ - **Declaration-site rule.** Root `authz` bodies (roles, rules, tenants, scopes, namespaces)
119
+ may reference **root-declared names only** — a root definition is visible everywhere and
120
+ would launder an area name out of its subtree. An area's bodies may reference root ∪
121
+ ancestors ∪ self.
122
+
123
+ One deliberate exception: root-config **namespace-identity wiring** — today exactly
124
+ `realtime.wsTicket.namespace` — may name an area's namespace. It attaches the area's complete
125
+ gate (its full lane set) and constructs no new grant. Such consumers are listed in the
126
+ manifest under the owning area.
127
+
128
+ ## Containment and the `route: 'self'` marker
129
+
130
+ The area's prefix is an audited surface:
131
+
132
+ - A feature **outside** the area may not declare an action path (or a table-level
133
+ `namespace` prefix) under the area's prefix — compile error.
134
+ - A project-level `authz.namespaces` entry the area does **not** own — root-declared, or
135
+ another area's — may not carve a prefix at or under the area's prefix. Namespace claiming
136
+ is longest-prefix-wins, so such an entry would silently re-gate the area's descendant
137
+ actions with its own `via` lanes — compile error. (A *descendant* feature's table-level
138
+ namespace inside the prefix is legal; the manifest attributes its claimed actions to that
139
+ namespace, not to the area.)
140
+ - A **descendant** action whose absolute path is *outside* the prefix opts out of the area's
141
+ admission gate and is gated solely by its own `access:`. That must be explicit:
142
+ mark the action `route: 'self'`, or the compile fails (a typo'd prefix must never silently
143
+ self-gate). The marker is equally rejected where it is dead — on in-prefix actions and in
144
+ features outside any mounted area. Every self-gated action is listed in the manifest.
145
+
146
+ Relative paths (`path: './…'`) resolve against the area prefix. Dot segments (`.` / `..`) are
147
+ rejected outright — the resolved route must stay under the prefix.
148
+
149
+ ## Nested areas
150
+
151
+ Areas nest to arbitrary depth. A nested area may declare additional **vocabulary** freely. A
152
+ nested area may **not** mount its own `prefix` under an ancestor that already mounts one:
153
+ per-level nested admission is *unlinked* (a caller related to child instance S under parent A
154
+ would be admitted at `/a/A/s/S` even when S belongs to parent B), and Quickback refuses to
155
+ compile an unlinked gate. Mount one prefix per chain, or keep the nested area
156
+ vocabulary-only.
157
+
158
+ ## The capability floor: `requires: ['feature-areas']`
159
+
160
+ An area-tree project **must** declare the marker in `quickback.config.ts`:
161
+
162
+ ```typescript
163
+ export default defineConfig({
164
+ // ...
165
+ requires: ['feature-areas'],
166
+ });
167
+ ```
168
+
169
+ Any CLI — including one that predates areas — passthrough-executes the config, so the marker
170
+ always reaches the compiler. A current compiler that sees the marker but no `areas` payload
171
+ rejects the compile with an upgrade message instead of silently compiling a project whose
172
+ nested features an old CLI never loaded (which would otherwise generate destructive
173
+ migrations). In the other direction, a current CLI refuses output from a compiler that
174
+ predates areas.
175
+
176
+ ## The authz manifest
177
+
178
+ Area projects emit `quickback/authz-manifest.json` on every compile — the audit inventory the
179
+ flat config can no longer answer from one file: the area tree, every folded name and its
180
+ declaring file, per-area member features, `areaGatedActions` vs `selfGatedActions`, and any
181
+ root-config namespace consumers. Review it in PRs the way you review the security reports;
182
+ the generated `AGENTS.md` also gains a feature-areas section so coding agents place new
183
+ features correctly.
184
+
185
+ ## What belongs at root
186
+
187
+ Root `authz` remains the home for genuinely global vocabulary — names used across areas or by
188
+ flat features. Everything scoped to one concept belongs in that concept's `_area.ts`. When in
189
+ doubt: if only one folder's features reference it, it belongs in that folder's area.
@@ -88,6 +88,13 @@ Same object, two names — pick one.
88
88
 
89
89
  ## Feature directory layout
90
90
 
91
+ Feature directories normally sit flat under `features/`. To group several features under one
92
+ authz concept (a shared route prefix + shared relationships/roles/scopes), put them inside an
93
+ **area** folder carrying `_area.ts` — see [Feature areas](/compiler/definitions/feature-areas).
94
+ Reserved sub-directories (`actions/`, `lib/`, `pages/`) are never child features, and a
95
+ subdirectory of a NON-area feature containing `defineTable(...)`/`defineAction(...)` fails the
96
+ compile (nested features load only under an area).
97
+
91
98
  A feature directory holds tables, optional shared schemas, and the handler files that back any actions:
92
99
 
93
100
  ```
@@ -111,6 +118,32 @@ Three things to know:
111
118
 
112
119
  For everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](/compiler/definitions/actions).
113
120
 
121
+ ## Composition vs reference — `owns`
122
+
123
+ A schema-level FK (`references:` / `.references()`) says "this row points at
124
+ that row." It does **not** say who owns whom. When a set of child rows has no
125
+ lifecycle of its own — junction memberships, normalized phones/emails, line
126
+ items — declare the composition with `owns` on the root table:
127
+
128
+ ```ts
129
+ export default feature("projects", {
130
+ // ...
131
+ owns: {
132
+ tasks: { table: "tasks", fk: "projectId", inherit: ["organizationId"] },
133
+ members: { table: "projectMembers", fk: "projectId", refs: { personId: "people" }, inherit: ["organizationId"] },
134
+ },
135
+ });
136
+ ```
137
+
138
+ That single fact generates the whole aggregate write path — one atomic
139
+ changeset request over the root plus its owned relations, every op paying the
140
+ child's own firewall/access/guards. Keep plain `references` for pointers at
141
+ independent entities (those go in the relation's `refs`, existence-checked
142
+ per-tenant). Contract v2 only. Full reference:
143
+ [changesets](/compiler/definitions/changesets) — including the per-op
144
+ `routes: false` knob for widening a child's access for changeset use without
145
+ mounting its raw route.
146
+
114
147
  ## Handlers — one `q` namespace for everything
115
148
 
116
149
  Custom action handlers need to run queries against the database. Quickback's compiled projects expose the Drizzle query-builder helpers on the same `q` namespace you use for schema authoring, so handler code stays inside one DSL:
@@ -119,7 +119,7 @@ The `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shutt
119
119
 
120
120
  ## Relationship-based scoping (`via:`)
121
121
 
122
- For relationship authorization — "this user can see rows X if they have a confirmed `event_guests` row pointing at X" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:
122
+ For relationship authorization — "this user can see rows X if they have a confirmed `event_guests` row pointing at X" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate. These relationships (and the named roles/permissions built on them) are defined once, centrally — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).
123
123
 
124
124
  ```typescript
125
125
  // quickback.config.ts
@@ -212,6 +212,65 @@ The compile-time analyzer additionally flags a referenced permission that can
212
212
  never be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost
213
213
  of each permission — see [Diagnostics](/compiler/definitions/diagnostics).
214
214
 
215
+ ## Named tenant anchors (`{ tenant }`)
216
+
217
+ The tenant predicate `{ field: 'organizationId', equals: 'ctx.activeOrgId' }` tends to be repeated on every table. Declare it **once** as a named anchor and reference it by name:
218
+
219
+ ```typescript
220
+ // quickback.config.ts
221
+ authz: {
222
+ tenants: {
223
+ org: { column: 'organizationId', equals: 'ctx.activeOrgId' },
224
+ },
225
+ }
226
+
227
+ // any firewall — top level or inside all/any groups:
228
+ firewall: [
229
+ { tenant: 'org' }, // → { field: 'organizationId', equals: 'ctx.activeOrgId' }
230
+ { field: 'deletedAt', isNull: true },
231
+ ]
232
+
233
+ // per-site COLUMN override (the claim side is never overridable):
234
+ firewall: [{ field: 'orgId', tenant: 'org' }]
235
+ ```
236
+
237
+ The anchor's `equals` must be a **verified ctx claim**: `ctx.activeOrgId` | `ctx.userId` | `ctx.scope.<kind>` | `ctx.scope.<kind>.<subKey>`. `ctx.activeTeamId` (drop-when-absent semantics stay a per-resource decision) and legacy aliases are rejected at declaration time — an anchor can never bind a request-derived value. A `{ tenant }` reference carrying its own `equals` is a compile error (one source of truth); an unknown anchor name is a compile error listing the declared anchors.
238
+
239
+ Expansion happens at compile time, before rendering — the emitted SQL is byte-identical to writing the predicate inline. Auth-DB read views accept the same anchors as a string: [`tenant: 'org'`](/stack/realtime/live-views#auth-db-includes-source-auth) — with one extra constraint: an anchor referenced from an auth-view include must bind a single-segment session claim (`ctx.<claim>`); scope-principal claims (`ctx.scope.*`) are firewall-lane bindings and are rejected there.
240
+
241
+ ## Named gate references (`{ rule }`)
242
+
243
+ A [gate](/compiler/definitions/access#named-gates-authzrules) that declares `firewall` lanes can be stamped onto a resource by name:
244
+
245
+ ```typescript
246
+ // quickback.config.ts
247
+ authz: {
248
+ rules: {
249
+ eventRow: {
250
+ who: { roles: ['owner', 'admin', 'member'] },
251
+ firewall: [{ any: [
252
+ { tenant: 'org' }, // org staff
253
+ { field: 'eventId', equals: 'ctx.scope.event' }, // signed scope claim
254
+ ] }],
255
+ },
256
+ },
257
+ }
258
+
259
+ // the resource:
260
+ firewall: [{ rule: 'eventRow' }]
261
+ // composes with the resource's own lanes (top-level AND):
262
+ firewall: [{ rule: 'eventRow' }, { field: 'kind', equals: 'ctx.scope.event.kind' }]
263
+ ```
264
+
265
+ Semantics — **AND-compose, top-level only, a reference can only narrow**:
266
+
267
+ - The gate's lanes splice into the resource's **top-level AND array** in place. They never replace the resource's own lanes, and composition can only *narrow* the row set.
268
+ - `{ rule }` is **not** valid inside an `{ all }` / `{ any }` group — a gate's firewall is one-or-more AND lanes, and splicing a multi-lane gate into an `any` group would OR-flatten it, admitting rows in **other tenants** that merely match one lane. This is a type error at authoring time and a compile error at coerce time.
269
+ - A gate's firewall may not contain `{ exception: true }` (a named bundle can never smuggle a firewall opt-out) or another `{ rule }` (gates don't nest — expansion is single-step, so cycles are impossible by construction).
270
+ - A gate with **no** `firewall` arm referenced from `firewall:` is a compile error — a who/record-only gate would silently contribute zero row lanes while the `record:` filter only ever applies at access sites.
271
+
272
+ The splice expands before validation and rendering, so the emitted `buildFirewallConditions` helper is byte-identical to writing the lanes inline — same groups, same absent-claim `1 = 0` guards, same `via:` subqueries.
273
+
215
274
  ## Context Sources
216
275
 
217
276
  When `equals` references the request context, use these standard sources:
@@ -111,6 +111,20 @@ firewall: [
111
111
 
112
112
  The semantic rule is "if the firewall says this column's value comes from the request context, the client cannot submit it." The value is auto-populated on create / upsert from `ctx`.
113
113
 
114
+ ### Changeset ops widen the set per-surface
115
+
116
+ On [changeset](/compiler/definitions/changesets) ops, an owned child's
117
+ systemManaged set additionally includes its **spine FK and every `inherit`
118
+ column** — the changeset supplies those structurally (the FK from the parent
119
+ op's id, inherit columns from the firewall-verified parent row), so a
120
+ client-supplied value is a pointer-carrying `GUARD_SYSTEM_MANAGED` rejection
121
+ (never silently stripped or stamped-over).
122
+
123
+ The child's **plain-CRUD guards are unaffected**: a junction that keeps its FK
124
+ in `createable` for its raw `POST` route stays correct — the same field
125
+ arriving in a changeset op is rejected because that surface stamps it. Two
126
+ surfaces, one declared rule each.
127
+
114
128
  ## Example
115
129
 
116
130
  ```typescript
@@ -23,13 +23,38 @@ my-app/
23
23
  │ ├── candidates.ts # Table + config (defineTable)
24
24
  │ ├── applications.ts # Secondary table + config
25
25
  │ ├── interview-scores.ts # Internal table (no routes)
26
- │ ├── actions.ts # Custom actions (optional)
27
- │ └── handlers/ # Action handlers (optional)
28
- │ └── advance-stage.ts
26
+ │ ├── actions/ # Custom actions — one file per action
27
+ │ │ └── advance-stage.ts
28
+ │ ├── lib/ # Feature-local helpers (optional)
29
+ │ └── pages/ # CMS page definitions (optional)
29
30
  ├── src/ # Generated code (output)
30
31
  └── package.json
31
32
  ```
32
33
 
34
+ `actions/`, `handlers/`, `lib/`, and `pages/` are the **reserved** sub-directories of a
35
+ feature — nothing else inside a feature folder is loaded, and a stray subdirectory that
36
+ contains `defineTable(...)` / `defineAction(...)` files fails the compile (files silently
37
+ disappearing after a mis-move is the failure mode this guards against).
38
+
39
+ Features can also be grouped into **areas**: a folder carrying an `_area.ts`
40
+ (`export default defineArea({...})`) declares a route prefix + admission gate and a shared
41
+ authz vocabulary, and every unreserved child directory becomes a child feature (nesting to
42
+ arbitrary depth):
43
+
44
+ ```
45
+ quickback/features/
46
+ ├── workspace/ # AREA (has _area.ts)
47
+ │ ├── _area.ts # defineArea({...}) — prefix, via lanes, vocabulary
48
+ │ ├── projects.ts # the area folder may itself be a feature
49
+ │ └── tasks/ # child feature
50
+ │ ├── tasks.ts
51
+ │ └── actions/addTask.ts
52
+ └── billing/ # flat feature (unchanged)
53
+ ```
54
+
55
+ Area projects must declare `requires: ['feature-areas']` in `quickback.config.ts`.
56
+ See [Feature areas](/compiler/definitions/feature-areas) for the full model.
57
+
33
58
  **Table files** use `defineTable` to combine schema and security config:
34
59
 
35
60
  ```typescript
@@ -145,6 +145,14 @@ The `'owner'` condition compares against the owner column declared via `q.scope(
145
145
 
146
146
  Relationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.
147
147
 
148
+ ### Named gates in masking
149
+
150
+ [Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:
151
+
152
+ - A **who-only** gate expands like a named role (its flat role list; the owner-gated flat-role constraint above applies).
153
+ - A gate carrying a **`record:`** predicate is a **compile error** — masking cannot evaluate record conditions, so the record dimension would be silently dropped.
154
+ - A gate carrying **firewall lanes** is a **compile error** — masking has no firewall array to satisfy, so the gate's row lanes would silently not apply. Reference a who-only rule (or inline the roles) in `show:`, and stamp the firewall gate on the resource's `firewall:` instead.
155
+
148
156
  **Workarounds**, depending on intent:
149
157
 
150
158
  - **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.
@@ -53,6 +53,8 @@ export default defineTable(customers, {
53
53
  | `GET /api/v1/{resource}/:id` | `read.access` |
54
54
  | `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |
55
55
 
56
+ Each `access` block takes a `roles: [...]` array. When the same role expression recurs across reads/views/CRUD, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).
57
+
56
58
  Single-record `GET /:id` inherits `read.access` automatically — there's no
57
59
  separate `read.get` block. If you need different access for single records,
58
60
  use record-level conditions on `read.access`:
@@ -208,9 +210,20 @@ export default defineTable(balanceSnapshots, {
208
210
  });
209
211
  ```
210
212
 
213
+ ## Aggregate Reads
214
+
215
+ Reading a parent **with** its owned relations is served today by `defineView`
216
+ includes (reverse-FK embedding with per-included-table firewall + masking) and
217
+ contract-v2 `?include=` on FK columns. The aggregate-changeset write surface
218
+ ([changesets](/compiler/definitions/changesets)) deliberately returns the
219
+ **root row only** in v1 — a nested aggregate representation is the phase-2
220
+ reader and will land on `?include=` over the `owns` graph, not on the write
221
+ response.
222
+
211
223
  ## See Also
212
224
 
213
225
  - [Views](/compiler/definitions/views) — Full reference for named projections
226
+ - [Changesets](/compiler/definitions/changesets) — Atomic writes over the `owns` graph
214
227
  - [Access](/compiler/definitions/access) — Roles, record conditions, and combinators
215
228
  - [Firewall](/compiler/definitions/firewall) — Tenant scoping and `firewallErrorMode`
216
229
  - [Views API](/compiler/targets/hono-api/using-the-api/views-api) — Calling views from clients
@@ -78,7 +78,7 @@ A few mechanics to know:
78
78
  - **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.
79
79
  - **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.
80
80
  - **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.
81
- - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`.
81
+ - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/compiler/definitions/changesets) on the root to generate the atomic aggregate write path.
82
82
  - **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.
83
83
 
84
84
  ### Column Types
@@ -95,6 +95,7 @@ A few mechanics to know:
95
95
  | `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
96
96
  | `q.id()` | `text('id').primaryKey()` | `z.string()` |
97
97
  | `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
98
+ | `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |
98
99
 
99
100
  `q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).
100
101
 
@@ -132,6 +133,38 @@ ownerId: q.scope('owner', { source: 'ctx.userId' }),
132
133
 
133
134
  `q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.
134
135
 
136
+ ### q.stamp() — proven-principal identity columns
137
+
138
+ `q.stamp({ fromScope, claim })` server-stamps a column from a **proven** scope claim — the caller's own identity within a relationship they were cryptographically proven to hold (e.g. an event attendee's own guest id). It is the identity sibling of `q.scope`:
139
+
140
+ | | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |
141
+ |---|---|---|
142
+ | **Purpose** | tenant isolation column | proven-principal **identity** column |
143
+ | **Value** | `ctx.scope.<kind>.id` / `activeOrgId` / `userId` | `ctx.scope.<kind>.<claim>` (`id` \| `subjectId` \| a scalar sub-key) |
144
+ | **Firewall arm?** | **yes** — it is the tenant `WHERE` | **never** — identity is not a tenant scope |
145
+ | **Guarantee** | "stamp **and verify**" (firewall re-checks on read/patch/delete) | "stamp **and prove**" (un-spoofable by token provenance) |
146
+
147
+ ```typescript
148
+ columns: {
149
+ eventId: q.scope('event'), // tenant firewall column
150
+ authorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }), // proven identity — un-spoofable
151
+ }
152
+ ```
153
+
154
+ **Runtime precedence — the org/admin hierarchy takes priority.** The stamp fires **only when the caller is admitted as a scope-only principal** (a scope-token holder, `ctx.scopePrincipal === true`): the column is force-stamped from the proven claim and any client-sent value is ignored. A caller admitted via the **org role hierarchy** (member / admin / owner) writes the column through the **org path** — a normal client-settable value, bounded by the org firewall (this is legitimate org-admin capability over their own org's rows). So a table whose `create` admits *both* org roles and a scope role needs **no split**: each identity writes the column the way its principal allows. The invariant that always holds is that a scope-only principal can never set a scope-stamped column to anything but its proven token.
155
+
156
+ **Fail-closed.** If a scope-only caller reaches the write without the required claim (`ctx.scope.<kind>.<claim>` absent) the write is refused with **403** *before* the insert — never a `NULL` identity row — for nullable stamp columns too. A `q.stamp` column may not also be a firewall arm, live on an `exception: true` table, or be sourced from a set-valued sub-key; each is a compile error.
157
+
158
+ `optional: true` makes the DDL column nullable (an org caller may then omit it); it does **not** relax the scope-principal 403.
159
+
160
+ **Set-on-insert, immutable thereafter.** A `q.stamp` column is a **create-time identity** — it is never re-derived on update. On every update-shaped write (`PATCH`, `PUT`, batch update, upsert, and a changeset root/child patch) the column is **systemManaged**: a client value for it is **rejected** (400), regardless of your `guards.updatable` list. Re-keying a proven identity is not an operation. (The force-stamp and the org-writable-on-create allowance apply to the create path only.)
161
+
162
+ **A non-nullable stamp on the org path must be supplied by the caller.** The force-stamp fires for scope-only principals; an org-admitted caller writes the column as normal client input. So a `NOT NULL` `q.stamp` column (the default) that an org caller *omits* lands on the database `NOT NULL` constraint (a deterministic field-named 400), not a NULL row. Add the column to `guards.createable` so org callers can supply it, or mark it `optional: true` if an org-created row may legitimately have no identity.
163
+
164
+ **The scope-only lane needs a scope-reachable write.** The force-stamp only runs once the scope-only principal actually *reaches* the insert. A table with a **hard organization firewall arm** (an `organizationId` sourced from `ctx.activeOrgId`) emits an `ORG_REQUIRED` gate that denies a sessionless scope principal (who has no active org) *before* the stamp — so on such tables the stamp serves the **org-admitted** caller, and the scope-only principal writes these rows as a **changeset child** that *inherits* `organizationId` from a firewall-verified parent. For a plain create/batch by a scope-only principal, firewall the table on the **scope** arm only (e.g. `firewall: { any: [{ field: 'eventId', equals: 'ctx.scope.event' }] }`, no org column) so no `ORG_REQUIRED` gate is emitted.
165
+
166
+ **Idempotency (at-least-once).** The stamp rides inside the write, so it inherits the endpoint's replay semantics: a **keyed** replay (a repeated `Idempotency-Key` whose handler is skipped) neither re-writes nor re-stamps; a **keyless** retry re-writes and therefore re-stamps from the caller's then-current proven claim.
167
+
135
168
  ### Naming Convention
136
169
 
137
170
  By default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).
@@ -490,6 +523,8 @@ ownerId: text('owner_id').notNull()
490
523
  teamId: text('team_id').notNull()
491
524
  ```
492
525
 
526
+ Those three are **tenant** auto-stamps (org / owner / team). To auto-stamp a **proven-principal identity** column instead — the caller's own id within a relationship, not a tenant key — use [`q.stamp()`](#qstamp--proven-principal-identity-columns). It sources from `ctx.scope.<kind>.<claim>` for scope-only principals and, unlike the tenant stamps, is never a firewall arm.
527
+
493
528
  ## Display Column
494
529
 
495
530
  When a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.
@@ -21,7 +21,12 @@ Most scope principals are signed-in users who prove a relationship at [`/scope/v
21
21
 
22
22
  ### 1. Declare relationships + scopes
23
23
 
24
- A scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing):
24
+ A scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing).
25
+
26
+ Scope kinds declare at root `authz` (visible everywhere) or inside a
27
+ [feature area](/compiler/definitions/feature-areas)'s `_area.ts` — then the kind, its bare
28
+ role aliases, the canonical `scope:<kind>:<role>` spellings, and `ctx.scope.<kind>` accessors
29
+ are all visible to that area's subtree only (any outside reference is a compile error):
25
30
 
26
31
  ```typescript
27
32
  // quickback.config.ts
@@ -173,6 +178,23 @@ kinds map to their session fields (`organization` → `ctx.activeOrgId`,
173
178
  `owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to
174
179
  `ctx.scope.<kind>.id`.
175
180
 
181
+ ### Stamping a proven *identity* claim (`q.stamp`)
182
+
183
+ `q.scope('event')` stamps the **tenant** id (`ctx.scope.event.id`). To stamp a
184
+ different **proven claim** off the same verified scope — the caller's own
185
+ `subjectId` (the conferring row's PK) or a scalar sub-key — use
186
+ [`q.stamp`](/compiler/definitions/schema#qstamp--proven-principal-identity-columns):
187
+
188
+ ```typescript
189
+ authorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }),
190
+ ```
191
+
192
+ Every proven scope carries `id`, `subjectId`, and any projected sub-keys; a
193
+ `q.stamp` column reads one of those. Unlike `q.scope` it is **never** a firewall
194
+ arm (identity is not a tenant scope), and it force-stamps **only** for scope-only
195
+ principals — an org member/admin/owner writes it via the org path. A scope-only
196
+ caller missing the claim gets a fail-closed **403**, never a `NULL` row.
197
+
176
198
  ## Namespace scope-claim refresh
177
199
 
178
200
  A scope is normally minted at `POST /scope/v1/enter`. When you also mount a
@@ -286,34 +286,33 @@ on staging or production targets. Wrangler uses this field only for local
286
286
  development; deployed Workers obtain their
287
287
  connection string from the Hyperdrive configuration identified by `id`.
288
288
 
289
- <Callout>
290
- The generated setup uses three Postgres roles: `quickback_owner` (NOLOGIN object
291
- owner for the app/auth schemas), `quickback_admin` (migration/setup actor — use
292
- its unpooled URL for `DATABASE_MIGRATION_URL`), and `quickback` (the Worker
293
- runtime role, the **only** deployed DB role — use its pooled URL for
294
- `DATABASE_URL`). The first generated migration bootstraps these roles as
295
- NOLOGIN; enable login and set passwords before use. Full walkthrough in the
296
- generated `docs/neon-setup.md`.
297
-
298
- Run the **first** `db:migrate` with your database owner credential (Neon's
299
- `neondb_owner`) — that bootstrap run also grants `quickback_admin` everything
300
- the Drizzle journal needs (`CREATE` on the database, plus ownership of the
301
- `drizzle` schema and `drizzle.__drizzle_migrations`). Routine migrates **after**
302
- bootstrap — applying new schema deltas — then run entirely as `quickback_admin`
303
- via `DATABASE_MIGRATION_URL`, no owner credential required. This includes the
304
- pinned runner's `CREATE SCHEMA IF NOT EXISTS drizzle` preamble, which needs
305
- database-level `CREATE` even as a no-op and previously forced every migrate
306
- back onto the owner credential. (A change to the **security/RLS config** appends
307
- a new `quickback_rls` migration that re-runs the role bootstrap, so re-point
308
- `DATABASE_MIGRATION_URL` at the owner credential for that one apply.)
309
-
310
- Each security migration first removes direct `PUBLIC` and `quickback` runtime
311
- privileges from the Drizzle schema, journal table, journal sequences, and
312
- database-level `CREATE`, then restores the migration role's capability. The
313
- audit schema/table likewise revoke prior direct grants before restoring only
314
- runtime schema usage + table `INSERT` and admin forensic access. Reapplying a
315
- migration therefore converges privilege drift instead of merely adding grants.
316
- </Callout>
289
+ > The generated setup uses three Postgres roles: `quickback_owner` (NOLOGIN object
290
+ > owner for the app/auth schemas), `quickback_admin` (migration/setup actor — use
291
+ > its unpooled URL for `DATABASE_MIGRATION_URL`), and `quickback` (the Worker
292
+ > runtime role, the **only** deployed DB role — use its pooled URL for
293
+ > `DATABASE_URL`). The first generated migration bootstraps these roles as
294
+ > NOLOGIN; enable login and set passwords before use. Full walkthrough in the
295
+ > generated `docs/neon-setup.md`.
296
+ >
297
+ > Run the **first** `db:migrate` with your database owner credential (Neon's
298
+ > `neondb_owner`) — that bootstrap run also grants `quickback_admin` everything
299
+ > the Drizzle journal needs (`CREATE` on the database, plus ownership of the
300
+ > `drizzle` schema and `drizzle.__drizzle_migrations`). Routine migrates **after**
301
+ > bootstrap — applying new schema deltas — then run entirely as `quickback_admin`
302
+ > via `DATABASE_MIGRATION_URL`, no owner credential required. This includes the
303
+ > pinned runner's `CREATE SCHEMA IF NOT EXISTS drizzle` preamble, which needs
304
+ > database-level `CREATE` even as a no-op and previously forced every migrate
305
+ > back onto the owner credential. (A change to the **security/RLS config** appends
306
+ > a new `quickback_rls` migration that re-runs the role bootstrap, so re-point
307
+ > `DATABASE_MIGRATION_URL` at the owner credential for that one apply.)
308
+ >
309
+ > Each security migration first removes direct `PUBLIC` and `quickback` runtime
310
+ > privileges from the Drizzle schema, journal table, journal sequences, and
311
+ > database-level `CREATE`, then restores the migration role's capability. The
312
+ > audit schema/table likewise revoke prior direct grants before restoring only
313
+ > runtime schema usage + table `INSERT` and admin forensic access. Reapplying a
314
+ > migration therefore converges privilege drift instead of merely adding grants.
315
+
317
316
 
318
317
  ## Better Auth schema generation
319
318
 
@@ -277,6 +277,8 @@ fail-fast per-record loop, `meta.transactional: false`.
277
277
  | `PUT /batch` (upsert) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |
278
278
  | `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |
279
279
  | `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |
280
+ | [Changeset](/compiler/definitions/changesets) (`application/vnd.quickback.changeset+json`, contract v2) | tx-supporting (postgres, neon over websocket/hyperdrive) | n/a | `true` | Root op + every child op share one transaction; any op failure rolls back the whole changeset. |
281
+ | [Changeset](/compiler/definitions/changesets) | cloudflare-d1, neon over http (Cloudflare default) | n/a | `false` | Deterministic parent-first fail-fast — the first op failure stops the changeset; already-applied ops stay committed (a consistent, independently-authorized prefix). |
280
282
 
281
283
  ### Reading `meta.transactional` in clients
282
284