@quickback-dev/cli 0.10.16 → 0.10.20

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 (249) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +40 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.js +6 -6
  5. package/dist/docs/content.js.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/skill/SKILL.md +142 -1051
  8. package/dist/skill/agents/quickback-specialist/AGENT.md +36 -0
  9. package/dist/skill/docs/changelog.md +1192 -0
  10. package/dist/skill/docs/compiler/claude-code-skill.md +312 -0
  11. package/dist/skill/docs/compiler/cloud-compiler/authentication.md +63 -0
  12. package/dist/skill/docs/compiler/cloud-compiler/cli.md +307 -0
  13. package/dist/skill/docs/compiler/cloud-compiler/endpoints.md +78 -0
  14. package/dist/skill/docs/compiler/cloud-compiler/index.md +65 -0
  15. package/dist/skill/docs/compiler/cloud-compiler/local-compiler.md +115 -0
  16. package/dist/skill/docs/compiler/cloud-compiler/troubleshooting.md +76 -0
  17. package/dist/skill/docs/compiler/config/agents.md +144 -0
  18. package/dist/skill/docs/compiler/config/auth.md +109 -0
  19. package/dist/skill/docs/compiler/config/bindings.md +176 -0
  20. package/dist/skill/docs/compiler/config/domains.md +149 -0
  21. package/dist/skill/docs/compiler/config/index.md +419 -0
  22. package/dist/skill/docs/compiler/config/output.md +338 -0
  23. package/dist/skill/docs/compiler/config/providers.md +248 -0
  24. package/dist/skill/docs/compiler/config/security.md +255 -0
  25. package/dist/skill/docs/compiler/config/single-tenant.md +128 -0
  26. package/dist/skill/docs/compiler/config/variables.md +157 -0
  27. package/dist/skill/docs/compiler/definitions/access.md +445 -0
  28. package/dist/skill/docs/compiler/definitions/actions.md +884 -0
  29. package/dist/skill/docs/compiler/definitions/concepts.md +52 -0
  30. package/dist/skill/docs/compiler/definitions/feature.md +164 -0
  31. package/dist/skill/docs/compiler/definitions/firewall.md +285 -0
  32. package/dist/skill/docs/compiler/definitions/guards.md +241 -0
  33. package/dist/skill/docs/compiler/definitions/index.md +219 -0
  34. package/dist/skill/docs/compiler/definitions/masking.md +241 -0
  35. package/dist/skill/docs/compiler/definitions/read.md +220 -0
  36. package/dist/skill/docs/compiler/definitions/schema.md +697 -0
  37. package/dist/skill/docs/compiler/definitions/validation.md +35 -0
  38. package/dist/skill/docs/compiler/definitions/views.md +292 -0
  39. package/dist/skill/docs/compiler/getting-started/claude-code.md +126 -0
  40. package/dist/skill/docs/compiler/getting-started/full-example.md +431 -0
  41. package/dist/skill/docs/compiler/getting-started/hand-crafted.md +178 -0
  42. package/dist/skill/docs/compiler/getting-started/index.md +192 -0
  43. package/dist/skill/docs/compiler/getting-started/patterns.md +225 -0
  44. package/dist/skill/docs/compiler/getting-started/template-blog.md +280 -0
  45. package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +260 -0
  46. package/dist/skill/docs/compiler/getting-started/template-empty.md +112 -0
  47. package/dist/skill/docs/compiler/getting-started/templates.md +111 -0
  48. package/dist/skill/docs/compiler/index.md +85 -0
  49. package/dist/skill/docs/compiler/targets/hono-api/cloudflare.md +94 -0
  50. package/dist/skill/docs/compiler/targets/hono-api/database/d1.md +246 -0
  51. package/dist/skill/docs/compiler/targets/hono-api/database/index.md +16 -0
  52. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +144 -0
  53. package/dist/skill/docs/compiler/targets/hono-api/database/using-d1.md +39 -0
  54. package/dist/skill/docs/compiler/targets/hono-api/index.md +37 -0
  55. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +323 -0
  56. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +357 -0
  57. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/caching.md +105 -0
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +652 -0
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +224 -0
  60. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/index.md +37 -0
  61. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +203 -0
  62. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +199 -0
  63. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +161 -0
  64. package/dist/skill/docs/compiler/targets/index.md +47 -0
  65. package/dist/skill/docs/compiler/targets/supabase-rls/index.md +55 -0
  66. package/dist/skill/docs/compiler/targets/supabase-rls/limitations.md +48 -0
  67. package/dist/skill/docs/compiler/targets/supabase-rls/mappings.md +99 -0
  68. package/dist/skill/docs/compiler/targets/supabase-rls/setup.md +88 -0
  69. package/dist/skill/docs/compiler/troubleshooting.md +120 -0
  70. package/dist/skill/docs/index.md +77 -0
  71. package/dist/skill/docs/stack/account-ui/customization.md +378 -0
  72. package/dist/skill/docs/stack/account-ui/environment-variables.md +325 -0
  73. package/dist/skill/docs/stack/account-ui/features/admin.md +76 -0
  74. package/dist/skill/docs/stack/account-ui/features/api-keys.md +22 -0
  75. package/dist/skill/docs/stack/account-ui/features/avatars.md +37 -0
  76. package/dist/skill/docs/stack/account-ui/features/cli-authorize.md +21 -0
  77. package/dist/skill/docs/stack/account-ui/features/index.md +291 -0
  78. package/dist/skill/docs/stack/account-ui/features/organizations.md +29 -0
  79. package/dist/skill/docs/stack/account-ui/features/passkeys.md +31 -0
  80. package/dist/skill/docs/stack/account-ui/features/passwordless.md +28 -0
  81. package/dist/skill/docs/stack/account-ui/features/sessions.md +20 -0
  82. package/dist/skill/docs/stack/account-ui/hooks.md +209 -0
  83. package/dist/skill/docs/stack/account-ui/index.md +147 -0
  84. package/dist/skill/docs/stack/account-ui/library-usage.md +257 -0
  85. package/dist/skill/docs/stack/account-ui/standalone.md +149 -0
  86. package/dist/skill/docs/stack/account-ui/with-quickback.md +160 -0
  87. package/dist/skill/docs/stack/account-ui/worker.md +362 -0
  88. package/dist/skill/docs/stack/auth/api-keys.md +15 -0
  89. package/dist/skill/docs/stack/auth/device-auth.md +14 -0
  90. package/dist/skill/docs/stack/auth/index.md +64 -0
  91. package/dist/skill/docs/stack/auth/jwt-optimization.md +245 -0
  92. package/dist/skill/docs/stack/auth/plugins/aws-ses.md +127 -0
  93. package/dist/skill/docs/stack/auth/plugins/combo-auth.md +74 -0
  94. package/dist/skill/docs/stack/auth/plugins/index.md +228 -0
  95. package/dist/skill/docs/stack/auth/plugins/upgrade-anonymous.md +155 -0
  96. package/dist/skill/docs/stack/auth/security.md +455 -0
  97. package/dist/skill/docs/stack/auth/using-auth.md +39 -0
  98. package/dist/skill/docs/stack/cms/actions.md +199 -0
  99. package/dist/skill/docs/stack/cms/components.md +479 -0
  100. package/dist/skill/docs/stack/cms/connecting.md +199 -0
  101. package/dist/skill/docs/stack/cms/dashboard.md +39 -0
  102. package/dist/skill/docs/stack/cms/index.md +158 -0
  103. package/dist/skill/docs/stack/cms/inline-editing.md +136 -0
  104. package/dist/skill/docs/stack/cms/pages.md +275 -0
  105. package/dist/skill/docs/stack/cms/record-layouts.md +151 -0
  106. package/dist/skill/docs/stack/cms/schema-format.md +437 -0
  107. package/dist/skill/docs/stack/cms/schema-registry.md +200 -0
  108. package/dist/skill/docs/stack/cms/security.md +203 -0
  109. package/dist/skill/docs/stack/cms/table-views.md +142 -0
  110. package/dist/skill/docs/stack/index.md +65 -0
  111. package/dist/skill/docs/stack/queues/handlers.md +317 -0
  112. package/dist/skill/docs/stack/queues/index.md +56 -0
  113. package/dist/skill/docs/stack/queues/using-queues.md +192 -0
  114. package/dist/skill/docs/stack/realtime/durable-objects.md +488 -0
  115. package/dist/skill/docs/stack/realtime/index.md +67 -0
  116. package/dist/skill/docs/stack/realtime/using-realtime.md +211 -0
  117. package/dist/skill/docs/stack/storage/index.md +17 -0
  118. package/dist/skill/docs/stack/storage/kv.md +204 -0
  119. package/dist/skill/docs/stack/storage/r2.md +232 -0
  120. package/dist/skill/docs/stack/storage/using-kv.md +70 -0
  121. package/dist/skill/docs/stack/storage/using-r2.md +55 -0
  122. package/dist/skill/docs/stack/vector/embeddings.md +554 -0
  123. package/dist/skill/docs/stack/vector/index.md +44 -0
  124. package/dist/skill/docs/stack/vector/using-embeddings.md +186 -0
  125. package/dist/skill/docs/stack/webhooks/inbound.md +186 -0
  126. package/dist/skill/docs/stack/webhooks/index.md +36 -0
  127. package/dist/skill/docs/stack/webhooks/outbound.md +281 -0
  128. package/package.json +1 -1
  129. package/src/skill/SKILL.md +142 -1051
  130. package/src/skill/agents/quickback-specialist/AGENT.md +36 -0
  131. package/src/skill/docs/changelog.md +1192 -0
  132. package/src/skill/docs/compiler/claude-code-skill.md +312 -0
  133. package/src/skill/docs/compiler/cloud-compiler/authentication.md +63 -0
  134. package/src/skill/docs/compiler/cloud-compiler/cli.md +307 -0
  135. package/src/skill/docs/compiler/cloud-compiler/endpoints.md +78 -0
  136. package/src/skill/docs/compiler/cloud-compiler/index.md +65 -0
  137. package/src/skill/docs/compiler/cloud-compiler/local-compiler.md +115 -0
  138. package/src/skill/docs/compiler/cloud-compiler/troubleshooting.md +76 -0
  139. package/src/skill/docs/compiler/config/agents.md +144 -0
  140. package/src/skill/docs/compiler/config/auth.md +109 -0
  141. package/src/skill/docs/compiler/config/bindings.md +176 -0
  142. package/src/skill/docs/compiler/config/domains.md +149 -0
  143. package/src/skill/docs/compiler/config/index.md +419 -0
  144. package/src/skill/docs/compiler/config/output.md +338 -0
  145. package/src/skill/docs/compiler/config/providers.md +248 -0
  146. package/src/skill/docs/compiler/config/security.md +255 -0
  147. package/src/skill/docs/compiler/config/single-tenant.md +128 -0
  148. package/src/skill/docs/compiler/config/variables.md +157 -0
  149. package/src/skill/docs/compiler/definitions/access.md +445 -0
  150. package/src/skill/docs/compiler/definitions/actions.md +884 -0
  151. package/src/skill/docs/compiler/definitions/concepts.md +52 -0
  152. package/src/skill/docs/compiler/definitions/feature.md +164 -0
  153. package/src/skill/docs/compiler/definitions/firewall.md +285 -0
  154. package/src/skill/docs/compiler/definitions/guards.md +241 -0
  155. package/src/skill/docs/compiler/definitions/index.md +219 -0
  156. package/src/skill/docs/compiler/definitions/masking.md +241 -0
  157. package/src/skill/docs/compiler/definitions/read.md +220 -0
  158. package/src/skill/docs/compiler/definitions/schema.md +697 -0
  159. package/src/skill/docs/compiler/definitions/validation.md +35 -0
  160. package/src/skill/docs/compiler/definitions/views.md +292 -0
  161. package/src/skill/docs/compiler/getting-started/claude-code.md +126 -0
  162. package/src/skill/docs/compiler/getting-started/full-example.md +431 -0
  163. package/src/skill/docs/compiler/getting-started/hand-crafted.md +178 -0
  164. package/src/skill/docs/compiler/getting-started/index.md +192 -0
  165. package/src/skill/docs/compiler/getting-started/patterns.md +225 -0
  166. package/src/skill/docs/compiler/getting-started/template-blog.md +280 -0
  167. package/src/skill/docs/compiler/getting-started/template-cloudflare.md +260 -0
  168. package/src/skill/docs/compiler/getting-started/template-empty.md +112 -0
  169. package/src/skill/docs/compiler/getting-started/templates.md +111 -0
  170. package/src/skill/docs/compiler/index.md +85 -0
  171. package/src/skill/docs/compiler/targets/hono-api/cloudflare.md +94 -0
  172. package/src/skill/docs/compiler/targets/hono-api/database/d1.md +246 -0
  173. package/src/skill/docs/compiler/targets/hono-api/database/index.md +16 -0
  174. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +144 -0
  175. package/src/skill/docs/compiler/targets/hono-api/database/using-d1.md +39 -0
  176. package/src/skill/docs/compiler/targets/hono-api/index.md +37 -0
  177. package/src/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +323 -0
  178. package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +357 -0
  179. package/src/skill/docs/compiler/targets/hono-api/using-the-api/caching.md +105 -0
  180. package/src/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +652 -0
  181. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +224 -0
  182. package/src/skill/docs/compiler/targets/hono-api/using-the-api/index.md +37 -0
  183. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +203 -0
  184. package/src/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +199 -0
  185. package/src/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +161 -0
  186. package/src/skill/docs/compiler/targets/index.md +47 -0
  187. package/src/skill/docs/compiler/targets/supabase-rls/index.md +55 -0
  188. package/src/skill/docs/compiler/targets/supabase-rls/limitations.md +48 -0
  189. package/src/skill/docs/compiler/targets/supabase-rls/mappings.md +99 -0
  190. package/src/skill/docs/compiler/targets/supabase-rls/setup.md +88 -0
  191. package/src/skill/docs/compiler/troubleshooting.md +120 -0
  192. package/src/skill/docs/index.md +77 -0
  193. package/src/skill/docs/stack/account-ui/customization.md +378 -0
  194. package/src/skill/docs/stack/account-ui/environment-variables.md +325 -0
  195. package/src/skill/docs/stack/account-ui/features/admin.md +76 -0
  196. package/src/skill/docs/stack/account-ui/features/api-keys.md +22 -0
  197. package/src/skill/docs/stack/account-ui/features/avatars.md +37 -0
  198. package/src/skill/docs/stack/account-ui/features/cli-authorize.md +21 -0
  199. package/src/skill/docs/stack/account-ui/features/index.md +291 -0
  200. package/src/skill/docs/stack/account-ui/features/organizations.md +29 -0
  201. package/src/skill/docs/stack/account-ui/features/passkeys.md +31 -0
  202. package/src/skill/docs/stack/account-ui/features/passwordless.md +28 -0
  203. package/src/skill/docs/stack/account-ui/features/sessions.md +20 -0
  204. package/src/skill/docs/stack/account-ui/hooks.md +209 -0
  205. package/src/skill/docs/stack/account-ui/index.md +147 -0
  206. package/src/skill/docs/stack/account-ui/library-usage.md +257 -0
  207. package/src/skill/docs/stack/account-ui/standalone.md +149 -0
  208. package/src/skill/docs/stack/account-ui/with-quickback.md +160 -0
  209. package/src/skill/docs/stack/account-ui/worker.md +362 -0
  210. package/src/skill/docs/stack/auth/api-keys.md +15 -0
  211. package/src/skill/docs/stack/auth/device-auth.md +14 -0
  212. package/src/skill/docs/stack/auth/index.md +64 -0
  213. package/src/skill/docs/stack/auth/jwt-optimization.md +245 -0
  214. package/src/skill/docs/stack/auth/plugins/aws-ses.md +127 -0
  215. package/src/skill/docs/stack/auth/plugins/combo-auth.md +74 -0
  216. package/src/skill/docs/stack/auth/plugins/index.md +228 -0
  217. package/src/skill/docs/stack/auth/plugins/upgrade-anonymous.md +155 -0
  218. package/src/skill/docs/stack/auth/security.md +455 -0
  219. package/src/skill/docs/stack/auth/using-auth.md +39 -0
  220. package/src/skill/docs/stack/cms/actions.md +199 -0
  221. package/src/skill/docs/stack/cms/components.md +479 -0
  222. package/src/skill/docs/stack/cms/connecting.md +199 -0
  223. package/src/skill/docs/stack/cms/dashboard.md +39 -0
  224. package/src/skill/docs/stack/cms/index.md +158 -0
  225. package/src/skill/docs/stack/cms/inline-editing.md +136 -0
  226. package/src/skill/docs/stack/cms/pages.md +275 -0
  227. package/src/skill/docs/stack/cms/record-layouts.md +151 -0
  228. package/src/skill/docs/stack/cms/schema-format.md +437 -0
  229. package/src/skill/docs/stack/cms/schema-registry.md +200 -0
  230. package/src/skill/docs/stack/cms/security.md +203 -0
  231. package/src/skill/docs/stack/cms/table-views.md +142 -0
  232. package/src/skill/docs/stack/index.md +65 -0
  233. package/src/skill/docs/stack/queues/handlers.md +317 -0
  234. package/src/skill/docs/stack/queues/index.md +56 -0
  235. package/src/skill/docs/stack/queues/using-queues.md +192 -0
  236. package/src/skill/docs/stack/realtime/durable-objects.md +488 -0
  237. package/src/skill/docs/stack/realtime/index.md +67 -0
  238. package/src/skill/docs/stack/realtime/using-realtime.md +211 -0
  239. package/src/skill/docs/stack/storage/index.md +17 -0
  240. package/src/skill/docs/stack/storage/kv.md +204 -0
  241. package/src/skill/docs/stack/storage/r2.md +232 -0
  242. package/src/skill/docs/stack/storage/using-kv.md +70 -0
  243. package/src/skill/docs/stack/storage/using-r2.md +55 -0
  244. package/src/skill/docs/stack/vector/embeddings.md +554 -0
  245. package/src/skill/docs/stack/vector/index.md +44 -0
  246. package/src/skill/docs/stack/vector/using-embeddings.md +186 -0
  247. package/src/skill/docs/stack/webhooks/inbound.md +186 -0
  248. package/src/skill/docs/stack/webhooks/index.md +36 -0
  249. package/src/skill/docs/stack/webhooks/outbound.md +281 -0
