@fabrika/app 0.9.0-dev.4 → 0.9.0-dev.6

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 (113) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +41 -14
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +2 -1
  5. package/skill/references/endpoint.md +30 -24
  6. package/skill/references/errors.md +40 -35
  7. package/skill/references/files.md +4 -2
  8. package/skill/references/jobs.md +21 -4
  9. package/skill/references/table-and-migration.md +19 -2
  10. package/skill/references/tests.md +40 -1
  11. package/skill/references/webhooks-links-connectors.md +1 -1
  12. package/src/build-recipe.ts +198 -0
  13. package/src/build.ts +60 -4
  14. package/src/bun.ts +181 -13
  15. package/src/cloudflare/application.ts +822 -0
  16. package/src/cloudflare/bindings.ts +159 -0
  17. package/src/cloudflare/export.ts +621 -0
  18. package/src/cloudflare/import.ts +1013 -0
  19. package/src/cloudflare/maintenance.ts +518 -0
  20. package/src/cloudflare/names.ts +16 -0
  21. package/src/cloudflare/ops.ts +375 -0
  22. package/src/cloudflare/r2-files.ts +172 -0
  23. package/src/cloudflare/restore.ts +167 -0
  24. package/src/cloudflare/tracker.ts +192 -0
  25. package/src/cloudflare.ts +100 -146
  26. package/src/contract/app-id.ts +5 -0
  27. package/src/contract/artifact-schema.ts +9 -1
  28. package/src/contract/build.ts +40 -2
  29. package/src/contract/compile.ts +1 -0
  30. package/src/contract/context.ts +35 -9
  31. package/src/contract/declaration.ts +2 -0
  32. package/src/contract/defaults.ts +22 -2
  33. package/src/contract/define.ts +29 -3
  34. package/src/contract/kit.ts +4 -1
  35. package/src/contract/platform.ts +3 -2
  36. package/src/contract/vocabulary.ts +26 -8
  37. package/src/dev/launcher.ts +50 -4
  38. package/src/disk-assets.ts +8 -3
  39. package/src/files/archive.ts +2 -2
  40. package/src/files/job-names.ts +12 -0
  41. package/src/files/kinds.ts +73 -31
  42. package/src/files/scan.ts +3 -4
  43. package/src/files/streams.ts +3 -1
  44. package/src/implement/anonymous.ts +12 -11
  45. package/src/implement/boot.ts +75 -6
  46. package/src/implement/bounded.ts +21 -2
  47. package/src/implement/capability.ts +15 -3
  48. package/src/implement/dispatch.ts +419 -177
  49. package/src/implement/failures.ts +17 -1
  50. package/src/implement/faults.ts +1 -0
  51. package/src/implement/index.ts +1 -0
  52. package/src/implement/invocation.ts +58 -10
  53. package/src/implement/principal.ts +25 -2
  54. package/src/implement/terminals.ts +93 -0
  55. package/src/implement/workload.ts +42 -16
  56. package/src/jobs/mail.ts +8 -0
  57. package/src/jobs/report.ts +5 -1
  58. package/src/jobs/runner.ts +672 -113
  59. package/src/jobs/schedule.ts +7 -1
  60. package/src/jobs/scrub.ts +14 -1
  61. package/src/jobs/types.ts +6 -0
  62. package/src/spa-fallback.ts +12 -0
  63. package/src/testing/endpoint-access.ts +307 -152
  64. package/src/testing/isolation.ts +8 -1
  65. package/src/testing/kit.ts +80 -2
  66. package/src/testing/proxy.ts +15 -10
  67. package/types/src/build-recipe.d.ts +70 -0
  68. package/types/src/build.d.ts +19 -1
  69. package/types/src/bun.d.ts +34 -1
  70. package/types/src/cloudflare/application.d.ts +73 -0
  71. package/types/src/cloudflare/bindings.d.ts +33 -0
  72. package/types/src/cloudflare/export.d.ts +16 -0
  73. package/types/src/cloudflare/import.d.ts +51 -0
  74. package/types/src/cloudflare/maintenance.d.ts +117 -0
  75. package/types/src/cloudflare/names.d.ts +11 -0
  76. package/types/src/cloudflare/ops.d.ts +81 -0
  77. package/types/src/cloudflare/r2-files.d.ts +9 -0
  78. package/types/src/cloudflare/restore.d.ts +9 -0
  79. package/types/src/cloudflare/tracker.d.ts +29 -0
  80. package/types/src/cloudflare.d.ts +12 -18
  81. package/types/src/contract/app-id.d.ts +2 -0
  82. package/types/src/contract/artifact-schema.d.ts +2 -0
  83. package/types/src/contract/context.d.ts +35 -11
  84. package/types/src/contract/declaration.d.ts +4 -0
  85. package/types/src/contract/defaults.d.ts +19 -1
  86. package/types/src/contract/define.d.ts +20 -3
  87. package/types/src/contract/kit.d.ts +2 -1
  88. package/types/src/contract/platform.d.ts +2 -2
  89. package/types/src/contract/vocabulary.d.ts +9 -7
  90. package/types/src/disk-assets.d.ts +4 -1
  91. package/types/src/files/job-names.d.ts +9 -0
  92. package/types/src/files/kinds.d.ts +21 -14
  93. package/types/src/files/scan.d.ts +1 -3
  94. package/types/src/implement/anonymous.d.ts +2 -4
  95. package/types/src/implement/boot.d.ts +17 -1
  96. package/types/src/implement/bounded.d.ts +11 -1
  97. package/types/src/implement/capability.d.ts +4 -2
  98. package/types/src/implement/dispatch.d.ts +34 -1
  99. package/types/src/implement/failures.d.ts +5 -0
  100. package/types/src/implement/faults.d.ts +1 -0
  101. package/types/src/implement/index.d.ts +1 -0
  102. package/types/src/implement/invocation.d.ts +22 -7
  103. package/types/src/implement/principal.d.ts +6 -1
  104. package/types/src/implement/terminals.d.ts +33 -0
  105. package/types/src/implement/workload.d.ts +5 -0
  106. package/types/src/jobs/runner.d.ts +66 -2
  107. package/types/src/jobs/schedule.d.ts +2 -0
  108. package/types/src/jobs/types.d.ts +6 -0
  109. package/types/src/spa-fallback.d.ts +2 -0
  110. package/types/src/testing/endpoint-access.d.ts +37 -5
  111. package/types/src/testing/isolation.d.ts +1 -1
  112. package/types/src/testing/kit.d.ts +22 -1
  113. package/types/src/testing/proxy.d.ts +4 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/app",
3
- "version": "0.9.0-dev.4",
3
+ "version": "0.9.0-dev.6",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -109,14 +109,14 @@
109
109
  "test": "bun test --path-ignore-patterns='src/react/**' && bun test --isolate src/react"
110
110
  },