@@ -0,0 +1,884 @@
1
+ # Actions
2
+
3
+ Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.
4
+
5
+ ## Overview
6
+
7
+ Quickback supports two types of actions:
8
+
9
+ | Aspect | Record-Based | Standalone |
10
+ |--------|--------------|------------|
11
+ | Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |
12
+ | Record fetching | Automatic | None (`record` is `undefined`) |
13
+ | Firewall applied | Yes | No |
14
+ | Preconditions | Supported via `access.record` | Not applicable |
15
+ | Response types | JSON only | JSON, stream, file |
16
+ | Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |
17
+
18
+ Standalone 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.
19
+
20
+ ## Where do actions live?
21
+
22
+ **One file per action.** Each action is its own module under the feature's
23
+ `actions/` directory:
24
+
25
+ ```
26
+ features/applications/
27
+ ├── applications.ts ← defineTable (primary table)
28
+ ├── candidates.ts ← defineTable (sibling table)
29
+ ├── actions/
30
+ │ ├── advance.ts ← defineAction, binds to applications
31
+ │ ├── reject.ts ← defineAction, binds to applications
32
+ │ ├── stats.ts ← defineAction, standalone (has `path:`)
33
+ │ └── candidates/
34
+ │ └── disqualify.ts ← defineAction, binds to candidates
35
+ └── lib/
36
+ └── inputs.ts ← shared schemas (optional, copied verbatim)
37
+ ```
38
+
39
+ | Layout | Binds to |
40
+ |--------|----------|
41
+ | `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |
42
+ | `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |
43
+
44
+ The action's filename (sans `.ts`) is the action name and the URL segment.
45
+ Uniqueness is enforced per `(bound table, name)` pair — sibling-bound
46
+ actions on **different** tables may share a verb (`actions/episodes/publish.ts`
47
+ and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and
48
+ `/shows/:id/publish` and compile cleanly). The compiler errors only when
49
+ two action files would mount at the same URL — for example, a flat
50
+ `actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or
51
+ two standalones with the same `(method, path)`. Standalone actions are
52
+ unique per `(method, path)`.
53
+
54
+ Tableless features have no top-level `*.ts` files; every action under
55
+ `actions/` must be standalone (have `path:`). Use this for utility endpoints
56
+ like webhooks, reports, or integrations that don't operate on a specific
57
+ record.
58
+
59
+ ### Retired layouts
60
+
61
+ These are rejected at load time with migration guidance:
62
+
63
+ - **`actions.ts`** (bundled multi-action file)
64
+ - **`_feature.ts`** (shared schemas + non-table-bound actions)
65
+ - **`handlers/`** (separate handler-file directory)
66
+ - **`defineActions(table, {...})`** (the multi-action factory)
67
+ - **`defineActions(null, {...})`** (tableless variant)
68
+ - **`*-actions.ts` / `*.actions.ts`** filename patterns
69
+
70
+ For shared Zod schemas or helpers, put them under `<feature>/lib/` and import
71
+ from each action file. Files under `lib/` are copied verbatim into the
72
+ generated output.
73
+
74
+ ## Defining Actions
75
+
76
+ ```typescript
77
+ // features/applications/actions/advance.ts
78
+ import { z } from "zod";
79
+ import { eq } from "drizzle-orm";
80
+ import { defineAction } from "../.quickback/define-action";
81
+ import { applications } from "../applications";
82
+
83
+ export default defineAction({
84
+ description: "Move an application forward in the pipeline.",
85
+ input: z.object({
86
+ nextStatus: z.enum(["screening", "interview", "offer"]),
87
+ notes: z.string().max(2000).optional(),
88
+ }),
89
+ access: { roles: ["owner", "admin"] },
90
+ transition: {
91
+ field: "status",
92
+ via: "nextStatus",
93
+ fromTo: {
94
+ applied: ["screening"],
95
+ screening: ["interview"],
96
+ interview: ["offer"],
97
+ },
98
+ },
99
+ async execute({ db, record, input, whereTransition }) {
100
+ const [updated] = await db
101
+ .update(applications)
102
+ .set({
103
+ status: input.nextStatus,
104
+ notes: input.notes ?? record.notes,
105
+ })
106
+ .where(whereTransition!(applications))
107
+ .returning();
108
+ return updated;
109
+ },
110
+ });
111
+ ```
112
+
113
+ > **`defineAction` import.** Import from `"../.quickback/define-action"` —
114
+ > the `.quickback/` directory is generated alongside your feature with a
115
+ > typed helper that infers `record` and `input` types from the rest of the
116
+ > action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,
117
+ > `modifiedBy`) are hard-stamped by the audit DB wrapper on every
118
+ > `db.insert().values()` and `db.update().set()` — handlers don't pass
119
+ > them and can't override them.
120
+
121
+ ### Configuration Options
122
+
123
+ | Option | Required | Description |
124
+ |--------|----------|-------------|
125
+ | `description` | Yes | Human-readable description of the action |
126
+ | `input` | Yes | Zod schema for request validation |
127
+ | `access` | Yes | Access control (roles, record conditions, or function) |
128
+ | `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
129
+ | `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |
130
+ | `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST) |
131
+ | `responseType` | No | Response format: json, stream, file (default: json) |
132
+ | `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |
133
+ | `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |
134
+ | `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |
135
+ | `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |
136
+ | `cms` | No | Pass-through metadata blob for CMS surfaces |
137
+
138
+ `execute` must be an `async (ctx) => { … }` arrow function. `async function`
139
+ declarations and non-async forms are rejected at parse time.
140
+
141
+ ## Record-Based Actions
142
+
143
+ Record-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.
144
+
145
+ **Route pattern:** `{METHOD} /:id/{actionName}`
146
+
147
+ ```
148
+ POST /applications/:id/advance
149
+ POST /applications/:id/reject
150
+ POST /applications/:id/schedule-interview
151
+ ```
152
+
153
+ ### Runtime Flow
154
+
155
+ 1. **Authentication** - User token is validated
156
+ 2. **Record Loading** - The record is fetched by ID
157
+ 3. **Firewall Check** - Ensures user can access this record
158
+ 4. **Access Check** - Validates roles and preconditions
159
+ 5. **Input Validation** - Request body validated against Zod schema
160
+ 6. **Execution** - Your action handler runs
161
+ 7. **Response** - Result is returned to client
162
+
163
+ ### Example: Advance Application Stage
164
+
165
+ ```typescript
166
+ // features/applications/actions/advance.ts
167
+ import { z } from "zod";
168
+ import { eq } from "drizzle-orm";
169
+ import { defineAction } from "../.quickback/define-action";
170
+ import { applications } from "../applications";
171
+
172
+ export default defineAction({
173
+ description: "Move application to the next pipeline stage",
174
+ input: z.object({
175
+ stage: z.enum(["screening", "interview", "offer", "hired"]),
176
+ notes: z.string().optional(),
177
+ }),
178
+ access: {
179
+ roles: ["owner", "hiring-manager"],
180
+ record: { stage: { notEquals: "rejected" } },
181
+ },
182
+ async execute({ db, record, input }) {
183
+ const [updated] = await db
184
+ .update(applications)
185
+ .set({
186
+ stage: input.stage,
187
+ notes: input.notes ?? record.notes,
188
+ })
189
+ .where(eq(applications.id, record.id))
190
+ .returning();
191
+ return updated;
192
+ },
193
+ });
194
+ ```
195
+
196
+ ### Request Example
197
+
198
+ ```
199
+ POST /applications/app_123/advance
200
+ Content-Type: application/json
201
+
202
+ {
203
+ "stage": "interview",
204
+ "notes": "Strong technical background, moving to interview"
205
+ }
206
+ ```
207
+
208
+ ### Response Example
209
+
210
+ ```json
211
+ {
212
+ "data": {
213
+ "id": "app_123",
214
+ "stage": "interview",
215
+ "notes": "Strong technical background, moving to interview"
216
+ }
217
+ }
218
+ ```
219
+
220
+ ## Standalone Actions
221
+
222
+ Standalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.
223
+
224
+ **Route pattern:** Custom `path`
225
+
226
+ ```
227
+ POST /chat
228
+ GET /reports/summary
229
+ POST /webhooks/stripe
230
+ ```
231
+
232
+ ### Example: AI Chat with Streaming
233
+
234
+ ```typescript
235
+ // features/sessions/actions/chat.ts
236
+ import { z } from "zod";
237
+ import { defineAction } from "../.quickback/define-action";
238
+
239
+ export default defineAction({
240
+ description: "Send a message to AI",
241
+ path: "/chat",
242
+ method: "POST",
243
+ responseType: "stream",
244
+ input: z.object({
245
+ message: z.string().min(1).max(2000),
246
+ }),
247
+ access: { roles: ["recruiter", "hiring-manager"] },
248
+ async execute({ input, c }) {
249
+ // Stream response back to client...
250
+ return c.newResponse(/* ReadableStream */);
251
+ },
252
+ });
253
+ ```
254
+
255
+ ### Streaming Response Example
256
+
257
+ For actions with `responseType: 'stream'`:
258
+
259
+ ```
260
+ Content-Type: text/event-stream
261
+
262
+ data: {"type": "start"}
263
+ data: {"type": "chunk", "content": "Hello"}
264
+ data: {"type": "chunk", "content": "! I'm"}
265
+ data: {"type": "chunk", "content": " here to help."}
266
+ data: {"type": "done"}
267
+ ```
268
+
269
+ ### Tableless Features
270
+
271
+ A feature directory with no top-level `*.ts` files is "tableless" — every
272
+ action under `actions/` must be standalone. Use this for utility endpoints
273
+ like reports, integrations, or webhooks that don't map to a specific
274
+ resource.
275
+
276
+ ```
277
+ quickback/features/
278
+ └── reports/
279
+ └── actions/
280
+ ├── trial-balance.ts ← standalone (has path:)
281
+ └── profit-loss.ts ← standalone (has path:)
282
+ ```
283
+
284
+ ```typescript
285
+ // features/reports/actions/trial-balance.ts
286
+ import { z } from "zod";
287
+ import { defineAction } from "../.quickback/define-action";
288
+
289
+ export default defineAction({
290
+ description: "Generate trial balance report",
291
+ path: "/reports/trial-balance",
292
+ method: "GET",
293
+ input: z.object({
294
+ startDate: z.string(),
295
+ endDate: z.string(),
296
+ }),
297
+ access: { roles: ["admin", "accountant"] },
298
+ async execute({ db, input }) {
299
+ // ... build report
300
+ return { rows: [] };
301
+ },
302
+ });
303
+ ```
304
+
305
+ ## Access Configuration
306
+
307
+ Access controls who can execute an action and under what conditions.
308
+
309
+ ### Role-Based Access
310
+
311
+ ```typescript
312
+ access: {
313
+ roles: ["hiring-manager", "recruiter"] // OR logic: user needs any of these roles
314
+ }
315
+ ```
316
+
317
+ ### Public Access
318
+
319
+ Use `roles: ["PUBLIC"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.
320
+
321
+ ```typescript
322
+ // features/contact/actions/submit.ts
323
+ import { z } from "zod";
324
+ import { defineAction } from "../.quickback/define-action";
325
+
326
+ export default defineAction({
327
+ description: "Public contact form submission",
328
+ path: "/submit",
329
+ input: z.object({
330
+ name: z.string().min(1),
331
+ email: z.string().email(),
332
+ message: z.string().min(10),
333
+ }),
334
+ access: { roles: ["PUBLIC"] },
335
+ async execute({ db, input }) {
336
+ // ... persist submission
337
+ return { ok: true };
338
+ },
339
+ });
340
+ ```
341
+
342
+ The wildcard `"*"` is not supported and will throw a compile-time error. Use `"PUBLIC"` explicitly.
343
+
344
+ ### Record Conditions
345
+
346
+ For record-based actions, you can require the record to be in a specific state:
347
+
348
+ ```typescript
349
+ access: {
350
+ roles: ["hiring-manager"],
351
+ record: {
352
+ stage: { equals: "screening" } // Precondition
353
+ }
354
+ }
355
+ ```
356
+
357
+ **Supported operators:**
358
+
359
+ | Operator | Description |
360
+ |----------|-------------|
361
+ | `equals` | Field must equal value |
362
+ | `notEquals` | Field must not equal value |
363
+ | `in` | Field must be one of the values |
364
+ | `notIn` | Field must not be one of the values |
365
+
366
+ ### Context Substitution
367
+
368
+ Use `$ctx` to reference the current user's context:
369
+
370
+ ```typescript
371
+ access: {
372
+ record: {
373
+ ownerId: { equals: "$ctx.userId" },
374
+ orgId: { equals: "$ctx.orgId" }
375
+ }
376
+ }
377
+ ```
378
+
379
+ ### OR/AND Combinations
380
+
381
+ ```typescript
382
+ access: {
383
+ or: [
384
+ { roles: ["hiring-manager"] },
385
+ {
386
+ roles: ["recruiter"],
387
+ record: { ownerId: { equals: "$ctx.userId" } }
388
+ }
389
+ ]
390
+ }
391
+ ```
392
+
393
+ ### Function Access
394
+
395
+ For complex logic, use an access function:
396
+
397
+ ```typescript
398
+ access: async (ctx, record) => {
399
+ return ctx.roles.includes('admin') || record.ownerId === ctx.userId;
400
+ }
401
+ ```
402
+
403
+ ## Scoped Database
404
+
405
+ All actions receive a **scoped `db`** instance that automatically enforces security:
406
+
407
+ | Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |
408
+ |-----------|-------------|---------------|--------------------|-----------------------|
409
+ | `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |
410
+ | `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |
411
+ | `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |
412
+ | `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |
413
+
414
+ Scoping 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.
415
+
416
+ ```typescript
417
+ async execute({ db, ctx, input }) {
418
+ // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL
419
+ const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));
420
+
421
+ // Inserts automatically include organizationId
422
+ await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });
423
+
424
+ return items;
425
+ }
426
+ ```
427
+
428
+ **Not enforced** in scoped DB (by design):
429
+ - **Guards** — actions ARE the authorized way to modify guarded fields
430
+ - **Masking** — actions are backend code that may need raw data
431
+ - **Access** — already checked before action execution
432
+
433
+ ### Unsafe Mode
434
+
435
+ Actions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.
436
+
437
+ Use object form for explicit policy and mandatory audit metadata:
438
+
439
+ ```typescript
440
+ // features/admin/actions/cross-tenant-report.ts
441
+ import { z } from "zod";
442
+ import { defineAction } from "../.quickback/define-action";
443
+ import { applications } from "../../applications/applications";
444
+
445
+ export default defineAction({
446
+ description: "Generate cross-org hiring report",
447
+ path: "/admin/cross-tenant-report",
448
+ input: z.object({ startDate: z.string() }),
449
+ access: { roles: ["owner"] },
450
+ unsafe: {
451
+ reason: "Support investigation for enterprise customer",
452
+ adminOnly: true, // default true
453
+ crossTenant: true, // default true
454
+ targetScope: "all", // "all" | "organization"
455
+ },
456
+ async execute({ unsafeDb, input }) {
457
+ // unsafeDb bypasses scoped filters
458
+ const allOrgs = await unsafeDb.select().from(applications);
459
+ return allOrgs;
460
+ },
461
+ });
462
+ ```
463
+
464
+ Unsafe cross-tenant actions are generated with:
465
+
466
+ - Better Auth authentication required (no unauthenticated path)
467
+ - platform admin gate (`ctx.userRole === "admin"`)
468
+ - mandatory audit logging on deny/success/error
469
+
470
+ `PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.
471
+
472
+ Without unsafe mode, `unsafeDb` is `undefined` in the executor params.
473
+
474
+ ### Raw SQL Policy
475
+
476
+ By default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.
477
+
478
+ If a specific action must use raw SQL, opt in explicitly:
479
+
480
+ ```typescript
481
+ // features/ledgers/actions/reconcile.ts
482
+ import { z } from "zod";
483
+ import { sql } from "drizzle-orm";
484
+ import { defineAction } from "../.quickback/define-action";
485
+
486
+ export default defineAction({
487
+ description: "Run custom reconciliation query",
488
+ input: z.object({}),
489
+ access: { roles: ["owner"] },
490
+ allowRawSql: true,
491
+ async execute({ db }) {
492
+ return db.execute(sql`select 1`);
493
+ },
494
+ });
495
+ ```
496
+
497
+ Without `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.
498
+
499
+ The 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.
500
+
501
+ ## Sharing Code Between Actions
502
+
503
+ For Zod schemas, helpers, or constants used across multiple actions in a
504
+ feature, put them under `<feature>/lib/` and import from each action file.
505
+ Files under `lib/` are copied verbatim into the generated output.
506
+
507
+ ```
508
+ features/applications/
509
+ ├── applications.ts
510
+ ├── actions/
511
+ │ ├── advance.ts
512
+ │ └── reject.ts
513
+ └── lib/
514
+ ├── inputs.ts ← shared Zod schemas
515
+ └── transitions.ts ← state-machine helpers
516
+ ```
517
+
518
+ ```typescript
519
+ // features/applications/lib/inputs.ts
520
+ import { z } from "zod";
521
+
522
+ export const advanceInput = z.object({
523
+ nextStatus: z.enum(["screening", "interview", "offer"]),
524
+ notes: z.string().max(2000).optional(),
525
+ });
526
+ ```
527
+
528
+ ```typescript
529
+ // features/applications/actions/advance.ts
530
+ import { defineAction } from "../.quickback/define-action";
531
+ import { advanceInput } from "../lib/inputs";
532
+
533
+ export default defineAction({
534
+ description: "Move forward",
535
+ input: advanceInput,
536
+ access: { roles: ["owner"] },
537
+ async execute({ db, record, input }) { /* … */ },
538
+ });
539
+ ```
540
+
541
+ ### Importing Tables
542
+
543
+ Action 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:
544
+
545
+ ```typescript
546
+ // features/applications/actions/advance.ts
547
+ import { eq, and } from "drizzle-orm";
548
+
549
+ // Same feature — import from parent directory using the table's file name
550
+ import { applications } from "../applications";
551
+ import { interviewScores } from "../interview-scores";
552
+
553
+ // Cross-feature — go up to the features directory, then into the other feature
554
+ import { candidates } from "../../candidates/candidates";
555
+ import { jobs } from "../../jobs/jobs";
556
+ ```
557
+
558
+ **Path pattern from `features/{name}/actions/`:**
559
+ - Same feature table: `../{table-file-name}` (e.g., `../applications`)
560
+ - Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)
561
+ - Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)
562
+
563
+ ### Executor Parameters
564
+
565
+ ```typescript
566
+ import type { Auth } from "better-auth";
567
+
568
+ interface ActionExecutorParams {
569
+ db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)
570
+ unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)
571
+ ctx: AppContext; // User context (userId, roles, orgId)
572
+ record?: TRecord; // The record (record-based only, undefined for standalone)
573
+ input: TInput; // Validated input from Zod schema
574
+ services: TServices; // Configured integrations (billing, notifications, etc.)
575
+ c: HonoContext; // Raw Hono context for advanced use
576
+ env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.
577
+ auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.
578
+ whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.
579
+ whereTransition?: (table) => SQL; // whereRecord plus the transition's "from" precondition. Transition actions only.
580
+ }
581
+ ```
582
+
583
+ #### `auth` — Better Auth instance
584
+
585
+ `auth` is the Better Auth instance, ready to call from inside an action
586
+ handler. Use it for things like minting an OAuth access token, fetching the
587
+ current session in a custom way, or invoking a Better Auth plugin method
588
+ that isn't already exposed by the generated middleware.
589
+
590
+ ```typescript
591
+ // features/integrations/actions/connect-google-drive.ts
592
+ import { defineAction } from "../.quickback/define-action";
593
+ import { z } from "zod";
594
+
595
+ export default defineAction({
596
+ description: "Get a fresh Google Drive access token for the signed-in user",
597
+ input: z.object({}),
598
+ access: { roles: ["AUTHENTICATED"] },
599
+ async execute({ auth, ctx, c }) {
600
+ // genericOAuth plugin method — needs a cast since the default-generic
601
+ // `Auth` type doesn't carry plugin-specific API surface.
602
+ const token = await (auth.api as any).getAccessToken({
603
+ headers: c.req.raw.headers,
604
+ body: { providerId: "google", userId: ctx.userId },
605
+ });
606
+ return { accessToken: token.accessToken };
607
+ },
608
+ });
609
+ ```
610
+
611
+ **Lazy on Cloudflare**: the generated handler emits a `Proxy` so
612
+ `createAuth(c.env, c.req.raw.cf)` only runs the first time you read a
613
+ property on `auth`. Actions that never touch `auth` pay zero construction
614
+ cost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads
615
+ the database adapter) wrapped in the same proxy shape — call sites are
616
+ identical across runtimes.
617
+
618
+ **Typing**: `auth` is typed as `Auth` from `better-auth`. The base API
619
+ (`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only
620
+ methods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)
621
+ need a cast at the call site — the default-generic `Auth` doesn't infer
622
+ the project's specific plugin set.
623
+
624
+ #### `whereRecord` — explicit, scope-safe WHERE
625
+
626
+ For protected-field writes inside record-based actions, prefer
627
+ `whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle
628
+ expression that AND-merges the resource's firewall and soft-delete predicates
629
+ with the record id, so the WHERE is explicit even if a future refactor swaps
630
+ `db` back to an unscoped client:
631
+
632
+ ```typescript
633
+ // features/applications/actions/advance.ts
634
+ import { defineAction } from "../.quickback/define-action";
635
+ import { applications } from "../applications";
636
+
637
+ export default defineAction({
638
+ description: "Advance",
639
+ input: /* … */,
640
+ access: { roles: ["owner"] },
641
+ async execute({ db, record, input, whereRecord }) {
642
+ const [updated] = await db
643
+ .update(applications)
644
+ .set({
645
+ status: input.nextStatus,
646
+ notes: input.notes ?? record.notes,
647
+ })
648
+ .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one
649
+ .returning();
650
+ return updated;
651
+ },
652
+ });
653
+ ```
654
+
655
+ The audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every
656
+ `.set()` call, so handlers don't write them. The same wrapper hard-stamps
657
+ `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.
658
+ Caller-supplied audit fields are dropped on the floor — the audit log
659
+ always reflects the real actor and the real moment.
660
+
661
+ `whereRecord` is undefined for standalone actions (they have no record), so
662
+ the parameter is typed as optional. `whereTransition` extends `whereRecord`
663
+ with the transition's "from" precondition for transition actions.
664
+
665
+ ## HTTP API Reference
666
+
667
+ ### Request Format
668
+
669
+ | Method | Input Source | Use Case |
670
+ |--------|--------------|----------|
671
+ | `GET` | Query parameters | Read-only operations, fetching data |
672
+ | `POST` | JSON body | Default, state-changing operations |
673
+ | `PUT` | JSON body | Full replacement operations |
674
+ | `PATCH` | JSON body | Partial updates |
675
+ | `DELETE` | JSON body | Deletion with optional payload |
676
+
677
+ ### Response Formats
678
+
679
+ | Type | Content-Type | Use Case |
680
+ |------|--------------|----------|
681
+ | `json` | `application/json` | Standard API responses (default) |
682
+ | `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |
683
+ | `file` | Varies | File downloads (reports, exports) |
684
+
685
+ ### Error Codes
686
+
687
+ | Status | Description |
688
+ |--------|-------------|
689
+ | `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |
690
+ | `401` | Not authenticated |
691
+ | `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |
692
+ | `404` | Record not found (record-based actions) |
693
+ | `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |
694
+ | `500` | Handler execution error |
695
+
696
+ ### Validation Error Response
697
+
698
+ ```json
699
+ {
700
+ "error": "Invalid request data",
701
+ "layer": "validation",
702
+ "code": "VALIDATION_FAILED",
703
+ "details": {
704
+ "fields": {
705
+ "amount": "Expected positive number"
706
+ }
707
+ },
708
+ "hint": "Check the input schema for this action"
709
+ }
710
+ ```
711
+
712
+ ### Error Handling
713
+
714
+ **Option 1: Return a JSON error response** (recommended for most cases)
715
+
716
+ Since action handlers receive the Hono context (`c`), you can return error responses directly:
717
+
718
+ ```typescript
719
+ async execute({ ctx, record, input, c }) {
720
+ if (record.stage === 'hired') {
721
+ return c.json({
722
+ error: 'Cannot modify a hired application',
723
+ code: 'ALREADY_HIRED',
724
+ details: { currentStage: record.stage },
725
+ }, 400);
726
+ }
727
+ // ... continue
728
+ }
729
+ ```
730
+
731
+ **Option 2: Throw an ActionError**
732
+
733
+ ```typescript
734
+ import { ActionError } from "@quickback/types";
735
+
736
+ async execute({ ctx, record, input }) {
737
+ if (record.stage === 'hired') {
738
+ throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {
739
+ currentStage: record.stage,
740
+ });
741
+ }
742
+ // ... continue
743
+ }
744
+ ```
745
+
746
+ The `ActionError` constructor signature is `(message, code, statusCode, details?)`.
747
+
748
+ ## Protected Fields
749
+
750
+ Actions can modify fields that are protected from regular CRUD operations:
751
+
752
+ ```typescript
753
+ // In the table file (defineTable config)
754
+ guards: {
755
+ protected: {
756
+ status: ["advance", "reject", "hire", "withdraw"], // Only these actions can modify status
757
+ }
758
+ }
759
+ ```
760
+
761
+ This 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.
762
+
763
+ ## Transition (state-machine policy)
764
+
765
+ For protected fields that follow a state machine — application status, invoice
766
+ lifecycle, order fulfilment — use `transition` on the action so the compiler
767
+ generates a runtime guard that enforces the *from/to pair*, not just the
768
+ current state. Without it, an `advance` action whose input enum allows
769
+ `["screening", "interview", "offer"]` and whose `access.record` allows
770
+ `status in ["applied", "screening", "interview"]` will happily run
771
+ `applied → offer` (a skip) or `interview → screening` (a regression).
772
+
773
+ ```typescript
774
+ // features/applications/actions/advance.ts
775
+ import { z } from "zod";
776
+ import { defineAction } from "../.quickback/define-action";
777
+ import { applications } from "../applications";
778
+
779
+ export default defineAction({
780
+ description: "Move an application forward in the pipeline.",
781
+ input: z.object({ nextStatus: z.enum(["screening", "interview", "offer"]) }),
782
+ access: { roles: ["owner", "admin"] },
783
+ transition: {
784
+ field: "status",
785
+ via: "nextStatus", // read target from input.nextStatus
786
+ fromTo: {
787
+ applied: ["screening"],
788
+ screening: ["interview"],
789
+ interview: ["offer"],
790
+ },
791
+ },
792
+ async execute({ db, record, input, whereTransition }) { /* … */ },
793
+ });
794
+ ```
795
+
796
+ ```typescript
797
+ // features/applications/actions/hire.ts
798
+ import { z } from "zod";
799
+ import { defineAction } from "../.quickback/define-action";
800
+ import { applications } from "../applications";
801
+
802
+ export default defineAction({
803
+ description: "Finalize an offer.",
804
+ input: z.object({}),
805
+ access: { roles: ["owner"] },
806
+ transition: {
807
+ field: "status",
808
+ to: "hired", // fixed target — same value every call
809
+ fromTo: { offer: ["hired"] },
810
+ },
811
+ async execute({ db, record, whereTransition }) { /* … */ },
812
+ });
813
+ ```
814
+
815
+ | Field | Required | Description |
816
+ |---|---|---|
817
+ | `field` | Yes | Record column to validate (e.g. `"status"`) |
818
+ | `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |
819
+ | `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |
820
+ | `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |
821
+
822
+ Exactly one of `via` or `to` must be provided. The compiler rejects both at
823
+ validate time. When `to` is set, it must appear in some `fromTo[*]` array —
824
+ otherwise the action would be unreachable, which is almost certainly a bug.
825
+
826
+ ### Wire-level errors
827
+
828
+ The compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with
829
+ the field, the current value, the requested target, and the allowed set:
830
+
831
+ ```json
832
+ {
833
+ "error": "Action not allowed for current record state",
834
+ "layer": "access",
835
+ "code": "ACCESS_ACTION_NOT_ALLOWED_FOR_STATE",
836
+ "details": {
837
+ "field": "status",
838
+ "current": "interview",
839
+ "target": "screening",
840
+ "allowedTargets": ["offer"]
841
+ },
842
+ "hint": "From \"interview\", status can transition to: offer"
843
+ }
844
+ ```
845
+
846
+ This is distinct from a role failure: if the caller has the wrong role they
847
+ get **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients
848
+ tell *"you can't do this"* from *"you can't do this *yet*"* — the latter is
849
+ recoverable by the user, the former isn't.
850
+
851
+ The same 409 code is used when an `access.record` predicate (without
852
+ `transition`) fails — for example `record: { status: { equals: "pending" } }`
853
+ called against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,
854
+ not a misleading 403.
855
+
856
+ ## Examples
857
+
858
+ ### Bulk Import (Standalone, No Record)
859
+
860
+ ```typescript
861
+ // features/candidates/actions/bulk-import.ts
862
+ import { z } from "zod";
863
+ import { defineAction } from "../.quickback/define-action";
864
+ import { candidates } from "../candidates";
865
+
866
+ export default defineAction({
867
+ description: "Import candidates from job board CSV",
868
+ path: "/candidates/import",
869
+ input: z.object({
870
+ data: z.array(z.object({
871
+ email: z.string().email(),
872
+ name: z.string(),
873
+ })),
874
+ }),
875
+ access: { roles: ["hiring-manager", "recruiter"] },
876
+ async execute({ db, input }) {
877
+ const inserted = await db
878
+ .insert(candidates)
879
+ .values(input.data)
880
+ .returning();
881
+ return { imported: inserted.length };
882
+ },
883
+ });
884
+ ```