111
111
  "dependencies": {
112
- "@fabrika/auth": "0.9.0-dev.4",
113
- "@fabrika/auth-core": "0.9.0-dev.4",
114
- "@fabrika/db": "0.9.0-dev.4",
115
- "@fabrika/email": "0.9.0-dev.4",
116
- "@fabrika/jwks": "0.9.0-dev.4",
117
- "@fabrika/platform": "0.9.0-dev.4",
118
- "@fabrika/platform-node": "0.9.0-dev.4",
119
- "@fabrika/proxy-core": "0.9.0-dev.4",
112
+ "@fabrika/auth": "0.9.0-dev.6",
113
+ "@fabrika/auth-core": "0.9.0-dev.6",
114
+ "@fabrika/db": "0.9.0-dev.6",
115
+ "@fabrika/email": "0.9.0-dev.6",
116
+ "@fabrika/jwks": "0.9.0-dev.6",
117
+ "@fabrika/platform": "0.9.0-dev.6",
118
+ "@fabrika/platform-node": "0.9.0-dev.6",
119
+ "@fabrika/proxy-core": "0.9.0-dev.6",
120
120
  "altcha-lib": "2.6.0",
121
121
  "jose": "^5.9.0"
122
122
  },
package/skill/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: fabrika-app
3
- version: 0.9.0-dev.4
3
+ version: 0.9.0-dev.6
4
4
  description: >
5
5
  How to write and change a Fabrika application: src/vocabulary.ts, db/migrations/, src/db/tables.ts, the
6
6
  slices' endpoints.ts with their handlers, fabrika.contract.ts, jobs, files, webhooks, share links, connectors
@@ -233,14 +233,15 @@ the access check. `references/spa.md` shows the stack.
233
233
  | an outside HTTPS API | `egress: ['https://api.example.com']` | `fetch` to exactly those origins |
234
234
  | a signed link (unsubscribe) | `signs: ['<purpose>']` | `ctx.tokens.sign` |
235
235
  | a webhook binding | `binds: '<webhook>'` | `ctx.webhooks('<webhook>').bind` and `.unbind` |
236
- | a job run after the commit | `kicks: ['<job>']` | `ctx.kick('<job>')` |
236
+ | a job run after the commit | `kicks: ['<job>']` | `ctx.kick('<job>')`, `ctx.kick('<job>', { at })` |
237
237
  | a trigger, function or view | its migration | — |
238
238
 
239
- Scope every scoped table a raw statement reads with `${ctx.sql.scope(<capability>, '<table>', '<alias>')}`, a conjunct
240
- of its WHERE or JOIN … ON (`where (<filter>) and ${…}`): `ctx.target` for `on` and `in`, `ctx.within` for `over`, a
241
- job's minted `Ref` or `Within` with `tx.sql.scope`. It binds the capability's whole predicate, chain included, as the
242
- handles apply it, and on an `update` or `delete` target it needs that operation's action; a reference table needs
243
- none. A deviation is fine: declare it, and do not contort the code to avoid it. The approver sees every declaration
239
+ Scope every scoped table a raw statement reads with `${ctx.sql.scope(<capability>, '<table>', { alias: '<alias>' })}`,
240
+ a conjunct of its WHERE or JOIN … ON (`where (<filter>) and ${…}`): `ctx.target` for `on` and `in`, `ctx.within` for
241
+ `over`, a job's minted `Ref` or `Within` with `tx.sql.scope`. It binds the capability's whole predicate, chain
242
+ included, as the handles apply it. The table an `update` or `delete` writes takes `{ use: 'update' }` or
243
+ `{ use: 'delete' }`, which needs that operation's action; a reference table needs none. The runtime does not check
244
+ where you put a fragment: the approver reads it. A deviation is fine: declare it, and do not contort the code to avoid it. The approver sees every declaration
244
245
  marked "needs closer review". Do not hide reach in a helper; the runtime builds `ctx.sql` and `ctx.db.unscoped` only
245
246
  where they are declared. A query or an export declares only `'read'`.
246
247
 
@@ -258,7 +259,7 @@ Which promise the types, the checker, boot, the runtime or the approver keeps, a
258
259
  - No `as` (except `as const`), `any`, `@ts-ignore`, `@ts-expect-error`, `process.env` or `Bun.env`.
259
260
  - Never log an error object, a request, headers or the environment.
260
261
  - Never edit a generated file (`src/db/schema.generated.ts`, the generated tests, `fabrika/entry.generated.ts`,
261
- `fabrika/connect/`) or a committed migration. Regenerate the file; write a new migration.
262
+ `fabrika/migrations.generated.ts`, `fabrika/connect/`) or a committed migration. Regenerate the file; write a new migration.
262
263
 
263
264
  ## Ask the human first
264
265
 
@@ -295,11 +296,36 @@ bunx tsc --noEmit # once, at the end
295
296
  bunx fabrika-check . # once, after tsc; refusals fail; hints print below them
296
297
  ```
297
298
 
299
+ **On Cloudflare** (`fabrika.config.ts` imports `defineApp` from `@fabrika/provider-cloudflare`, as
300
+ `references/app-setup.md` shows) the application runs in one Durable Object over SQLite. Its `db/migrations/*.sql` are SQLite (`references/table-and-migration.md`), and the
301
+ object applies them when it boots, so there is no `migrate` and no command needs a database URL or `FABRIKA_APP_ID`.
302
+ The tests run on `@fabrika/db/testing-sqlite` (`references/tests.md`), in memory, and never skip. A handler holds the
303
+ object's transaction, so its `limits.timeoutMs` is at most 25 s. A job's is at most 14 minutes, its default: longer
304
+ work claims a bounded batch per run, and the next run takes the rest (`references/jobs.md`). `ctx.sql` is SQLite there
305
+ (`references/endpoint.md`). No `scan: true`: the checker, the deploy and the boot refuse it. A migration names no
306
+ `fabrika_*` table but `REFERENCES fabrika_files (id)`. The deploy serves each SPA mount's
307
+ built `dir` itself; declare no `assets` on the Worker (`references/app-setup.md`).
308
+
309
+ The object runs one transaction at a time, so every `await` in a handler that may write holds the whole environment:
310
+ IAM, R2, a `fetch`, a `ctx.connect` call, a binding. One 2 s call caps the environment at half a request a second. A
311
+ query holds no transaction: each of its statements runs on its own, so two of its reads may see different committed
312
+ states. Inside a
313
+ mutation keep I/O to the framework's own: IAM, and the file it writes. A slow outside call goes into a row, the
314
+ mutation calls `ctx.kick('<job>')`, and the job makes the call outside `ctx.transaction` (`references/jobs.md`). The
315
+ checker hints on a mutation that declares `egress` or `connect` (`cloudflare-held-call`), and refuses
316
+ `DEFAULT CURRENT_TIMESTAMP` in a migration (`cloudflare-current-timestamp`).
317
+
318
+ ```bash
319
+ bunx fabrika db new <slug> # a new SQLite migration file
320
+ bunx fabrika db codegen # applies the migrations in memory; writes src/db/schema.generated.ts
321
+ bunx fabrika db test-scaffold # the generated tests, on @fabrika/db/testing-sqlite
322
+ bun test --isolate # no database URL; then tsc and fabrika-check as above
323
+ ```
324
+
298
325
  A generated file changes only through its command (`codegen`, `test-scaffold`); running it is the loop, not an edit.
299
326
  Format and lint only the files you wrote, with the repository's own tools: in the fabrika-platform repository
300
- `bunx dprint fmt <files>` and `bunx biome lint <files>`, never `biome check` (its formatter fights dprint), and never a
301
- generated file. An application outside that repository has neither configuration: use the formatter its own
302
- repository configures, or none, and never add a configuration unasked; tsc and `fabrika-check` are its gates. `FABRIKA_APP_ID` is lowercase letters, digits and `-`. An applied file is immutable: while you still
327
+ `bunx dprint fmt <files>` and `bunx oxlint <files>`, and never a generated file. An application outside that
328
+ repository has neither configuration: use the formatter its own repository configures, or none, and never add a configuration unasked; tsc and `fabrika-check` are its gates. `FABRIKA_APP_ID` is lowercase letters, digits and `-`. An applied file is immutable: while you still
303
329
  change an uncommitted migration, migrate into a fresh schema with another `FABRIKA_APP_ID`. Read a refusal's
304
330
  "allowed form" and use it; fix hints too. `references/errors.md` explains the findings and the type errors.
305
331
 
@@ -326,9 +352,10 @@ e-mails them, a link holder's files, HR's review with its history.
326
352
 
327
353
  ## Not built yet
328
354
 
329
- - The data layer runs on Bun and Postgres only (Zerops). On Cloudflare an application has no tables, jobs or files.
330
- - Jobs are cron only and app-wide: no `ctx.jobs.enqueue`, no job per scope. A `ctx.kick` starts a run of its job; it
331
- carries nothing, and the job finds its work in a queue table with `claim`. A list write is off the road (`sql`).
355
+ - On Cloudflare, where the application runs in one Durable Object over its SQLite and its `db/migrations/*.sql` are
356
+ SQLite, a file kind with `scan: true` is refused. Everything else on the road runs there.
357
+ - Jobs are cron only and app-wide: no `ctx.jobs.enqueue`, no job per scope. A `ctx.kick` starts a run of its job, now
358
+ or at `{ at }`; it carries nothing, and the job finds its work in a queue table with `claim`. A list write is off the road (`sql`).
332
359
  - A read across tables (a join, a filter over a related table, an aggregate over several) is off the road (`sql`).
333
360
  - An MCP workspace has no shell, so `codegen` and `test-scaffold` cannot run there. Tell the human; never write a
334
361
  generated file by hand.
@@ -19,22 +19,22 @@ the SPA is added with it.
19
19
  "test": "bun test --isolate"
20
20
  },
21
21
  "dependencies": {
22
- "@fabrika/app": "0.9.0-dev.4",
23
- "@fabrika/db": "0.9.0-dev.4",
24
- "@fabrika/provider-zerops": "0.9.0-dev.4",
25
- "@fabrika/proxy-core": "0.9.0-dev.4",
26
- "@fabrika/ui": "0.9.0-dev.4",
22
+ "@fabrika/app": "0.9.0-dev.6",
23
+ "@fabrika/db": "0.9.0-dev.6",
24
+ "@fabrika/provider-zerops": "0.9.0-dev.6",
25
+ "@fabrika/proxy-core": "0.9.0-dev.6",
26
+ "@fabrika/ui": "0.9.0-dev.6",
27
27
  "kysely": "0.29.6",
28
28
  "react": "^19.0.0",
29
29
  "react-dom": "^19.0.0",
30
30
  "zod": "^3.25.76"
31
31
  },
32
32
  "devDependencies": {
33
- "@fabrika/check": "0.9.0-dev.4",
34
- "@fabrika/cli": "0.9.0-dev.4",
35
- "@fabrika/platform": "0.9.0-dev.4",
33
+ "@fabrika/check": "0.9.0-dev.6",
34
+ "@fabrika/cli": "0.9.0-dev.6",
35
+ "@fabrika/platform": "0.9.0-dev.6",
36
36
  "@happy-dom/global-registrator": "^20.11.2",
37
- "@types/bun": "latest",
37
+ "@types/bun": "^1.4.3",
38
38
  "@types/react": "^19.0.0",
39
39
  "@types/react-dom": "^19.0.0",
40
40
  "typescript": "^5.9.3"
@@ -249,6 +249,35 @@ The platform's build runs the tests, writes the entrypoint, runs `fabrika-check`
249
249
  run `fabrika db migrate`, `fabrika db codegen --verify` and `fabrika db test-isolation` before the server starts: a
250
250
  version does not go live until every generated test passes. It writes every `FABRIKA_*` variable; never set one.
251
251
 
252
+ ## The deploy surface (Cloudflare)
253
+
254
+ ```ts fabrika.config.ts
255
+ import { defineApp } from '@fabrika/provider-cloudflare'
256
+
257
+ export default defineApp({ id: 'tasks' })
258
+ ```
259
+
260
+ That is the whole config. `defineApp` builds the application Worker: named after the id, running
261
+ `fabrika/entry.generated.ts`, with no route and no public URL, and IAM bound at its application entrypoint. The deploy
262
+ builds the proxy Worker from `fabrika.contract.ts` and writes the application's Durable Object, its files bucket, its
263
+ cron trigger and every `FABRIKA_*` variable; Control writes the IAM schema from the approved contract. Declare none of
264
+ them: a config that does is refused. Write no `resources`, `schema` or `pipeline.workerDir` (the config's directory is
265
+ the default). A binding of the application's own, or another `compatibility_date` or `compatibility_flags`, goes in
266
+ `worker: { bindings, compatibility_date, compatibility_flags }`; `IAM` stays the platform's. `package.json` names
267
+ `@fabrika/provider-cloudflare` where the Zerops one names `@fabrika/provider-zerops`, the entry is written by
268
+ `fabrika app build --provider=cloudflare` (the deploy runs it again from the pinned commit), and there is no
269
+ `zerops.yaml`.
270
+
271
+ It also serves the SPA: the deploy copies the build directory of each SPA and
272
+ link mount (`dir`, a link's `spa`) into `fabrika/assets/` at the mount's prefix (`/admin` into `fabrika/assets/admin/`)
273
+ after `pipeline.build`, and binds it as `ASSETS`. A `.assetsignore` at the root of a mount's directory excludes files
274
+ as it does for wrangler (gitignore syntax, relative to that directory); `.git`, `.hg`, `.svn` and `.bzr` are never
275
+ copied. A deploy whose mount directory the build did not write fails and
276
+ names the mount. A config that composes its own Worker with `resources` and declares `assets` keeps them instead, and the object reads each
277
+ request path from that directory as it is (`/admin/app.js` is `admin/app.js` there), so a hand-written `assets` works
278
+ only for a root mount, or for mounts whose directories nest like their prefixes; it needs `binding: 'ASSETS'` and
279
+ `run_worker_first: true`.
280
+
252
281
  ## The SPA (added when the application has one)
253
282
 
254
283
  The SPA is React, built from the screens and hooks of the framework: `@fabrika/app/react` runs the typed client's
@@ -379,8 +408,9 @@ await Bun.write(
379
408
  `src/schemas.ts`, `src/shared/` and its own modules; never a slice, `src/db/` or a Bun or Node module. The plugin loads the
380
409
  contract without its handlers. A row type the screen declares (`Task` above) is checked against the answer where
381
410
  the rows are passed in.
382
- - The last step points the page's assets at the SPA's prefix (`/`): the mount answers `index.html` for every path
383
- under it, so a deep link such as `/tasks/<id>` renders. `define` gives React's production build.
411
+ - The last step points the page's assets at the SPA's prefix (`/`): the mount answers `index.html` for every page
412
+ route under it (a path without an extension, or a navigation), so a deep link such as `/tasks/<id>` renders; a
413
+ missing asset such as an old `chunk-….js` is 404. `define` gives React's production build.
384
414
  - `sourcemap: 'external'` writes each script's map beside it, and the page names none. The platform build uploads the
385
415
  maps to Operations for the release the page reports, so an error's frames show the original source; the mount
386
416
  never serves a `.map` file (404). Keep the maps external: `inline` would ship the source to every visitor.
@@ -397,4 +427,5 @@ await Bun.write(
397
427
 
398
428
  ## Ignored files
399
429
 
400
- `.gitignore`: `node_modules/`, `fabrika.manifest.json`, `/fabrika/entry.generated.ts`, `/dist/`.
430
+ `.gitignore`: `node_modules/`, `fabrika.manifest.json`, `/fabrika/entry.generated.ts`, `/dist/`, and on Cloudflare
431
+ `/fabrika/assets/`, where a deploy stages the SPA's files.
@@ -1,7 +1,8 @@
1
1
  # references/dev.md — previewing the application with `fabrika app dev`
2
2
 
3
3
  `bunx fabrika app dev` serves the application on `http://127.0.0.1:3000/` through its test kit: the proxy decision,
4
- the stand-in IAM, a throwaway schema of `FABRIKA_TEST_POSTGRES_URL`, and each SPA from its build (run
4
+ the stand-in IAM, a throwaway schema of `FABRIKA_TEST_POSTGRES_URL` (on Cloudflare an in-memory SQLite database,
5
+ without a URL), and each SPA from its build (run
5
6
  `bun run build:web` first). Use it to look at the screens, never in place of a test.
6
7
 
7
8
  ## The seed
@@ -406,7 +406,7 @@ export const workloadRows = (
406
406
  count(*) filter (where t.status <> 'done')::int as open,
407
407
  count(*) filter (where t.status <> 'done' and t.due_on < current_date)::int as overdue
408
408
  from tasks t
409
- where ${sql.scope(org, 'tasks', 't')}
409
+ where ${sql.scope(org, 'tasks', { alias: 't' })}
410
410
  and (${status}::text is null or t.status::text = ${status})
411
411
  group by t.assignee
412
412
  order by t.assignee`
@@ -421,7 +421,7 @@ export const workloadRows = (
421
421
  ## Raw SQL: `sql: 'read'`
422
422
 
423
423
  Raw SQL is legitimate for a join, a report, an `OR` or `IS NULL` filter, or a bulk write. Declare it on the endpoint;
424
- `ctx.sql` exists only there.
424
+ `ctx.sql` exists only there. It runs on Postgres and, on Cloudflare, on SQLite (the rules of each are below).
425
425
 
426
426
  ```ts src/reports/endpoints.ts
427
427
  import { attachment } from '@fabrika/app/contract'
@@ -475,7 +475,7 @@ export const reports = app.group({ callers: ['human'] }, (r) => ({
475
475
  const rows = await ctx.sql(TaskExportRow)`
476
476
  select t.title, t.status, t.assignee, t.due_on::text as due_on
477
477
  from tasks t
478
- where ${ctx.sql.scope(ctx.target, 'tasks', 't')}
478
+ where ${ctx.sql.scope(ctx.target, 'tasks', { alias: 't' })}
479
479
  order by t.title
480
480
  limit 10000`
481
481
  await ctx.db.target.project_exports.insert({ row_count: rows.length })
@@ -487,7 +487,7 @@ export const reports = app.group({ callers: ['human'] }, (r) => ({
487
487
  - Every `${…}` of a value is a bound parameter, never SQL text. The one exception is `${ctx.sql.scope(…)}`: it is SQL
488
488
  (the predicate) around its own bound values, and it may have no value at all (`(true)`, `(false)`). Put no
489
489
  interpolation inside quotes, a quoted name, a dollar body or a comment: the tag refuses it.
490
- - **Scope every scoped table the statement reads with `${ctx.sql.scope(capability, '<table>', '<alias>')}`.**
490
+ - **Scope every scoped table the statement reads with `${ctx.sql.scope(capability, '<table>', { alias: '<alias>' })}`.**
491
491
  `ctx.sql` has no scope predicate of its own. The fragment is the capability's whole predicate on that table: for a
492
492
  `Ref` the object's column and every link of its chain, so a project moved to another org is out; for a `Within` its
493
493
  values, each container grant on its own column, every row for a global grant and none for an empty one. The
@@ -495,29 +495,31 @@ export const reports = app.group({ callers: ['human'] }, (r) => ({
495
495
  `Within` it minted to `tx.sql.scope`. A table the capability does not reach is a type error at the table name. A
496
496
  reference table is shared by every scope and needs no fragment, and no statement writes it. An application table
497
497
  needs none either (the intake job of `references/public-intake.md`).
498
- - **A fragment carries its action into the statement.** On the table an `update` or `delete` writes it needs the
499
- table's own update or delete action (`ctx.within('tasks.write', 'project')` for `update tasks`), so a read action
500
- never scopes a write. A column's own write action (`columns: { assignee: { write: 'tasks.assign' } }`) scopes an
501
- `update` too, when every column its `set` assigns declares that action: a table with only column writes is updated
502
- this way; anywhere else it needs an action the handles read the table with. `insert … on conflict do
503
- update … where ${…}` is an update of the inserted table. The fragment answers for its own query block: a CTE that
504
- updates and a statement that deletes take one capability each, and another occurrence of the written table (a
505
- subquery, `from tasks other`) reads with a read capability under its own alias. A refused fragment fails the call
506
- before anything is sent.
507
- - **A fragment is a conjunct.** It stands alone, joined by AND, at the top level of a WHERE or JOIN … ON clause whose
508
- top level holds no OR: `where (<the whole filter>) and ${…}`, `join projects p on p.id = t.project_id and ${…}`.
509
- The tag refuses `where a or ${…}`, `where a or b and ${…}`, `not ${…}`, a fragment in parentheses or outside such a
510
- clause. Never scope by hand with `ctx.target.value` alone: it drops the chain. The generated tests check that an `in`
511
- endpoint with `sql` leaks nothing of another scope.
498
+ - **A fragment states what it scopes.** `use` is `'read'` by default; the table an `update` or `delete` writes takes
499
+ `{ use: 'update' }` or `{ use: 'delete' }`, which needs the table's own update or delete action
500
+ (`ctx.within('tasks.write', 'project')` for `update tasks`) on a `'write'` site, so a read action never scopes a
501
+ write. A column's own write action (`columns: { assignee: { write: 'tasks.assign' } }`) is enough for `use: 'update'`
502
+ too; set only the columns it writes. `insert … on conflict do update … where ${…}` scopes the inserted table with
503
+ `use: 'update'`. Each block takes its own fragment: a CTE that updates and a statement that deletes take one
504
+ capability each, and another occurrence of the written table (a subquery, `from tasks other`) reads under its own
505
+ alias. A refused fragment fails the call before anything is sent.
506
+ - **A fragment is a conjunct.** Put it alone, joined by AND, at the top level of a WHERE or JOIN … ON clause whose top
507
+ level holds no OR: `where (<the whole filter>) and ${…}`, `join projects p on p.id = t.project_id and ${…}`. The tag
508
+ does not read where it stands, which relation it filters or which columns a `set` assigns: the approver does, and a
509
+ fragment under an `or` widens the statement to every row. Never scope by hand with `ctx.target.value` alone: it drops
510
+ the chain. The generated tests check that an `in` endpoint with `sql` leaks nothing of another scope.
512
511
  - Rows are parsed like `fromRow` (snake_case to camelCase), then by the schema. Postgres sends `bigint` and `numeric`
513
512
  as text: cast a count (`count(*)::int`), and a sum to the type its output declares (`::int` for an integer sum that
514
513
  fits, `::float8` for a fractional one), or keep it a string. A sum over no rows is `null`: `coalesce(sum(…), 0)`.
515
514
  - An optional filter is `(${value}::text is null or <column> = ${value})`.
516
515
  - One statement: `select`, `with`, `values`, plus `insert`, `update` and `delete` on a `'write'` site (a mutation, a
517
- job or a webhook). Refused before anything is sent: DDL, `SET`, `COPY`, transaction control, another schema, any
518
- `fabrika_*` or `pg_*` name, and calls outside the reviewed built-ins. A function your migrations declare is refused
519
- too: call it from a view. These name rules are defense in depth; the runtime role (DML only) is the boundary.
520
- - A query runs in a read-only transaction; a mutation's `ctx.sql` runs in the same transaction as its handles.
516
+ job or a webhook). Refused before anything is sent: DDL, `SET`, `COPY`, transaction control, and any `fabrika_*`
517
+ name. On Postgres also another schema, any `pg_*` name, and calls outside the reviewed built-ins; a function your migrations declare is refused too: call it from a view. On SQLite also any `sqlite_*`
518
+ name, `PRAGMA`, `ATTACH`, and a parameter you write yourself (`?`, `:x`, `@x`, `$x`): interpolate every value.
519
+ - On SQLite write SQLite: `count(*)` is already an integer, there is no `::` cast (`cast(x as text)`), and a list value
520
+ binds as JSON (`t.status in (select value from json_each(${list}))`).
521
+ - A query runs in a read-only transaction; a mutation's `ctx.sql` runs in the same transaction as its handles. A
522
+ `'read'` statement writes nothing, even in a mutation: one that tries fails the call.
521
523
 
522
524
  ## A file download: `attachment`
523
525
 
@@ -564,7 +566,7 @@ Every procedure takes `admission` (who may send it, how often) and `limits` (how
564
566
  | `admission.origins` | `'same-origin'` (default) or `'listed'` | `'same-origin'`, `'listed'` or `'any'` |
565
567
  | `admission.challenge` | none | `{ provider: 'altcha', secret, action?, cost?, maxAgeMs? }`, or `{ provider: 'turnstile', secret, siteKey, action? }` |
566
568
  | `limits.maxBytes` | 64 KiB, at most 1 MiB; with file fields 64 KiB plus each file at its kind's `maxBytes`, at most 48 MiB | the same |
567
- | `limits.timeoutMs` | 10 s, at most 60 s | the same |
569
+ | `limits.timeoutMs` | 10 s, at most 60 s; at most 25 s on Cloudflare | the same |
568
570
 
569
571
  - A declared `rate` merges into the default; `null` turns one bucket off. Past a bucket the answer is 429.
570
572
  - Every bucket is charged before the body is read and stays charged whatever the handler does. A bucket is a database
@@ -642,7 +644,7 @@ export const app = defineApp(vocabulary, tables, {
642
644
  - A public procedure updates or removes a row only by an id a verified token of its request carries, with
643
645
  `expectVersion`.
644
646
  - Single use and revocation are your state (a row the token names). The keys are the platform's: Control generates
645
- and rotates them, and an old key verifies until its last token expires. Cloudflare has no signed tokens.
647
+ and rotates them, and an old key verifies until its last token expires.
646
648
 
647
649
  ## Outside calls: `egress`
648
650
 
@@ -652,6 +654,10 @@ refused while the site runs (`capability_refused: undeclared_egress`). A public,
652
654
  none. The checker's `cross-app-fetch` accepts an absolute URL only under an origin some site declares. The approver
653
655
  sees every origin. The guard stops mistakes; it is no sandbox.
654
656
 
657
+ On Cloudflare a procedure waits for its outside call inside the object's transaction, so the whole environment waits
658
+ with it (`SKILL.md`). A mutation records a row and kicks a job, which declares the `egress` and calls outside
659
+ `ctx.transaction` (`references/jobs.md`).
660
+
655
661
  ## Links to your own procedures: `ctx.url`
656
662
 
657
663
  `ctx.url('<endpoint id>', { input?, query? })` builds an absolute URL of one of the application's own procedures, on
@@ -8,39 +8,44 @@ architecture, and a refusal's allowed form is the one fix that passes. There is
8
8
 
9
9
  The refusals agents meet most, and their fix:
10
10
 
11
- | Rule | Means | Fix |
12
- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
13
- | `literal` | the shell (contract, vocabulary, tables, groups, schemas) holds a computed value or call | literal objects, `z.*` calls and imported literal consts; move logic into `.handle(…)` |
14
- | `contract` | the contract does not compile (a reserved role, an unknown action, a wrong field) | the message names the field |
15
- | `package-replacement` | `package.json` names the app under `@fabrika/*`, or a dependency is `workspace:*` | another name; a registry range such as `^0.0.4` |
16
- | `generated-test-hash` | a generated test is missing, edited or stale | `bunx fabrika db test-scaffold`, and commit what it writes |
17
- | `endpoint-fixture` | an endpoint's input cannot be sampled, a fixture or seed names no endpoint, or a member, invitation or link field no endpoint that reads, cancels or revokes one | a literal in `src/__tests__/endpoint-access.fixtures.ts` (`references/tests.md`) |
18
- | `raw-sql` | a driver's `sql` (imported from `bun`, Kysely, `postgres`) | the handles, or `sql: 'read'` and `ctx.sql` |
19
- | `forbidden-import` | a driver, an S3 client, `jose`, `node:http`, `child_process` | the handles, a file column with `ctx.files`, a connector |
20
- | `forbidden-global` | `Bun.sql`, `Bun.serve`, `Bun.spawn`; `globalThis`, `window`, `self`, `global` or `Bun` in a server module | the handles; state lives in a table, not in a global; `crypto.randomUUID()` for an id |
21
- | `env-read` | `process.env`, `Bun.env` | `defineDeps(build)`, which receives the application's variables |
22
- | `client-identity` | an input field `userId`, `ownerId`, `createdBy`, `tenantId`, `workspaceId` | the access form's `from`, `ctx.principal.id`, or `createdBy` in the policy |
23
- | `type-assertion` | `as T` (other than `as const`), `<T>x` | fix the type; `fromRow` parses a row into a schema's type |
24
- | `sensitive-log` | a log of an error object, a request, headers or the environment | log a short fixed message |
25
- | `migration-name` | a migration not named `YYYYMMDDHHMMSS_slug.sql` (UTC) | `bunx fabrika db new <slug>` |
26
- | `test-only-import` | `@fabrika/app/testing`, `@fabrika/app/react/testing` or `@fabrika/db/testing` outside a test file | import them only from `*.test.ts` or `__tests__/` |
27
- | `spa-server-import` | the SPA loads a server module | the SPA imports `@fabrika/app/client`, the contract, `src/schemas.ts` and `src/shared/` |
28
- | `shared-import` | a module under `src/shared/` loads a slice, `src/db/`, `@fabrika/*` or a builtin | a shared module imports `zod/v4` and other shared modules only |
29
- | `skipped-test` | `.skip`, `.only`, `.todo` | run the test |
30
- | `file-column-migration` | a file column without `REFERENCES fabrika_files (id)` or without an index it leads | both, in a new migration (`references/table-and-migration.md`) |
31
- | `on-conflict-index` | `insert(…, { onConflict: { columns } })` whose columns are no unique index the migrations create | a `UNIQUE` constraint or a `CREATE UNIQUE INDEX` without `WHERE` on exactly those columns |
32
- | `cross-app-fetch` | a `fetch` of an absolute URL under no origin a site declares in `egress` | `egress: ['https://…']` on the site that calls it (`references/endpoint.md`) |
33
- | `url-endpoint` | `ctx.url('<id>')` names no procedure of the contract | the endpoint id `<mount>.<group>.<procedure>` |
11
+ | Rule | Means | Fix |
12
+ | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
13
+ | `literal` | the shell (contract, vocabulary, tables, groups, schemas) holds a computed value or call | literal objects, `z.*` calls and imported literal consts; move logic into `.handle(…)` |
14
+ | `contract` | the contract does not compile (a reserved role, an unknown action, a wrong field) | the message names the field |
15
+ | `package-replacement` | `package.json` names the app under `@fabrika/*`, or a dependency is `workspace:*` | another name; a registry range such as `^0.0.4` |
16
+ | `generated-test-hash` | a generated test is missing, edited or stale | `bunx fabrika db test-scaffold`, and commit what it writes |
17
+ | `endpoint-fixture` | an endpoint's input cannot be sampled, a fixture or seed names no endpoint, a member, invitation or link field no endpoint that reads, cancels or revokes one, a file names no file field or a path outside the application, or a refusal is `validation` | a literal in `src/__tests__/endpoint-access.fixtures.ts` (`references/tests.md`) |
18
+ | `raw-sql` | a driver's `sql` (imported from `bun`, Kysely, `postgres`) | the handles, or `sql: 'read'` and `ctx.sql` |
19
+ | `forbidden-import` | a driver, an S3 client, `jose`, `node:http`, `child_process` | the handles, a file column with `ctx.files`, a connector |
20
+ | `forbidden-global` | `Bun.sql`, `Bun.serve`, `Bun.spawn`; `globalThis`, `window`, `self`, `global` or `Bun` in a server module | the handles; state lives in a table, not in a global; `crypto.randomUUID()` for an id |
21
+ | `env-read` | `process.env`, `Bun.env` | `defineDeps(build)`, which receives the application's variables |
22
+ | `client-identity` | an input field `userId`, `ownerId`, `createdBy`, `tenantId`, `workspaceId` | the access form's `from`, `ctx.principal.id`, or `createdBy` in the policy |
23
+ | `type-assertion` | `as T` (other than `as const`), `<T>x` | fix the type; `fromRow` parses a row into a schema's type |
24
+ | `sensitive-log` | a log of an error object, a request, headers or the environment | log a short fixed message |
25
+ | `migration-name` | a migration not named `YYYYMMDDHHMMSS_slug.sql` (UTC) | `bunx fabrika db new <slug>` |
26
+ | `test-only-import` | `@fabrika/app/testing`, `@fabrika/app/react/testing`, `@fabrika/db/testing` or `@fabrika/db/testing-sqlite` outside a test file | import them only from `*.test.ts` or `__tests__/` |
27
+ | `spa-server-import` | the SPA loads a server module | the SPA imports `@fabrika/app/client`, the contract, `src/schemas.ts` and `src/shared/` |
28
+ | `shared-import` | a module under `src/shared/` loads a slice, `src/db/`, `@fabrika/*` or a builtin | a shared module imports `zod/v4` and other shared modules only |
29
+ | `skipped-test` | `.skip`, `.only`, `.todo` | run the test |
30
+ | `file-column-migration` | a file column without `REFERENCES fabrika_files (id)` or without an index it leads | both, in a new migration (`references/table-and-migration.md`) |
31
+ | `on-conflict-index` | `insert(…, { onConflict: { columns } })` whose columns are no unique index the migrations create | a `UNIQUE` constraint or a `CREATE UNIQUE INDEX` without `WHERE` on exactly those columns |
32
+ | `cross-app-fetch` | a `fetch` of an absolute URL under no origin a site declares in `egress` | `egress: ['https://…']` on the site that calls it (`references/endpoint.md`) |
33
+ | `url-endpoint` | `ctx.url('<id>')` names no procedure of the contract | the endpoint id `<mount>.<group>.<procedure>` |
34
+ | `cloudflare-scan` | on Cloudflare, a file kind with `scan: true` | the kind without `scan`, and no public procedure that takes its files |
35
+ | `cloudflare-job-segment` | on Cloudflare, a job whose `limits.timeoutMs` exceeds one 14-minute segment | at most 14 minutes: claim a bounded batch per run, and the next run takes the rest |
36
+ | `cloudflare-current-timestamp` | on Cloudflare, `DEFAULT CURRENT_TIMESTAMP` in a migration: SQLite stores `YYYY-MM-DD HH:MM:SS`, which every read of the table refuses | `DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`, in a new migration |
37
+ | `cloudflare-framework-name` | on Cloudflare, a `fabrika_*` name in a migration, quoted or not | your own tables, and `REFERENCES fabrika_files (id)` for a file column |
34
38
 
35
39
  The hints:
36
40
 
37
- | Hint | Means | Fix |
38
- | ---------------------- | ------------------------------------------------------------- | ----------------------------------------------------------- |
39
- | `handler-location` | a `.handle(…)` outside a slice's `endpoints.ts` | move the endpoint into `src/<slice>/endpoints.ts` |
40
- | `data-access-location` | `ctx.db` or `ctx.sql` outside `endpoints.ts` and `queries.ts` | pass the handle into a function of the slice's `queries.ts` |
41
- | `logic-data-access` | `logic.ts` reaches data | keep `logic.ts` pure; pass it plain values |
42
- | `cross-slice-queries` | a slice loads another slice's `queries.ts` | move the function, or call that slice's endpoint |
43
- | `sql-undeclared` | `ctx.sql` in a handler whose endpoint declares no `sql` | add `sql: 'read'` (or `'write'`) to that endpoint |
41
+ | Hint | Means | Fix |
42
+ | ---------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
43
+ | `handler-location` | a `.handle(…)` outside a slice's `endpoints.ts` | move the endpoint into `src/<slice>/endpoints.ts` |
44
+ | `data-access-location` | `ctx.db` or `ctx.sql` outside `endpoints.ts` and `queries.ts` | pass the handle into a function of the slice's `queries.ts` |
45
+ | `logic-data-access` | `logic.ts` reaches data | keep `logic.ts` pure; pass it plain values |
46
+ | `cross-slice-queries` | a slice loads another slice's `queries.ts` | move the function, or call that slice's endpoint |
47
+ | `sql-undeclared` | `ctx.sql` in a handler whose endpoint declares no `sql` | add `sql: 'read'` (or `'write'`) to that endpoint |
48
+ | `cloudflare-held-call` | on Cloudflare, a mutation that declares `egress` or `connect` holds the whole environment while it waits | record a row and `ctx.kick('<job>')`; the job makes the call outside `ctx.transaction` |
44
49
 
45
50
  The first run may report only the contract's refusals: the generated-test findings appear once the contract compiles.
46
51
 
@@ -99,11 +104,11 @@ A 500 answers a fixed message; the server log has one line, `fabrika: <endpoint>
99
104
  fixed failure code and, for a framework refusal, its reason and the reason's fixed text, never a value or your error's
100
105
  message. The codes you meet most:
101
106
 
102
- | Code | Means |
103
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
104
- | `query_refused` | the data layer refused a statement or an operation: `undeclared_reach`, `sql_read_only`, `unknown_column`, `read_only`, `sql_outside_transaction` …; the reason's text names the rule |
105
- | `capability_refused` | a capability of another kind, dimension or action than the call takes (`wrong_capability`, `wrong_action`, `out_of_reach`), or one kept past its request (`ended`, `foreign_work`) |
106
- | `handler_failed` | your handler threw something else; the log has no more: the Operations issue has the stack, or test the handler |
107
+ | Code | Means |
108
+ | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
109
+ | `query_refused` | the data layer refused a statement or an operation: `undeclared_reach`, `sql_read_only`, `unknown_column`, `read_only`, `sql_outside_transaction`, `sql_scope`, `sql_name` …; the reason's text names the rule |
110
+ | `capability_refused` | a capability of another kind, dimension or action than the call takes (`wrong_capability`, `wrong_action`, `out_of_reach`), or one kept past its request (`ended`, `foreign_work`) |
111
+ | `handler_failed` | your handler threw something else; the log has no more: the Operations issue has the stack, or test the handler |
107
112
 
108
113
  With an Operations DSN the same 500 is a `RequestFailed` issue in Operations. Its event also carries what your handler
109
114
  threw: the error's type, its message, its stack and its `cause` chain. Read the stack there, not in the log. A crash
@@ -363,7 +363,8 @@ export const erase = app.cron('30 2 * * *', {
363
363
  ## Malware scan
364
364
 
365
365
  `scan: true` on a kind holds every file of it `quarantined` until ClamAV answers clean; on Zerops the platform
366
- installs ClamAV and runs the scan job. A file answer is 409 `file_not_ready` until then and 409 `file_rejected` once
366
+ installs ClamAV and runs the scan job. No scanner runs on Cloudflare: the deploy and the boot refuse a kind with
367
+ `scan: true` there, and so a public procedure with a file field. A file answer is 409 `file_not_ready` until then and 409 `file_rejected` once
367
368
  the file is `rejected`; a list shows each file's `status`, so show it rather than a broken link. In a test, the scan runs with
368
369
  `kit.runJob(FILE_SCAN_JOB)` and a `scanner` passed to `testKit` (`references/tests.md`); the generated tests pass their
369
370
  own seeded files.
@@ -401,7 +402,8 @@ the transaction that deletes the row. The file is never copied; the sweep delete
401
402
  ## Storage
402
403
 
403
404
  On Zerops, declare one `object-storage` service in `fabrika.config.ts`; the platform writes `FABRIKA_APP_STORAGE_*`
404
- from it. Never read those variables, build a storage URL or import an S3 client.
405
+ from it. Never read those variables, build a storage URL or import an S3 client. On Cloudflare the platform binds the
406
+ environment's R2 bucket itself; declare nothing.
405
407
 
406
408
  ```text
407
409
  // in the services of fabrika.config.ts
@@ -4,8 +4,8 @@ Background work is a cron job: `app.cron(schedule, { actions })` with its `.hand
4
4
  `endpoints.ts` of the slice whose data it works on, mounted under `jobs` in the contract. There are no timers, loops,
5
5
  `setInterval` or self-scheduled work, and no `ctx.jobs.enqueue`: work for later is a row that a run picks up, usually
6
6
  from a queue table with `claim` (below). A mutation, a webhook or another job that declares `kicks: ['<job>']` and
7
- calls `ctx.kick('<job>')` starts a run within seconds of its commit (the outbox below); the schedule picks up whatever
8
- that run leaves.
7
+ calls `ctx.kick('<job>')` starts a run within seconds of its commit (the outbox below), and `ctx.kick('<job>', { at })`
8
+ starts one at `at`; the schedule picks up whatever that run leaves.
9
9
 
10
10
  ```ts src/overdue/endpoints.ts
11
11
  import { app } from '../app-kit'
@@ -118,7 +118,7 @@ export const contract = app.contract((c) => ({
118
118
  one, since no zone is a day further ahead.
119
119
  - **Reads run outside the transaction; every write runs inside `ctx.transaction((tx) => …)`**, through `tx.db`, fenced
120
120
  by the attempt's lease. A write outside it is a type error that names `tx.db`.
121
- - An attempt that fails or outlives `limits.timeoutMs` (default 15 minutes, at most a day) is retried up to `retries` times, so every write is
121
+ - An attempt that fails or outlives `limits.timeoutMs` (default 14 minutes, at most a day; at most 14 minutes on Cloudflare) is retried up to `retries` times, so every write is
122
122
  idempotent. **Re-read each row under its lock before you write it:** `tx.db.on(ref).getForUpdate()` inside the
123
123
  transaction, decide again on what it answers with the list's whole filter (`isOverdue`), and write with its
124
124
  `version`. The listed row is already old: someone
@@ -177,7 +177,14 @@ that says so): it records an outbox row and kicks the job (below). `references/p
177
177
  (RFC 8058), so a mailbox offers one-click unsubscribe. The URL is a public procedure of your own with a signed token
178
178
  (`ctx.url('api.mail.unsubscribe', { query: { t: ctx.tokens.sign('unsubscribe', claims, { days: 400 }) } })`,
179
179
  `references/endpoint.md`). There are no free headers. A transport without the header refuses the message.
180
- - The idempotency key covers the attachments and the unsubscribe URL: a repeated key with other content is refused.
180
+ - `broadcast: true` marks one message of a send to many recipients (a newsletter, an announcement to every student),
181
+ as opposed to mail a recipient's own action triggers (a sign-in link, a confirmation). Providers keep the two apart
182
+ and pause an account whose transactional channel carries broadcast mail, so mark every message of a bulk send. It
183
+ needs `unsubscribe`. A transport without `ctx.mail.capabilities.broadcast` refuses it as `invalid_message`. Under
184
+ `mailer: 'installation'` the capability is true even where the installation's provider sends none; the first
185
+ message then fails `invalid_message`, so stop a bulk send at its first refusal instead of failing every row.
186
+ - The idempotency key covers the attachments, the unsubscribe URL and `broadcast`: a repeated key with other content
187
+ is refused.
181
188
  - `idempotencyKey` is 1 to 200 visible ASCII characters, unique per message in the application environment, and
182
189
  derived from the outbox row (`intake-link-<link id>`), never random. `ctx.mail` puts a prefix of the installation
183
190
  and the environment in front of it, so no other application on the same provider account shares it.
@@ -222,6 +229,8 @@ for (const row of await ctx.db.app('mail.send').outbox.claim({ limit: 50 })) {
222
229
  later.
223
230
  - A failure or a crash leaves the row as the claim left it, due again after the backoff; nothing retries at once.
224
231
  Attempts count claims, so claim only what the run will reach.
232
+ - A claim that leased rows runs the job again when the same claim would next find one (its `where`, its scope, below
233
+ `maxAttempts`), no sooner than a second later; a claim that took its full `limit` runs it again at once.
225
234
  - A row past `maxAttempts` stays in the table, no longer due, for the application to show or requeue.
226
235
  - One recipe covers an outbox, a per-record reminder (`<due>` is the reminder time) and asynchronous work: a mutation
227
236
  inserts a request row and kicks; the job claims it, renders, puts the result into a file column with
@@ -237,9 +246,17 @@ row, in its own transaction: a public procedure's row (`registrations`), an outb
237
246
  transaction committed, the job runs within seconds, under its own key, and the answer does not wait for it. A thrown
238
247
  handler, a refused answer and a failed commit kick nothing. Kicks coalesce: at most one run is active and one pending,
239
248
  however many calls arrive. A kick carries nothing; the job reads its rows, and its schedule stays the recovery.
249
+ The kick is written in the site's transaction, so a crash right after the commit still runs the job.
240
250
  `kicks` names cron jobs of the contract, as literals (`r.mutation({ …, kicks: ['testMails'] })`); a mutation, a
241
251
  webhook and a job declare it, and the kick edges never form a cycle.
242
252
 
253
+ **A kick for later.** `ctx.kick('<job>', { at })`, with `at` a `Date`, runs the job at that time instead of after the
254
+ commit: a reminder, a retry the application times itself. Kicks of one job in the same second are one; kicks at
255
+ different times stay apart, and a run takes only those already due. The second argument is the time and nothing else;
256
+ what to do stays in the job's rows (`where <due> <= now()`, or a queue table's `<due>`). On Cloudflare the object's
257
+ alarm runs it within seconds of `at`; on Bun the serving process that wrote it runs it at `at`, and another process
258
+ finds it within a minute.
259
+
243
260
  The rules of the job:
244
261
 
245
262
  - **Bounded batches.** Each run takes at most a fixed number of records (`order by received_at, id limit 50`), oldest
@@ -1,7 +1,7 @@
1
1
  # references/table-and-migration.md — the vocabulary, migrations and table policies
2
2
 
3
- The order is fixed: the vocabulary, then the migration, then `fabrika db migrate` and `fabrika db codegen`, then the
4
- table policies, which take the generated `columns`.
3
+ The order is fixed: the vocabulary, then the migration, then `fabrika db migrate` and `fabrika db codegen` (on
4
+ Cloudflare `codegen` only), then the table policies, which take the generated `columns`.
5
5
 
6
6
  ## The vocabulary
7
7
 
@@ -155,6 +155,23 @@ INSERT INTO priorities (code, label, rank) VALUES ('low', 'Low', 1), ('normal',
155
155
  - Never edit, rename or delete a committed migration; add a new one. Change a schema by expand, switch, contract, and
156
156
  ask before you drop or rename anything.
157
157
 
158
+ ## On Cloudflare: SQLite migrations
159
+
160
+ An application on Cloudflare (its `fabrika.config.ts` imports `defineApp` from `@fabrika/provider-cloudflare`) writes
161
+ its migrations in SQLite. Its Durable Object applies them when it boots, each file once in name order, in a transaction
162
+ of its own, so there is no `fabrika db migrate`; `fabrika db codegen` applies them to an in-memory database and needs
163
+ no URL. The rules above for keys, chains, composite foreign keys, `version` and `created_by` hold unchanged, and the
164
+ database enforces foreign keys.
165
+
166
+ - The declared types codegen reads: `TEXT` (a UUID too), `INTEGER`, `REAL`, `BLOB`; `BOOLEAN`, stored as 0 or 1 and
167
+ read as a boolean; `TIMESTAMP`, stored as UTC ISO text and read as a `Date`; `DATE`, `YYYY-MM-DD` text. Any other
168
+ declared type is refused. A `STRICT` table admits only `INTEGER`, `REAL`, `TEXT` and `BLOB`, so a table with a
169
+ `BOOLEAN`, `TIMESTAMP` or `DATE` column is not `STRICT`.
170
+ - SQLite has no `ENUM`: a column with a fixed set of values is `TEXT` with `CHECK (<column> IN ('a', 'b'))`. The
171
+ generated tests write its first value.
172
+ - No transaction control (`BEGIN`, `COMMIT`, `SAVEPOINT`) and no Postgres syntax (`timestamptz`, `::` casts,
173
+ `GENERATED ALWAYS AS IDENTITY`, `CREATE TYPE`).
174
+
158
175
  ## Database code is a declared deviation
159
176
 
160
177
  A function, trigger, view, rule, policy or `DO` block in a migration is allowed. The migration file declares it, and