@protobase/cli 0.129.1 → 0.130.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/auth/config-organizations.js +15 -0
  2. package/dist/auth/register.js +8 -2
  3. package/dist/auth/write-migration.js +34 -12
  4. package/dist/cli/package.js +1 -1
  5. package/dist/config/build-project.js +1 -0
  6. package/dist/config/project-modules.js +64 -0
  7. package/dist/config/read-only-queries.js +9 -0
  8. package/dist/config/user-tables-config.js +1 -1
  9. package/dist/dev/dev-jobs.js +12 -6
  10. package/dist/dev/entry.js +12 -19
  11. package/dist/doctor/capture-files.js +3 -3
  12. package/dist/doctor/startup.js +2 -4
  13. package/dist/migration/apply-migrations.js +9 -6
  14. package/dist/migration/baseline/read-live-modules.js +31 -0
  15. package/dist/migration/baseline/read-live-store.js +18 -4
  16. package/dist/migration/baseline/write-baseline.js +50 -17
  17. package/dist/migration/migrate-project.js +3 -3
  18. package/dist/migration/migration-project.js +29 -15
  19. package/dist/migration/older-code/catalog.js +34 -0
  20. package/dist/migration/older-code/contractions.js +86 -0
  21. package/dist/migration/older-code/lint-files.js +55 -0
  22. package/dist/migration/older-code/refusal.js +9 -0
  23. package/dist/migration/older-code/trial.js +58 -0
  24. package/dist/migration/parts.js +8 -104
  25. package/dist/migration/record/after-file.js +20 -2
  26. package/dist/migration/register.js +67 -19
  27. package/dist/migration/release/release-record.js +9 -7
  28. package/dist/migration/release/release-steps.js +15 -3
  29. package/dist/migration/sign-off/contract.js +65 -0
  30. package/dist/migration/sign-off/delete.js +50 -0
  31. package/dist/migration/sign-off/signed-off-file.js +19 -0
  32. package/dist/migration/snapshot/auth-difference.js +135 -15
  33. package/dist/migration/snapshot/auth-target.js +9 -3
  34. package/dist/migration/snapshot/check.js +24 -5
  35. package/dist/migration/snapshot/custom.js +6 -3
  36. package/dist/migration/snapshot/drop.js +7 -2
  37. package/dist/migration/snapshot/header.js +11 -4
  38. package/dist/migration/snapshot/module-changes.js +22 -0
  39. package/dist/migration/snapshot/module-prompts.js +42 -0
  40. package/dist/migration/snapshot/module-sections.js +38 -0
  41. package/dist/migration/snapshot/next-snapshot.js +13 -7
  42. package/dist/migration/snapshot/off-choice.js +11 -0
  43. package/dist/migration/snapshot/organizations-off-facts.js +49 -0
  44. package/dist/migration/snapshot/revival-rows.js +34 -0
  45. package/dist/migration/snapshot/run-migration.js +82 -15
  46. package/dist/migration/snapshot/snapshot-file.js +7 -0
  47. package/dist/migration/snapshot/terminal-prompts.js +21 -0
  48. package/dist/migration/snapshot/write-file.js +1 -1
  49. package/dist/migration/summary.js +3 -2
  50. package/dist/organizations/api.js +4 -2
  51. package/dist/organizations/commands.js +27 -10
  52. package/dist/organizations/pin-source.js +20 -0
  53. package/dist/organizations/pin.js +40 -0
  54. package/dist/organizations/register.js +20 -12
  55. package/dist/scaffold/protobase-tables.js +2 -2
  56. package/dist/serve/create-admin.js +6 -3
  57. package/dist/serve/lifecycle.js +2 -2
  58. package/dist/serve/migrate-release.js +1 -1
  59. package/dist/serve/relay-check.js +7 -8
  60. package/dist/serve/startup-checks.js +12 -22
  61. package/dist/supabase/load-phase.js +3 -1
  62. package/dist/supabase/project-users.js +4 -1
  63. package/dist/users/commands.js +44 -6
  64. package/dist/users/load-auth.js +9 -3
  65. package/dist/users/manage.js +16 -1
  66. package/dist/users/register.js +28 -25
  67. package/dist/users/set-disabled.js +3 -2
  68. package/dist/users/users-api.js +9 -3
  69. package/dist/worker/start-worker.js +7 -4
  70. package/package.json +8 -8
  71. package/skills/protobase/references/features/api-functions.md +1 -0
  72. package/skills/protobase/references/features/build-and-run.md +4 -2
  73. package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
  74. package/skills/protobase/references/guides/api-functions.md +27 -2
  75. package/skills/protobase/references/guides/deploy.md +2 -2
  76. package/skills/protobase/references/reference/assistant.md +1 -1
  77. package/skills/protobase/references/reference/auth.md +52 -17
  78. package/skills/protobase/references/reference/calls.md +1 -1
  79. package/skills/protobase/references/reference/cli.md +48 -28
  80. package/skills/protobase/references/reference/comments.md +1 -1
  81. package/skills/protobase/references/reference/config/api.md +1 -1
  82. package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
  83. package/skills/protobase/references/reference/config/sign-in.md +22 -4
  84. package/skills/protobase/references/reference/config.md +1 -1
  85. package/skills/protobase/references/reference/data-config.md +9 -9
  86. package/skills/protobase/references/reference/derived.md +1 -1
  87. package/skills/protobase/references/reference/email.md +2 -2
  88. package/skills/protobase/references/reference/events.md +2 -2
  89. package/skills/protobase/references/reference/history.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +5 -5
  91. package/skills/protobase/references/reference/live.md +2 -2
  92. package/skills/protobase/references/reference/notifications.md +4 -4
  93. package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
  94. package/skills/protobase/references/reference/realtime-relay.md +1 -1
  95. package/skills/protobase/references/reference/status.md +2 -2
  96. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  97. package/skills/protobase/references/reference/user-tables.md +1 -1
  98. package/skills/protobase/references/reference/webhooks.md +1 -1
  99. package/dist/migration/snapshot/lint-custom.js +0 -23
@@ -51,7 +51,7 @@ protobase scaffold [connection string | --env VAR] [target] [options]
51
51
 
52
52
  Without a connection string or `--env`, the URL is `DATABASE_URL`, from the environment or the nearest `.env` at or above the current directory, as `dev` reads it. `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended. A table that a written one points to with a foreign key is written too, outside the target or excluded, unless it has a resource already, since the app refuses a relation to a resource it does not have; a line names each.
53
53
 
54
- Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_migrations` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), pg-boss's `jobs` schema, and the `migrations` schema whose `applied` table records the migrations applied. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` or `migrations` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
54
+ Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_steps` or `auth_migrations` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), pg-boss's `jobs` schema, and the `migrations` schema whose `applied` table records the migrations applied. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` or `migrations` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
55
55
 
56
56
  | Option | Effect |
57
57
  | --- | --- |
@@ -145,11 +145,11 @@ Without a connection string, `--env` or `DATABASE_URL`, doctor stops and names `
145
145
  | Check | Without a database | With one |
146
146
  | --- | --- | --- |
147
147
  | Relations to a resource the config does not declare, sorts by a field that is not `.sortable()`, page components without reads | yes | yes |
148
- | The triggers, `capture()`, outbox, history and notices tables of resources with events, history or live updates | from `db/migrations/*.sql`, for each resource whose table a migration creates | from the catalog |
148
+ | The triggers, `capture()`, outbox, history and notices tables of resources with events, history or live updates | from `db/migrations/*.sql`, for each resource whose table a migration creates | from the record of migrations |
149
149
  | The server's build of the app, such as an owner field that must hold sign-in's user ids | yes | yes |
150
150
  | Tables, columns, types and keys; indexes for the reads; [user tables](user-tables.md); the other startup checks of the database | skipped | yes |
151
151
 
152
- From the migrations, a resource passes when they create its table, `capture()` in the changes schema and the outbox, the history table when it keeps history and the notices table when it is live, and a trigger of each name the server looks up on its table; a missing one fails with the server's message, as the startup check does. Statements are matched by name in the files, in any order, so a trigger a later migration drops or one created in dynamic SQL is judged only with a database. A resource whose table no migration creates, as in an app on a database of its own, is left to the database. <gap>Doctor cannot judge the jobs, comments, webhooks, workflows, notifications, status, rollup and other feature schemas without a database because reading their versions from the migration files is not implemented.</gap> Doctor ends with the checks it skipped:
152
+ From the migrations, a resource passes when they create its table, `capture()` in the changes schema and the outbox, the history table when it keeps history and the notices table when it is live, and a trigger of each name the change capture writes on its table; a missing one fails, naming the resource. Statements are matched by name in the files, in any order, so a trigger a later migration drops or one created in dynamic SQL is judged only with a database. A resource whose table no migration creates, as in an app on a database of its own, is left to the database. <gap>Doctor cannot judge the jobs, comments, webhooks, workflows, notifications, status, rollup and other feature schemas without a database because reading their versions from the migration files is not implemented.</gap> Doctor ends with the checks it skipped:
153
153
 
154
154
  ```
155
155
  Skipped without a database:
@@ -460,11 +460,11 @@ bun --no-install protobase-serve.js migrate-release <bundle> --plan # print wh
460
460
  bun --no-install protobase-serve.js migrate-release <bundle> # apply it
461
461
  ```
462
462
 
463
- It loads the bundle's config with the app's settings, as `create-admin` does, and compares every feature the config turns on with the database itself, as [`migration`](#migration) does with `DATABASE_URL` set: the sign-in tables by the versions their `auth_migrations` table records, the jobs, change capture, workflows, notifications and the other built-in schemas by what the database has. It applies what differs in one transaction, then the row that records the release in `migrations.history`, which the server reads at startup, behind the lock `migrate` takes, stopping at once while another run holds it, prints each part it applies, such as `applying auth`, or that the database is up to date, so a second run applies nothing. A step whose check refuses the rows already there, such as two From addresses one person entered with different case, stops it with the step's message and exit code 1, and nothing is applied. It refuses a database that lacks any of the bundle's own migrations, since the steps are compared with what they made.
463
+ It loads the bundle's config with the app's settings, as `create-admin` does, and compares every feature the config turns on with the database itself, as [`migration`](#migration) does with `DATABASE_URL` set: the sign-in tables by the steps their `auth_steps` table records, the jobs schema by the step pg-boss's version is at and the version Protobase's functions carry, the change capture, workflows, notifications and the other built-in schemas by what the database has. It applies what differs in one transaction, then the row that records the release in `migrations.history`, with or without sign-in, which the server reads at startup, behind the lock `migrate` takes, stopping at once while another run holds it, prints each part it applies, such as `applying auth`, or that the database is up to date, so a second run applies nothing. A step whose check refuses the rows already there, such as two From addresses one person entered with different case, stops it with the step's message and exit code 1, and nothing is applied. It refuses a database that lacks any of the bundle's own migrations, since the steps are compared with what they made.
464
464
 
465
465
  `--plan` applies nothing and prints the same statements as one SQL script, each part under a comment, ending with `-- N steps to apply; nothing was applied`. The script records the sign-in versions it applies itself, so a host can run it in a transaction of its own, such as one it rolls back to try it first, or one it commits while nothing else writes.
466
466
 
467
- A project that gets the same steps later from its own [`migration`](#migration) applies them without doing any twice: each sign-in step in its files runs only while `auth_migrations` lacks its version, and the other parts are compared with its database.
467
+ A project that gets the same steps later from its own [`migration`](#migration) applies them without doing any twice: each sign-in step in its files runs only while `auth_steps` lacks it, and the other parts are compared with its database.
468
468
 
469
469
  ## `serve`
470
470
 
@@ -617,12 +617,12 @@ Prints a fresh key pair for [Web Push](notifications.md#web-push) as `PROTOBASE_
617
617
 
618
618
  ```sh
619
619
  protobase users create <email> [--name <name>] [--role <role>] [--password-stdin | --generate-password | --no-password] [--github-id <id>]
620
- [--organization <organization> [--org-role <role>] [--app-roles <a,b>]]
621
- protobase users list
620
+ [--organization <organization> | --all-organizations] [--org-role <role>] [--app-roles <a,b>]
621
+ protobase users list [--organization <organization> | --all-organizations]
622
622
  protobase users roles
623
- protobase users set-role <email> <role>
624
- protobase users disable <email> # and: enable <email>
625
- protobase users delete <email> [--yes]
623
+ protobase users set-role <email> <role> [--organization <organization> | --all-organizations]
624
+ protobase users disable <email> [--organization <organization> | --all-organizations] # and: enable <email>
625
+ protobase users delete <email> [--yes] [--organization <organization> | --all-organizations]
626
626
  ```
627
627
 
628
628
  Run inside a project with sign-in on (its config's `auth`, on unless `false`, or unless the config leaves `auth` out and sets `authenticate.jwksUrl`). Like `organizations`, `token` and `auth migration`, it reads the `.env` nearest the project and needs `DATABASE_URL`. There is no web setup page, and [open sign-up](auth.md#open-sign-up), when a project turns it on, waits for the first admin: the first admin is created here. The first user is always an admin, whatever `--role` says; later users get `--role`, or the project's default role (`auth: { roles, defaultRole }` in its config). `protobase users roles` lists the roles of the project; anything else is refused with that list. `set-role` also takes comma separated roles (`sales,accountant`). `--github-id` links the new user to a GitHub user id (the number, not the login), so signing in with GitHub, the app's own provider or the [platform's](auth.md#platform-sign-in-providers), finds them whatever address GitHub reports; an id that signs in another user already is refused. `createUser(auth, { ..., accounts: [{ providerId, accountId }] })` does the same from code.
@@ -631,28 +631,34 @@ The password is typed at a hidden prompt with confirmation, read from stdin with
631
631
 
632
632
  `delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. With [MCP](auth.md#oauth-for-mcp-clients) on, it also disconnects their MCP clients. `enable` lifts the ban; the clients have to be allowed again. `protobase dev` prints the command that creates the first admin at startup while the user table is empty (see [`dev`](#dev)).
633
633
 
634
- With [organizations](auth.md#organizations), `--role` is the user's global role (none by default) and `--organization` adds the new user to an organization, by its slug or id, with `--org-role` (`owner`, `admin`, or `member`, the default) and `--app-roles` there.
634
+ With [organizations](auth.md#organizations), `--role` is the user's global role (none by default), and each command acts on [the pinned organization](#the-pinned-organization): `create` adds the new user to it with `--org-role` (`owner`, `admin`, or `member`, the default) and `--app-roles` there, or to no organization with `--all-organizations`; the first user owns it already when it had no members. `list` lists its members, or every user with `--all-organizations`. `set-role`, `disable`, `enable` and `delete` reach only its members, or any user with `--all-organizations`; they change the whole account, in every organization the user belongs to.
635
635
 
636
636
  ## `organizations`
637
637
 
638
638
  ```sh
639
- protobase organizations list
639
+ protobase organizations list [--organization <organization> | --all-organizations]
640
640
  protobase organizations create <name> --owner <email> [--slug <slug>] [--id <id>] [--members all]
641
- protobase organizations add-member <organization> <email> [--org-role <role>] [--app-roles <a,b>]
642
- protobase organizations set-roles <organization> <email> [--org-role <role>] [--app-roles <a,b>]
643
- protobase organizations remove-member <organization> <email>
644
- protobase organizations add-app-role <role> --to owners
641
+ protobase organizations add-member <email> [--organization <organization>] [--org-role <role>] [--app-roles <a,b>]
642
+ protobase organizations set-roles <email> [--organization <organization>] [--org-role <role>] [--app-roles <a,b>]
643
+ protobase organizations remove-member <email> [--organization <organization>]
644
+ protobase organizations add-app-role <role> --to owners [--organization <organization> | --all-organizations]
645
645
  ```
646
646
 
647
- For a project with [organizations](auth.md#organizations); `<organization>` is a slug or an id. The host acts as a superuser, so it may give any role. `create` makes `--owner` the owner with every app role; `--id` keeps an existing tenant value, and `--members all` adds every other user, superusers as owners and everyone else as a member with their global roles moved onto the membership, for an app that ran as one organization. `remove-member` and `set-roles` refuse to leave an organization without an owner. `add-app-role` gives a role the project added later to every owner.
647
+ For a project with [organizations](auth.md#organizations). The host acts as a superuser, so it may give any role. Every command but `create` acts on [the pinned organization](#the-pinned-organization): `list` lists it with its members, or every organization with `--all-organizations`; `add-member`, `set-roles` and `remove-member` change a membership in it, and refuse `--all-organizations`; `add-app-role` gives a role the project added later to its owners, or to every organization's owners with `--all-organizations`. `create` makes `--owner` the owner with every app role; `--id` keeps an existing tenant value, and `--members all` adds every other user, superusers as owners and everyone else as a member with their global roles moved onto the membership, for an app that ran as one organization. `remove-member` and `set-roles` refuse to leave an organization without an owner.
648
+
649
+ ### The pinned organization
650
+
651
+ The `users` and `organizations` commands act on one organization: the config's [`auth.organizations.default`](auth.md#the-default-organization), or the one `--organization` names by its slug or id. They print it first, or `Every organization` with `--all-organizations`, which reaches every organization's people. An organization the database does not have is refused, naming it, and so is a project without `auth.organizations.default` unless the command gets `--organization` or `--all-organizations`.
652
+
653
+ The pin is a filter, not a boundary: whoever runs a host command holds the database's credentials, so it keeps a command from reaching another organization's people by accident, not on purpose.
648
654
 
649
655
  ## `migrate`
650
656
 
651
657
  ```sh
652
- protobase migrate [connection string | --env VAR] [--plan]
658
+ protobase migrate [connection string | --env VAR] [--plan] [--force]
653
659
  ```
654
660
 
655
- Applies the project's `db/migrations/*.sql` that the database has not applied yet, in file name order, as the runtime's [`migrate`](#build-serve) applies a bundle's: behind the same lock, which it only tries, stopping at once while another run holds it, recorded in the same `migrations.applied` and, by each file's own last statement, in `migrations.history` (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)), so a database either one migrated is current for the other. The files apply in batches, each in one transaction, cut after a file with an `.after.sql`, whose statements run outside a transaction before the next batch; a file a stopped run left unfinished is finished first. It prints each file it applies and each `.after.sql` it runs, or that the database is up to date; a project without `db/migrations` applies nothing and says so. It runs none of the project's code, so a project with only `protobase.config.ts`, no `package.json` and nothing installed, migrates as well. The URL comes as for [`scaffold`](#scaffold), and is needed only when there are migrations. A project that still has a `db/migrate.ts` recording in `public.schema_migrations` first copies in the presets' current `db/migrate.ts` and `drop.ts`, so the two keep one record. `--plan` is a dry run: it prints each `.after.sql` left unfinished, then each file not applied yet under its name, with its SQL and its `.after.sql`, from a read-only transaction, and applies and records nothing. <gap>`migrate` cannot report where the tables it touched differ from the record's model, nor refuse a Postgres older than the supported one, because comparing them after applying, and `migration check --database`, are not implemented.</gap>
661
+ Applies the project's `db/migrations/*.sql` that the database has not applied yet, in file name order, as the runtime's [`migrate`](#build-serve) applies a bundle's: behind the same lock, which it only tries, stopping at once while another run holds it, recorded in the same `migrations.applied` and, by each file's own last statement, in `migrations.history` (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)), so a database either one migrated is current for the other. The files apply in batches, each in one transaction, cut after a file with an `.after.sql`, whose statements run outside a transaction before the next batch; a file a stopped run left unfinished is finished first. It prints each file it applies and each `.after.sql` it runs, or that the database is up to date; a project without `db/migrations` applies nothing and says so. It runs none of the project's code, so a project with only `protobase.config.ts`, no `package.json` and nothing installed, migrates as well. The URL comes as for [`scaffold`](#scaffold), and is needed only when there are migrations. A project that still has a `db/migrate.ts` recording in `public.schema_migrations` first copies in the presets' current `db/migrate.ts` and `drop.ts`, so the two keep one record. `--plan` is a dry run: it prints each `.after.sql` left unfinished, then each file not applied yet under its name, with its SQL and its `.after.sql`, from a read-only transaction, and applies and records nothing. `--force` lets a file that turns a [kept sign-in module](auth.md#turning-a-module-off) on again apply while its tables hold rows, which come back into use; without it the file stops, naming each table with its count. <gap>`migrate` cannot report where the tables it touched differ from the record's model, nor refuse a Postgres older than the supported one, because comparing them after applying, and `migration check --database`, are not implemented.</gap>
656
662
 
657
663
  ## `migration`
658
664
 
@@ -661,26 +667,40 @@ A project with auth migrations written before the snapshot starts it with `migra
661
667
  :::
662
668
 
663
669
  ```sh
664
- protobase migration [--dir db/migrations] [--extend <dir>]
670
+ protobase migration [--dir db/migrations] [--extend <dir>] [--off keep|archive|delete] [--force]
665
671
  protobase migration --custom <name> [--record-config] [--after]
666
672
  protobase migration check
667
673
  protobase migration baseline [--dir db/migrations] [--extend <dir>]
674
+ protobase migration contract [--hours 24]
675
+ protobase migration delete <module> [--hours 168]
668
676
  protobase migration drop
669
677
  protobase migration up
670
678
  ```
671
679
 
672
- Writes what the config and this version of Protobase need beyond the project's `protobase.snapshot.json` as the project's next migration in `--dir`: one numbered file each run, named after what it holds, such as `004_auth.sql` or `005_changes_webhooks.sql`, after the folder's highest number, and rewrites the snapshot to end at it, so both show in the pull request. The file starts with lines Protobase reads back: `-- protobase:id`, a random id of its own, then the version that wrote it, each sign-in module's last step, and the hash of the snapshot's model once it is applied. The file ends with the statement that records it in `migrations.history` with the snapshot's model, which the server reads at startup (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)); it counts as additive when it holds only sign-in steps. It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
680
+ Writes what the config and this version of Protobase need beyond the project's `protobase.snapshot.json` as the project's next migration in `--dir`: one numbered file each run, named after what it holds, such as `004_auth.sql` or `005_changes_webhooks.sql`, after the folder's highest number, and rewrites the snapshot to end at it, so both show in the pull request. The file starts with lines Protobase reads back: `-- protobase:id`, a random id of its own, then the version that wrote it, each sign-in module's last step, the schema modules' part of the model as JSON (`-- protobase:modules`), and the hash of the snapshot's model once it is applied. The file ends with the statement that records it in `migrations.history` with the snapshot's model, which the server reads at startup (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)), with whether it is additive (see [Changes that break older code](#changes-that-break-older-code)). It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
681
+
682
+ A sign-in module the config turns off is [kept](auth.md#turning-a-module-off): on a terminal it asks what becomes of its tables, keep, archive or delete, keep being the default, and without one it needs `--off`. Archive and delete keep it as keep does until [`contract`](#signing-off-an-update) signs the update off. A kept module turned on again goes on from its step; with `DATABASE_URL` set and rows in its tables, it asks on a terminal whether to bring them back, and needs `--force` without one, and the file it writes then applies with `protobase migrate --force`.
683
+
684
+ The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization, and in `external` the store's relations Protobase did not make, such as the user view of [`users.keyTable`](auth.md#a-view-over-another-systems-users), which no step alters; and `physical`, every schema, table, column and index name the store has. Its `model.modules` holds each built-in schema, each a module with numbered steps, such as the [jobs schema](jobs.md#the-jobs-schema) (`jobs`), the [change capture](events.md#migrations-and-startup) (`changes`) and its [history](history.md#the-table) and [notices](live.md#the-table) tables (`history`, `notices`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`) and their delivery log with `deliveryLog` (`webhook_delivery_log`), the [workflows, versions and runs](workflows.md#turning-them-on) of `workflows` (`workflows`) with their storage configurations and custom steps while those are on (`workflow_storage`, `workflow_custom_steps`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notification_devices`, `notification_history`), each unless a store of the app's own replaces it, the [comments table](comments.md#the-table) (`comments`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), written before the change capture whose triggers capture its events, and the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), and the [query role](assistant.md#the-built-in-backend) of the assistant's read-only queries (`query`), each at its last step and the version of the functions over it, with the names it takes from the config, such as the schema `events`, `webhooks.schema` or `workflows.schema` names, the notifications tables' names and columns and the users table they point at, and the triggers of each captured resource at a digest of their statements; it keeps one the config no longer needs as the migrations left it. That part of the file comes from the snapshot alone too, after the store's: the module's steps after its last one, then its functions where the snapshot has another version, then the triggers of each resource whose statements differ, such as one added or one whose field became sensitive; a file that replaces them with a version the code before does not run on says `-- protobase:breaks-older-code`. A name the config changes, such as `events.schema`, `webhooks.schema` or a notifications table's column, is refused, since Protobase does not write renames; so is turning sign-in on under notifications tables made without it, whose user column then points at no users table. With `DATABASE_URL` set, it refuses to write a module from its first step onto a database that has it already, as made by an earlier version's migration, and names `baseline`. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each followed by its row in `auth_steps`, and for a snapshot whose store has no `auth_steps` yet, that table first, made from `auth_migrations`. Each runs only while `auth_steps` lacks it, so a database that has it already, such as one [`migrate-release`](#release-steps) brought to a newer release, skips it. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`. A store a newer Protobase describes otherwise with no step to apply, such as personal access tokens now holding an organization's rows, gets a file that records it anew and changes nothing in the database. A step whose work cannot run in a transaction leaves it to the file's `.after.sql`, such as the batches that give each personal access token the [default organization](auth.md#the-default-organization) when organizations turn on, and the index it builds concurrently. With organizations on or ever on, the file needs `organizations.default` in the config, and turning them on the first time over a store that may hold users needs `organizations.existingUsersRole`; it refuses without them, as `migration check` reports.
673
685
 
674
- The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization, and in `external` the store's relations Protobase did not make, such as the user view of [`users.keyTable`](auth.md#a-view-over-another-systems-users), which no step alters; and `physical`, every schema, table, column and index name the store has. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each version followed by its row in `auth_migrations`. Each runs only while `auth_migrations` lacks its version, so a database that has it already, such as one [`migrate-release`](#release-steps) brought to a newer release, skips it. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`.
686
+ The rest of the file is what the config still needs of the database, compared with it, under its own comment and named in the file name as in brackets: with [`userTables`](user-tables.md#the-switch), the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`owned_definitions`). It is compared only with `DATABASE_URL` set, against the database with the project's migrations applied, and the command says so without it. The jobs schema is written when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or uses the relay, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date). The rollups and formulas module is written when a resource has [rollup or formula fields](data-config.md#rollups-and-formulas) or is a [time rollup](data-config.md#time-rollups) (`computed`): the `rollups` schema, then per field and rollup the columns, the functions and triggers that keep the rollups, and the tables, indexes and refresh functions of time rollups; a changed one is dropped and made again, and what sets a rollup's values or fills a time rollup goes in the file's `.after.sql`, which runs once its transaction commits. The `derived` schema is written when a resource has [derived values](derived.md), with each value declared and its fill enqueued, and a value no longer declared loses its state. The schemas of user tables (`user_tables`) are written with [`userTables`](user-tables.md#the-switch); the tables users add inside them are data, made while the app serves. The change capture is written when a resource has events, history, live updates or derived values, another's derived values or live updates read it, or `mailFeedback` is on; its history table with history, and its notices table with live updates. The webhooks, workflows, notifications, [status](status.md), [calls](calls.md), comments, mail feedback and unsubscribe modules, the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) and the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) are written while the config turns their feature on, and none of them while it is off; turning a feature off later leaves its tables as they are. Calls write the notices table too, which rings reach open pages through. The [relay](realtime-relay.md#sessions) module, the trigger that ends a deleted session's sockets and `realtime.members` with the triggers that keep it from channel records that list their members, is written with `realtime.relay`, and for an app with sign-in and a live resource whose conversation page has `members`, after the auth store's steps, since its trigger is on the sessions table. The query module, the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as with the function they run through, is written last when the command finds the built-in assistant's key (`query`), with the role's grants on each resource's table but those of the auth store: a resource added writes only its grants, and one removed takes them back. It reads the config merged with those of `--extend` as `dev` merges them, and the `.env` nearest the current directory.
675
687
 
676
- The rest of the file is what the other features the config enables still need of the database, compared with it, each under its own comment and named in the file name as in brackets: the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date) (`jobs`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`changes`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`computed`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`query`), the [comments table](comments.md#the-table) (`comments`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`workflows`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notifications`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`realtime_relay`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`channel_sends`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets and `realtime.members` with the triggers that keep it from channel records that list their members, also for an app with sign-in and a live resource whose conversation page has `members` (`relay`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`user_tables`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`owned_definitions`). Those are compared only with `DATABASE_URL` set, against the database with the project's migrations applied, and the command says so without it. <gap>`protobase migration` cannot write the jobs, change capture, rollup and other feature schemas from the snapshot because recording their models in it is not implemented.</gap> It reads the config merged with those of `--extend` as `dev` merges them, and the `.env` nearest the current directory.
688
+ #### Changes that break older code
677
689
 
678
- - `--custom <name>` writes an empty numbered file, `NNN_<name>.sql`, with Protobase's lines and `-- protobase:custom`, for statements you write by hand, and makes the snapshot end at it. It counts as not additive; once it only adds, put `-- protobase:additive` among its `-- protobase:` lines and `check` lints it with the lint rules Protobase's own steps pass, such as no dropped table or column, no new required column and no unique constraint without a check of the rows. Write the statements above the statement that records it, which stays last; `migrate` fills in its hash and whether it is marked additive from the finished file. With `--record-config`, the snapshot takes the sign-in store's names as the config has them now, each module at the step it was: the file is where you make the store match, such as a rename. With `--after`, it also writes an empty `NNN_<name>.after.sql` beside it, for statements that cannot run in a transaction, such as `create index concurrently if not exists`, which `migrate` runs once the file commits (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)).
679
- - `check`, for CI, writes nothing and exits 1 with a line for each problem: a config or Protobase version that needs steps the migrations lack, a name the config changed, two files that share a number when Protobase wrote one of them, a snapshot that does not end at the newest file Protobase wrote or whose model does not match its `modelHash`, and a hand-written file marked additive that is not.
680
- - `baseline` starts the snapshot of a project whose sign-in store came from auth migrations written before it, such as an app's existing `db/migrations/*_auth.sql`, once: run it with `DATABASE_URL` pointing at the database with those migrations applied. In one read-only transaction it reads the versions the store records in `auth_migrations` and the tables of the store's schema, and writes `NNN_baseline.sql`, which changes nothing and drops nothing and only records itself in `migrations.history`, and `protobase.snapshot.json` describing the store as it is: each module the config has on at the step its recorded versions reach, so the former chain's versions 1 to 8 put each module at its first step; a module that is off but has tables as kept; organizations as ever on when a table whose rows belong to an organization, such as `member`, has the column that names it; and the user table as external when the config reads it through [`users.keyTable`](auth.md#a-view-over-another-systems-users), so no step writes to it; a user table the database has as a view needs `users.keyTable`, naming the table that holds the user ids, and is refused without it. `auth_migrations` stays as it is. Apply the file with the project's other migrations, then run `protobase migration`, which writes only the steps the store lacks, and nothing for a current store. It refuses a project that has a snapshot already, a store without `auth_migrations`, one made before 0.48, which [`auth migration`](#auth-migration) adopts first, a version this Protobase does not ship, and a table a recorded step made that the schema lacks under the name the config gives it, such as one renamed since, naming each. <gap>`baseline` cannot refuse a column renamed since a step made it because recording which columns each step adds is not implemented.</gap> <gap>`baseline` cannot fill an organization column from organization data a store keeps elsewhere, such as `session.active_organization_id`, because organizations as a tenancy axis of the app's own tables are not implemented.</gap>
681
- - `drop` deletes the newest file Protobase wrote and takes the snapshot back to the one before it, from that file's lines, or removes the snapshot with the first file. It refuses while two files share a number or the snapshot does not end at the newest file, so it never deletes another branch's file, and after a file that recorded a changed config, whose snapshot before it only version control has.
690
+ Every file is additive, so the code still running while it deploys, and the version before it once rolled back, still runs on the database, or it breaks older code, and that code refuses to start rather than fail on a request, when the file changes the model the record holds (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)). With `DATABASE_URL` set, `protobase migration` applies the file to the database in a transaction it rolls back, reads the schema before and after, and names what older code loses: a table, column, sequence, function or enum value dropped, renamed or moved, a trigger dropped, disabled or firing on fewer events, a table or column made again with its rows or values lost, a column whose type changes or that becomes `not null`, a required column without a default or one losing its default, and a new constraint or unique index on a table there already, which rows older code writes may break. A view, function, trigger or generated column made again is not lost, and taking back a privilege, which only narrows access, is always allowed. What the sign-in modules' steps take, such as the organization every personal access token needs once organizations turn on, is Protobase's own path: the file then says `-- protobase:breaks-older-code` in its header, with what the steps take under it, and is recorded as not additive. What another part would take is refused before anything is written, naming it, with the way through: write the change by hand with `--custom` and mark the file `-- protobase:breaks-older-code`. Protobase's own parts keep what older code still reads, such as the triggers of a resource that no longer has events, history or live updates while another resource is still captured, so the dispatch job drains what they capture; they follow the resource's fields, so a field made sensitive is no longer copied. Once no resource is captured, the change capture drops them, in a file that says `-- protobase:breaks-older-code`; so does the function and trigger of a rollup field the config no longer has, which the next file drops. A rename or a move is always one file that breaks older code, with no view or trigger in between. A column Protobase adds is retired rather than dropped once the config no longer needs it: the column of a rollup or formula field the config no longer has stays as it is, and putting the field back finds it, with its values; the columns a [sign-in module turned off](auth.md#turning-a-module-off) adds to the tables still on stay under their names, watched for the writes older code still makes, and are in use again, with their values, once it is on again. A resource field's column is the project's own, as is its table: removing the field writes nothing, and dropping the column is a hand-written file marked `-- protobase:breaks-older-code`. [`contract` and `delete`](#signing-off-an-update) write their statements under `-- protobase:contract <id>`, naming the migration that stopped older code from using what they take. <gap>A sign-in step that takes from older code cannot carry `-- protobase:contract` because steps naming the migration that stopped older code from using what they take is not implemented.</gap> A [time rollup](data-config.md#time-rollups) that changes has its table made again and filled from its source, which loses no rows, as its comment marks it as Protobase's: only the columns older code reads that it no longer has are named.
691
+
692
+ - `--custom <name>` writes an empty numbered file, `NNN_<name>.sql`, with Protobase's lines and `-- protobase:custom`, for statements you write by hand, and makes the snapshot end at it. Say what it is among its `-- protobase:` lines, which `check` requires: `-- protobase:additive` once it only adds, which `check` verifies with Postgres's own parser, statement by statement, passing only what adds, such as a new table (not `if not exists`, which may find one with rows), a nullable or defaulted column, a plain index, a constraint or unique index on a table the file makes, a new enum value, a trigger dropped and made again on its table, and `create or replace` of a view or function, which Postgres refuses when its columns, arguments or result change; a dropped default, a renamed enum value and a `delete` inside an `insert` or `update` count as taking from older code; or `-- protobase:breaks-older-code` when it takes from older code what it reads, such as a rename or a dropped column. Either way `migrate` records it as not additive unless it says `-- protobase:additive`. Write the statements above the statement that records it, which stays last; `migrate` fills in its hash and whether it is marked additive from the finished file. With `--record-config`, the snapshot takes the sign-in store's names as the config has them now, each module at the step it was: the file is where you make the store match, such as a rename, and it says `-- protobase:breaks-older-code`. With `--after`, it also writes an empty `NNN_<name>.after.sql` beside it, for statements that cannot run in a transaction, such as `create index concurrently if not exists`, which `migrate` runs once the file commits (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)).
693
+ - `check`, for CI, writes nothing and exits 1 with a line for each problem: a config or Protobase version that needs steps the migrations lack, of the sign-in store or a schema module, or a schema module the snapshot does not record at all, a name the config changed, two files that share a number when Protobase wrote one of them, a snapshot that does not end at the newest file Protobase wrote or whose model does not match its `modelHash`, a hand-written file that says neither `-- protobase:additive` nor `-- protobase:breaks-older-code`, says both, has a statement marked `-- protobase:contract`, which only Protobase writes, or is marked additive while a statement does not only add, and a `-- protobase:contract <id>` that names no file before its own. It also prints a `warning:` line, which leaves the exit code alone, for each statement the `squawk-cli` linter finds that holds a lock blocking reads while it scans or rewrites a table, such as `set not null` or a column type change, and for each statement of a file Protobase wrote that takes from older code without `-- protobase:contract`, such as a formula's column made again.
694
+ - `baseline` describes, once, what the project's earlier migrations made that the snapshot does not record: each schema module the config needs, such as a jobs schema an earlier version's `protobase migration` wrote, read from its catalogue as the step pg-boss's version is at and the version Protobase's functions carry, and refused at a pg-boss version no step records, or a change capture, read as its first step once the outbox is there, `capture()` at its version when its body is the one this version writes, and each resource whose table has triggers calling it, which the next `protobase migration` writes again when they are not the ones the config makes, and refused for an outbox without its `database_role` column or a history table without its indexes, or the rollups and formulas, read as their first step once the `rollups` schema is there, and each rollup's column, formula's column, rollup's function and trigger, and time rollup's table and refresh function found, current when it is what this or, for a rollup or formula, an earlier version made of the config, else made again by the next `protobase migration`, as a time rollup an earlier version made is, and refused where the column or table is the project's own or a rollup's column is of another type, or the `derived` schema, read as its first step once its tables, sequence and indexes are there, with each value `derived.declared` marks, and refused without the sequence, the pending table or their indexes, or the schemas of user tables, read as their first step once every part is there, and refused for a definitions table made before organizations, or the tables of webhooks, workflows and notifications, each read as its first step once its tables are there with every index and, for a devices or history table of the app's own, each column under its configured name and the foreign key to the users, the webhooks' functions at the version their comments carry and the workflows' at version 28, the statuses table read as its first step once it has its columns and the foreign key to the users, the calls schema as its first step once its tables are there and its second once its guest tables are too, the `realtime_relay` and `channels` schemas as their first step once their tables are there, `channels.send()` too, the comments, mail feedback and opt-outs tables as their first step once each is there with every index, the query role as its first step once it and the `query` schema are there, with its function at version 1 when it is the one this version writes, owned by the role and not executable by everyone, each resource whose table it reads, and each table it reads that no resource has, which the next `protobase migration` takes back, and the relay's trigger and `realtime.members` functions at their versions with each listed channel whose triggers are the ones this version writes, enabled on its table and its partitions, else written again by the next `protobase migration`, and refused at an older version or shape no step records, such as webhooks without the indexes their version 2 added, a devices table without its session column, a feedback table whose recipient a complaint cannot leave out, or `realtime.members` functions before their version 3; in a project without a snapshot, the sign-in store too. It writes `NNN_baseline.sql`, which changes nothing and records itself, and the snapshot with them, after which `protobase migration` writes only what they lack. For the sign-in store, it starts the snapshot of a project whose store came from auth migrations written before it, such as an app's existing `db/migrations/*_auth.sql`, once: run it with `DATABASE_URL` pointing at the database with those migrations applied. In one read-only transaction it reads the steps the store records in `auth_steps`, or for a store an earlier Protobase made, the versions it records in `auth_migrations`, and the tables of the store's schema, and writes `NNN_baseline.sql`, which drops nothing, changes nothing but making `auth_steps` from `auth_migrations` where the store lacks it, and records itself in `migrations.history`, and `protobase.snapshot.json` describing the store as it is: each module the config has on at the step its recorded versions reach, so the former chain's versions 1 to 8 put each module at its first step; a module that is off but has tables as kept; organizations as ever on when a table whose rows belong to an organization, such as `member`, has the column that names it; and the user table as external when the config reads it through [`users.keyTable`](auth.md#a-view-over-another-systems-users), so no step writes to it; a user table the database has as a view needs `users.keyTable`, naming the table that holds the user ids, and is refused without it. `auth_migrations` stays as it is, read no more. Apply the file with the project's other migrations, then run `protobase migration`, which writes only the steps the store lacks, and nothing for a current store. It refuses a project whose snapshot records every schema module the database has, a store with neither record, one made before 0.48, which [`auth migration`](#auth-migration) adopts first, a version this Protobase does not ship, and a table a recorded step made that the schema lacks under the name the config gives it, such as one renamed since, naming each. <gap>`baseline` cannot refuse a column renamed since a step made it because recording which columns each step adds is not implemented.</gap> The first `protobase migration` after it keeps the organization of each personal access token that has one, and refuses one without, naming it, rather than give it the [default organization](auth.md#the-default-organization): no other column says where a token works.
695
+ - `drop` deletes the newest file Protobase wrote and takes the snapshot back to the one before it, from that file's lines, or removes the snapshot with the first file. It refuses while two files share a number or the snapshot does not end at the newest file, so it never deletes another branch's file, and after a file that recorded a changed config, or one `contract` or `delete` wrote, whose snapshot before it only version control has.
682
696
  - `up` rewrites the snapshot in this version's format. Every other command refuses a snapshot of an older format, and one of a newer format, which only a newer Protobase reads.
683
697
 
698
+ #### Signing off an update
699
+
700
+ An update that turned a sign-in module off with `--off archive` or `--off delete` keeps its tables, as keep does, until you sign it off: once the update counts as successful, `protobase migration contract` writes the next numbered file, `NNN_contract.sql`, which archives each such module. Every statement in it carries `-- protobase:contract <id>`, naming the file that turned the module off, and the file says `-- protobase:breaks-older-code`. Its first statement refuses, so `migrate` applies none of it, until `migrations.history` has that file's row, a migration applied after it, as the next update applies one, and `--hours` (24 by default) since it was applied. The archive moves the module's tables, with their rows, to the schema `protobase_archive_<n>`, `<n>` being the file's number, after dropping every foreign key between them and the tables still on, in either direction; renames each column the module added to the tables still on to `<column>_archive`; watches both in `retired.writes`, a table's writes under the column `*`; and takes every privilege on that schema and its tables and sequences from each role that owns or holds one, from everyone, and from the role applying the file, so the app's roles get `permission denied`. The snapshot moves the module from `decisions.modules.kept` to `decisions.modules.archived`, with the schema, its tables and the archived columns. A module turned on again after its archive starts from its first step under the live names, with its rows in `auth_steps` reset, as fresh empty tables, except a column it leaves in use while off, such as a personal access token's `organization_id`, which keeps its values and its steps and gets back the foreign key the archive took, not checked against rows whose organization the archive holds, which no longer work; the archive stays as it is, still refused, until it is deleted, and there is no restore from it. Turning it off again with archive or delete is refused while that archive is there.
701
+
702
+ `protobase migration delete <module>` writes the file that removes an archived module for good, never written on its own: its statements, each under `-- protobase:contract` naming the sign-off's file, refuse until that file was applied `--hours` ago (168 by default), and while `retired.writes` counts a write of an archived table or column within those hours, or does not watch one. It then drops the archived tables, the schema once nothing else is in it, and each `<column>_archive`, and, while the module is still off, its rows in `auth_steps`; the snapshot no longer lists it as archived. Archive and delete differ only in the choice the snapshot records: what removes the tables is always `delete`. Dropping what a module retired takes three applications of the migrations, each in an update of its own: the one that turns the module off stops every reader and writer; the sign-off comes in a later one, once another migration was applied after the off file and `--hours` passed since it; and the delete in one after that, `--hours` after the sign-off.
703
+
684
704
  When two branches each write a migration, both rewrite the snapshot, so merging the second reports a conflict in `protobase.snapshot.json`, and the commands refuse until it is resolved. On the second branch, delete its own new file, take the other branch's snapshot, and run `protobase migration` again: it writes the second branch's changes as one file after the other's.
685
705
 
686
706
  ```sh
@@ -712,7 +732,7 @@ Prints the app's entry for the apps file of [Realtime](realtime-relay.md), as JS
712
732
  protobase auth migration [--dir db/migrations] [--name auth]
713
733
  ```
714
734
 
715
- Run inside a project, against its database with the project's migrations applied. It reads the versions the store applied from its `auth_migrations` table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. It starts with Protobase's lines, ends with the statement that records it in `migrations.history`, and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it, and one whose store is current but not in `migrations.history`, such as one migrated before that record, a file that only records it. For a store made before 0.48, without `auth_migrations`, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
735
+ Run inside a project, against its database with the project's migrations applied. It reads the steps the store applied from its `auth_steps` table, or for a store an earlier Protobase made, the versions it applied from `auth_migrations`, which the file then records by step in `auth_steps`, and writes the steps of the modules the config has on that it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. It starts with Protobase's lines, ends with the statement that records it in `migrations.history`, and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it, and one whose store is current but not in `migrations.history`, such as one migrated before that record, a file that only records it. For a store made before 0.48, with neither record, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
716
736
 
717
737
  ## `import supabase`
718
738
 
@@ -70,7 +70,7 @@ Once a resource takes comments, admins get **Comments** (the built-in resource `
70
70
 
71
71
  ## The table
72
72
 
73
- [`protobase migration`](cli.md#migration) adds the schema `comments` with the table `comments.comments`; apply it with the project's other migrations. It has an index for each column the Comments list filters on, and the next migration adds one an earlier version's table lacks. `protobase dev` and `protobase serve` do not start while a resource has comments and the table is missing; without an index added since, they start, and only the Comments list's reads that need it are refused. A deleted record's comments stay in the table.
73
+ [`protobase migration`](cli.md#migration) adds the schema `comments` with the table `comments.comments`; apply it with the project's other migrations. It has an index for each column the Comments list filters on. `protobase dev` and `protobase serve` do not start while a resource has comments and the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks the table. [`protobase migration baseline`](cli.md#migration) records once a table an earlier version's migration made, and refuses one without every index. A deleted record's comments stay in the table.
74
74
 
75
75
  | Column | |
76
76
  | --- | --- |
@@ -162,7 +162,7 @@ export default defineConfig({ runtimeUpdates: false })
162
162
  - **Type:** `{ processes?: 'one' | 'many', sqlSends?: boolean, relay?: { url, app, apiKey, ticketKey, channels, presence? } }`
163
163
  - **Default:** `{ processes: 'one', sqlSends: false }`
164
164
 
165
- How [channels](../channels.md) and [Supabase Realtime](../supabase-realtime.md) are served. With `'one'`, one process serves the app, and broadcasts and presence go between its channels in memory. Set `'many'` when several processes serve the app behind one address: broadcasts and presence then go between the processes through the `realtime_relay` schema of the app's database, which [`protobase migration`](../cli.md#migration) writes and the server checks at start. See [Several processes](../channels.md#several-processes). Set `sqlSends: true` to let SQL in the app's database broadcast to channels with `channels.send()`, from the `channels` schema that `protobase migration` writes and the server checks at start. See [From SQL](../channels.md#from-sql). With `relay`, the app also hands its realtime connections to a relay, so it can sleep while people stay connected; see [Realtime relay](../realtime-relay.md).
165
+ How [channels](../channels.md) and [Supabase Realtime](../supabase-realtime.md) are served. With `'one'`, one process serves the app, and broadcasts and presence go between its channels in memory. Set `'many'` when several processes serve the app behind one address: broadcasts and presence then go between the processes through the `realtime_relay` schema of the app's database, which [`protobase migration`](../cli.md#migration) writes and the server finds in the [record of migrations](../../guides/deploy.md#the-record-of-migrations) at start. See [Several processes](../channels.md#several-processes). Set `sqlSends: true` to let SQL in the app's database broadcast to channels with `channels.send()`, from the `channels` schema that `protobase migration` writes and the server finds in the record of migrations at start. See [From SQL](../channels.md#from-sql). With `relay`, the app also hands its realtime connections to a relay, so it can sleep while people stay connected; see [Realtime relay](../realtime-relay.md).
166
166
 
167
167
  ```ts
168
168
  export default defineConfig({ realtime: { processes: 'many', sqlSends: true } })
@@ -362,7 +362,7 @@ export default defineConfig({ notifications: { history: { table: 'inbox_items' }
362
362
  People set their own status, busy, do not disturb or a text of their own, which the people they share an organization with see, and do not disturb holds their pushes. It needs `auth` with organizations, and its table is written by `protobase migration`. See [Status](../status.md).
363
363
 
364
364
  ```ts
365
- export default defineConfig({ auth: { organizations: true }, status: {} })
365
+ export default defineConfig({ auth: { organizations: { enabled: true, default: { id: 'main', name: 'Main', slug: 'main' } } }, status: {} })
366
366
  ```
367
367
 
368
368
  ## status.schema
@@ -33,7 +33,7 @@ The roles users can hold. `admin` is always included. With [`organizations`](#au
33
33
 
34
34
  ```ts
35
35
  export default defineConfig({
36
- auth: { roles: { manager: { label: 'Manager', grants: ['sales'] }, sales: 'Sales' }, organizations: true },
36
+ auth: { roles: { manager: { label: 'Manager', grants: ['sales'] }, sales: 'Sales' }, organizations: { enabled: true, default: { id: 'main', name: 'Main', slug: 'main' } } },
37
37
  })
38
38
  ```
39
39
 
@@ -50,13 +50,20 @@ export default defineConfig({ auth: { roles: ['admin', 'sales', 'warehouse'], de
50
50
 
51
51
  ## auth.organizations
52
52
 
53
- - **Type:** `true | { create?: 'admins' | 'everyone'; names?: { singular: string; plural: string }; createDescription?: string; creatorAppRoles?: 'all' | string[]; invitationDays?: number; membershipLimit?: number; deleteRecords?: 'refuse' | 'cascade'; invitationUrl?: string }`
53
+ - **Type:** `{ enabled: boolean; default?: { id: string; name: string; slug: string }; existingUsersRole?: string; create?: 'admins' | 'everyone'; names?: { singular: string; plural: string }; createDescription?: string; creatorAppRoles?: 'all' | string[]; invitationDays?: number; membershipLimit?: number; deleteRecords?: 'refuse' | 'cascade'; invitationUrl?: string }`
54
54
  - **Default:** off: the app works as one organization
55
55
 
56
- Turns on organizations: people work in one at a time, records of `.tenant` resources are scoped to it, and roles are held globally or per membership. `create` is who may create one (default `admins`), `names` what the screens call an organization, as a view's names are written (default Organization), `createDescription` a line under the title of the screen where someone names their first, `creatorAppRoles` the roles its creator holds there (default `all`), `invitationDays` how long an invitation works (default 7), `membershipLimit` the most members (default 1000), `deleteRecords` whether deleting one is refused while it has records (`refuse`, the default) or left to the foreign keys (`cascade`), and `invitationUrl` the page an invitation opens (default `/-/invitation` on the origin the invitation was made on). Its hooks are in `auth/hooks.ts`. See [Organizations](../auth.md#organizations) and [First organization](../auth.md#first-organization-and-start-address).
56
+ `enabled: true` turns on organizations: people work in one at a time, records of `.tenant` resources are scoped to it, and roles are held globally or per membership. `create` is who may create one (default `admins`), `names` what the screens call an organization, as a view's names are written (default Organization), `createDescription` a line under the title of the screen where someone names their first, `creatorAppRoles` the roles its creator holds there (default `all`), `invitationDays` how long an invitation works (default 7), `membershipLimit` the most members (default 1000), `deleteRecords` whether deleting one is refused while it has records (`refuse`, the default) or left to the foreign keys (`cascade`), and `invitationUrl` the page an invitation opens (default `/-/invitation` on the origin the invitation was made on). Its hooks are in `auth/hooks.ts`. See [Organizations](../auth.md#organizations) and [First organization](../auth.md#first-organization-and-start-address).
57
+
58
+ `default` is the default organization: the one that stands in for every organization while they are off, which [`protobase migration`](../cli.md#migration) makes when they turn on and records in `protobase.snapshot.json`. It refuses without it once organizations are on or were ever on, so turning them off is `enabled: false` with `default` kept. `existingUsersRole` is the app role, one a member can hold, that each user there already gets in the default organization when organizations turn on for the first time; it is required then, unless the store is new and holds no users. See [The default organization](../auth.md#the-default-organization).
57
59
 
58
60
  ```ts
59
- export default defineConfig({ auth: { organizations: { create: 'everyone', invitationDays: 14, names: { singular: 'Workspace', plural: 'Workspaces' } } } })
61
+ export default defineConfig({
62
+ auth: {
63
+ roles: { sales: 'Sales' },
64
+ organizations: { enabled: true, default: { id: 'main', name: 'Main', slug: 'main' }, existingUsersRole: 'sales', create: 'everyone', invitationDays: 14 },
65
+ },
66
+ })
60
67
  ```
61
68
 
62
69
  ## auth.signUp
@@ -177,6 +184,17 @@ The OpenID Connect providers the platform adds for people who already have an ac
177
184
  export default defineConfig({ auth: { signInProviders: [] } })
178
185
  ```
179
186
 
187
+ ## auth.signInDevices
188
+
189
+ - **Type:** `boolean`
190
+ - **Default:** `false`
191
+
192
+ Lets the platform's sign-in providers from the environment sign in [devices](../auth.md#device-accounts) (`PROTOBASE_SIGN_IN_DEVICES=true`), and makes their tables with the next `protobase migration`. Without it, such a provider stops the server at startup. A provider of `auth.signInProviders` with `devices: true` needs no switch.
193
+
194
+ ```ts
195
+ export default defineConfig({ auth: { signInDevices: true } })
196
+ ```
197
+
180
198
  ## auth.operator
181
199
 
182
200
  - **Type:** `{ issuer: string; clientId: string; clientSecret: string; name?: string; group?: string; scopes?: string[]; acrValues?: string[]; sessionMinutes?: number } | false`
@@ -12,7 +12,7 @@ import { defineConfig } from '@protobase/config'
12
12
 
13
13
  export default defineConfig({
14
14
  timezone: 'Europe/Amsterdam',
15
- auth: { roles: ['admin', 'sales'], organizations: true },
15
+ auth: { roles: { sales: 'Sales' }, organizations: { enabled: true, default: { id: 'main', name: 'Main', slug: 'main' } } },
16
16
  jobs: {
17
17
  'send-invoice': { description: 'Mails an invoice to its customer.', arguments: { invoiceId: 'bigint' }, maxAttempts: 5 },
18
18
  },
@@ -163,7 +163,7 @@ Not yet:
163
163
  - <gap>A rollup through a relation of several columns is not supported yet.</gap>
164
164
  :::
165
165
 
166
- A **rollup** is a value of the other records that point at a record, such as an order's total of its lines. A **formula** is a value computed from the record's own fields, such as a line's amount. Neither needs SQL: you declare the field, and [`protobase migration`](cli.md#migration) writes its column into the project's next migration (`NNN_computed.sql`). Both are real columns, kept by the database in the transaction that writes, so they are right for writes from psql or other services too, and they filter and sort like any column once they have an index.
166
+ A **rollup** is a value of the other records that point at a record, such as an order's total of its lines. A **formula** is a value computed from the record's own fields, such as a line's amount. Neither needs SQL: you declare the field, and [`protobase migration`](cli.md#migration) writes its column into the project's next migration (`NNN_computed.sql`), from the project's snapshot, without a database. A resource's table without a schema in `.table()` is taken to be in `public`; name the schema of one elsewhere, such as `.table('sales.orders')`. Both are real columns, kept by the database in the transaction that writes, so they are right for writes from psql or other services too, and they filter and sort like any column once they have an index.
167
167
 
168
168
  ```ts title="docs-examples/reference/rollups.ts"
169
169
  import { f, resource } from '@protobase/schema'
@@ -207,11 +207,11 @@ export const orderLines = resource('order_lines')
207
207
  | `avg` | The average of `field`. Empty without records. | `f.decimal()`, `.optional()` |
208
208
  | `min`, `max` | The least or greatest value of `field`. Empty without records. | a number field, `.optional()` |
209
209
 
210
- Empty values of `field` are left out, as in SQL. The migration adds the column, a function in the `rollups` schema and a trigger on `from`'s table that sets the value after every insert, delete and update of the columns it reads, and then sets every record's value once. <gap>A rollup over its own table is not supported yet.</gap> <gap>A rollup on a resource with a key of several columns is not supported yet.</gap> <gap>A rollup through a relation of several columns is not supported yet.</gap>
210
+ Empty values of `field` are left out, as in SQL. The migration adds the column, a function in the `rollups` schema and a trigger on `from`'s table that sets the value after every insert, delete and update of the columns it reads, and then sets every record's value once, in the migration's `.after.sql`, which runs after its transaction commits so a large table is not set inside it. When the rollup changes, or the formula it reads, the migration drops its function, which takes the trigger with it, writes both again and sets the values again. <gap>A rollup over its own table is not supported yet.</gap> <gap>A rollup on a resource with a key of several columns is not supported yet.</gap> <gap>A rollup through a relation of several columns is not supported yet.</gap>
211
211
 
212
- `.formula(expression)` is a Postgres generated column. The expression reads the record's number fields, and takes numbers, `+ - * /`, parentheses, `coalesce(a, b, ...)` and `round(x)` or `round(x, digits)`. It is computed exactly as decimals, so `7 / 2` is 3.5, and is stored as the field's type, so an integer field rounds the result. A formula that reads an optional field is `.optional()` too, unless `coalesce()` gives that field a value. A formula cannot read another formula. When the expression changes, the migration drops the column and adds it again, so an index on it must be created again in the same migration.
212
+ `.formula(expression)` is a Postgres generated column. The expression reads the record's number fields, and takes numbers, `+ - * /`, parentheses, `coalesce(a, b, ...)` and `round(x)` or `round(x, digits)`. It is computed exactly as decimals, so `7 / 2` is 3.5, and is stored as the field's type, so an integer field rounds the result. A formula that reads an optional field is `.optional()` too, unless `coalesce()` gives that field a value. A formula cannot read another formula. When the expression changes, the migration drops the column and adds it again, so an index on it must be created again in the same migration; so does a rollup's column whose type changes.
213
213
 
214
- Neither field can be written through the API, have a default, or be sensitive, an AI field, a file, or the key, tenant, owner or soft delete field, and a formula cannot read a sensitive field. The server does not start while a declared column, function or trigger is missing or out of date, with a message that names the fields; the migration fixes that. It stops with an error, without writing anything, when the column already exists as the project's own: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type.
214
+ Neither field can be written through the API, have a default, or be sensitive, an AI field, a file, or the key, tenant, owner or soft delete field, and a formula cannot read a sensitive field. The server does not start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks a declared field's column, function or trigger, or has it otherwise, with a message that names the fields; the migration fixes that. A column that already exists as the project's own makes the migration fail when it is applied; [`protobase migration baseline`](cli.md#migration) refuses one where a formula or rollup is declared: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type. The column of a field the config no longer has stays, and putting the field back finds it; the function and trigger of a rollup go with it.
215
215
 
216
216
  ## Lookups
217
217
 
@@ -283,7 +283,7 @@ export const orders = resource('orders')
283
283
  A rollup cannot yet group by an optional field or roll up a source with some access rules, as the marked limits below say.
284
284
  :::
285
285
 
286
- A large events table, such as millions of meter readings, gets a **time rollup**: a table with one row per hour or day and per group, holding how many records fell in it and the sums and greatest values of their numbers. A chart over months then reads a few thousand rows instead of millions. You declare the rollup as a resource over the events resource, and [`protobase migration`](cli.md#migration) writes its table, indexes and refresh function into the project's next migration (`NNN_computed.sql`), with the rollup filled once. From then on the app keeps it up to date by itself, at most a minute behind. It is plain Postgres: no extension.
286
+ A large events table, such as millions of meter readings, gets a **time rollup**: a table with one row per hour or day and per group, holding how many records fell in it and the sums and greatest values of their numbers. A chart over months then reads a few thousand rows instead of millions. You declare the rollup as a resource over the events resource, and [`protobase migration`](cli.md#migration) writes its table, indexes and refresh function into the project's next migration (`NNN_computed.sql`), with the rollup filled once in the migration's `.after.sql`, after its transaction commits. From then on the app keeps it up to date by itself, at most a minute behind. It is plain Postgres: no extension.
287
287
 
288
288
  ```ts title="docs-examples/reference/time-rollups.ts"
289
289
  import { f, resource } from '@protobase/schema'
@@ -336,11 +336,11 @@ The rollup's records have these fields, all read-only:
336
336
  | `bucket` | The start of the hour or day. Filterable and sortable. |
337
337
  | the `by` fields | The group's values, under the source's field names. Filterable and sortable. |
338
338
  | `events` | How many records of the source fell in the bucket, as a bigint. |
339
- | `<field>_sum` | The sum of the field: a bigint for an integer, a decimal of ten more digits for a bigint or a decimal. Empty when every value was. |
340
- | `<field>_max` | The greatest value of the field, of its type. Empty when every value was. |
339
+ | `<field>_sum` | The sum of the field, of the type Postgres's `sum` gives: a bigint for an integer, a numeric for a bigint or a decimal. Empty when every value was. |
340
+ | `<field>_max` | The greatest value of the field, of its column's type. Empty when every value was. |
341
341
  | `<field>_count` | How many records of the bucket have a value of the field, as a bigint, for every field in `measures`. |
342
342
 
343
- Records the source soft deleted are left out. The migration creates the table in the rollup's schema, with a unique index on `(bucket, by...)` and an index on `(group, bucket)` per group, so a list filtered on the bucket, on a group or on both passes the [scan guard](api.md#safety). It writes `rollups.<table>_refresh(from timestamptz)`, which recomputes every bucket from the one `from` falls in, in one statement: it upserts their counts, sums and greatest values and deletes those left without records. When the rollup's declaration changes, the migration drops its table and creates and fills it again. The table and function of a rollup the config no longer has stay; a migration of your own drops them, in a deploy after the one that stops reading them.
343
+ Records the source soft deleted are left out. The migration creates the table in the rollup's schema, or `public` when its `.table()` names none, from the query its refresh runs, so its columns take the source's types, with a unique index on `(bucket, by...)` and an index on `(group, bucket)` per group, so a list filtered on the bucket, on a group or on both passes the [scan guard](api.md#safety). It writes `rollups.<table>_refresh(from timestamptz)`, which recomputes every bucket from the one `from` falls in, in one statement: it upserts their counts, sums and greatest values and deletes those left without records. When the rollup's declaration changes, or the type of a field it reads, the migration drops its table and creates and fills it again. A change of a source column's type that its field does not show, such as a longer `varchar`, is not seen: change the rollup's declaration too, or alter its table in a migration of your own. The table and function of a rollup the config no longer has stay; a migration of your own drops them, in a deploy after the one that stops reading them.
344
344
 
345
345
  Only the database writes a rollup's rows: creates, updates and deletes are refused whatever its rules say, and it cannot have soft delete, a manual order, an author, a parent or `.openExisting()`. Its access is its own `.access()`: the source's rules do not reach it, so give it rules that let read only those who may see every record of a group. Its tenant is the source's, which is why `by` includes it. A field that is sensitive or has its own read rule, such as `.access({ read: roles.can('costs.read') })`, cannot be grouped by or measured, and one with its own read rule cannot be the rollup's `time`, since a bucket would show it to anyone who reads the rollup. The server does not start while the source has its own `read` or `list` rule in `.access()`, whatever the rule returns, or while a role reads only some of the source's records that a bucket mixes with others: `.own` or `.team` while `by` does not include the source's owner field, or a role's filter on fields outside `by`. <gap>A time rollup cannot group by an optional field because a bucket key with empty parts is not implemented.</gap> <gap>A time rollup cannot roll up a resource whose reads follow a parent because applying the parent's access to buckets is not implemented.</gap> <gap>A time rollup cannot roll up a resource with its own `read` or `list` access rule because declaring the fields such a rule filters on is not implemented.</gap>
346
346
 
@@ -350,7 +350,7 @@ The app's [jobs](jobs.md) keep every time rollup up to date: a built-in [recurri
350
350
 
351
351
  A record that arrives, or changes, later than `late` after its time, such as one imported from an older history, is counted only by a refresh from before it: [`protobase buckets rebuild`](cli.md#buckets-rebuild) recounts a rollup from an earlier time, such as `protobase buckets rebuild readings_hourly --from 2026-07-01`, which recomputes every bucket from that day's first hour in one statement, or every bucket without `--from`.
352
352
 
353
- The server does not start while a rollup's table or function is missing or out of date, with a message that names the rollup; the migration fixes that. It stops with an error, without writing anything, when the table already exists as the project's own.
353
+ The server does not start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks a rollup's table or function, or has it otherwise, with a message that names the rollup; the migration fixes that. A table that already exists as the project's own makes the migration fail when it is applied, and `protobase migration baseline` refuses it.
354
354
 
355
355
  ### Charts over a rollup
356
356
 
@@ -87,7 +87,7 @@ Runs are `derived.compute` jobs, four at a time per worker, retried like any [jo
87
87
 
88
88
  ## State
89
89
 
90
- `protobase migration` adds a `derived` schema, applied with the project's other migrations, and `protobase dev` and `protobase serve` do not start without it:
90
+ `protobase migration` writes the `derived` schema from the project's snapshot as numbered steps, applied with the project's other migrations, with each derived value declared and the job that computes its records once enqueued; a value the config no longer declares loses its state in the next migration, so declaring it again fills it again. `protobase dev` and `protobase serve` do not start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks the schema or a declared value. [`protobase migration baseline`](cli.md#migration) records a schema an earlier version made, and refuses one without the versions sequence, the pending table or their indexes:
91
91
 
92
92
  | Table | |
93
93
  | --- | --- |
@@ -283,7 +283,7 @@ Mail you mark as bulk carries a one-click unsubscribe, as large mailbox provider
283
283
 
284
284
  **Bulk** is mail the recipient did not ask for by an action of their own: newsletters, digests, announcements and marketing. **Transactional** mail answers something the recipient did or needs to act on, such as a password reset, a sign-in code, a receipt or an invoice: it is not marked bulk and carries no unsubscribe. Protobase's own mail is transactional.
285
285
 
286
- Turn it on in the config, then run `protobase migration`, which writes its table, `mail.unsubscribes`, as a migration of the project's own, and apply it with the project's migrations: `protobase serve` refuses to start while the table or its unique index is missing, and names the migration to write. Its links are on the app's [`url`](config/app.md#url), which must be `https://` but on `localhost`, and signed with its [`secret`](config/app.md#secret):
286
+ Turn it on in the config, then run `protobase migration`, which writes its table, `mail.unsubscribes`, as a migration of the project's own, and apply it with the project's migrations: `protobase serve` refuses to start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks the table, and names the migration to write. Its links are on the app's [`url`](config/app.md#url), which must be `https://` but on `localhost`, and signed with its [`secret`](config/app.md#secret):
287
287
 
288
288
  ```ts
289
289
  export default defineConfig({ unsubscribe: true })
@@ -319,7 +319,7 @@ Amazon SES (through SNS) and Resend report to their own endpoints so far, beside
319
319
 
320
320
  A mail provider tells the app when a message bounced or its recipient marked it as spam. With `mailFeedback` on, each report becomes a `mail_feedback` record, one per recipient, or one for a complaint that hides who complained, with the events `mail_feedback.bounced` and `mail_feedback.complained`, which [workflows](workflows.md), [subscriptions](webhooks.md) and your own code act on, such as marking a contact's address undeliverable. Protobase records and notifies only: it keeps sending to the address, and the app decides what a bounce means.
321
321
 
322
- Turn it on in the config, then run `protobase migration`, which writes its table, `mail.feedback`, and the capture of its events as migrations of the project's own; apply them with the project's migrations, as `protobase serve` refuses to start while the table is missing:
322
+ Turn it on in the config, then run `protobase migration`, which writes its table, `mail.feedback`, and the capture of its events as migrations of the project's own; apply them with the project's migrations, as `protobase serve` refuses to start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks the table:
323
323
 
324
324
  ```ts
325
325
  export default defineConfig({ mailFeedback: true })
@@ -102,9 +102,9 @@ export default defineConfig({ events: { schema: 'row_changes' } })
102
102
 
103
103
  ## Migrations and startup
104
104
 
105
- [`protobase migration`](cli.md#migration) compares the database with the resources' events and writes what it lacks as the project's next migrations: the jobs schema, then the `changes` schema, the function, and a trigger pair per resource with events. Apply it with the project's other migrations. A trigger changes when the resource's fields do, a field that became sensitive for instance, so run the command after changing the config. Once a resource has no events, the next migration drops its triggers; it never drops a table.
105
+ [`protobase migration`](cli.md#migration) writes what the project's `protobase.snapshot.json` lacks of the change capture as the project's next migration: the jobs schema, then the `changes` schema with the outbox, the function, and a trigger pair per resource with events, each a module with numbered steps that the snapshot and the record of migrations hold. Apply it with the project's other migrations. A trigger changes when the resource's fields do, a field that became sensitive for instance, so run the command after changing the config. Once a resource has no events, it keeps its triggers while another resource is still captured, so the code still running drains what they capture, and the migration once none is drops them, saying it breaks older code; it never drops a table. <gap>`protobase migration` cannot refuse a trigger of the app's own named like the capture's, `<table>_changes` or `<table>_changes_update`, which the file replaces, because reading the database's triggers before writing is not implemented.</gap>
106
106
 
107
- `protobase dev` and `protobase serve` do not start while a resource with events lacks its triggers, or has out-of-date ones, or the jobs schema is missing, and name the command to run. `dev` checks again whenever it reloads the config. Neither changes the schema itself.
107
+ `protobase dev` and `protobase serve` do not start while the record of migrations lacks the change capture, a resource's triggers as the config makes them, or the jobs schema, and name what to run. `dev` checks again whenever the config it reloads changes what it needs. Neither changes the schema itself.
108
108
 
109
109
  ## The outbox
110
110
 
@@ -83,7 +83,7 @@ Once a resource has history, admins get **Activity** (the built-in resource `rec
83
83
 
84
84
  ## The table
85
85
 
86
- [`protobase migration`](cli.md#migration) adds the table `changes.history` to the `changes` schema of the event capture (renamed with `events: { schema }`), and the capture triggers of each resource with history; apply it with the project's other migrations. It has an index for each column the Activity list filters on, and the next migration adds one an earlier version's table lacks. `protobase dev` and `protobase serve` do not start while the table or a trigger is missing; without an index added since, they start, and only the Activity list's reads that need it are refused. A resource that drops `.history()` loses its triggers, unless it has events, at the next migration; its changes stay in the table.
86
+ [`protobase migration`](cli.md#migration) adds the table `changes.history` to the `changes` schema of the event capture (renamed with `events: { schema }`), and the capture triggers of each resource with history; apply it with the project's other migrations. It has an index for each column the Activity list filters on. `protobase dev` and `protobase serve` do not start while the record of migrations lacks the table or a trigger. A resource that drops `.history()` keeps its triggers while another resource is captured, and loses them at the migration once none is; its changes stay in the table.
87
87
 
88
88
  | Column | |
89
89
  | --- | --- |
@@ -53,7 +53,7 @@ export default (async ({ invoiceId }, { db }) => {
53
53
  | its name | Letters, digits, `_`, `-`, `.` and `/`; the file `jobs/<name>.ts` holds what it does. |
54
54
  | `description` | What the job does, for the people who read the config. |
55
55
  | `arguments` | Its arguments by name, each a [field type](data-config.md#field-types) such as `'integer'` or `'bigint'`, or the type with options: `{ type: 'enum', values: ['day', 'week'] }`, `{ type: 'text', min: 1 }`, `{ type: 'integer', optional: true }`, `{ type: 'decimal', precision: 8, scale: 2 }`. Each value is checked as a field of that type checks it, when the job is enqueued and again before it runs, and no other argument is taken. A payload refused at run time fails the job for good. The same is JSON in a `protobase.config.json`. |
56
- | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, decryptField, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`, its payload `JobPayload<typeof config, '<name>'>` (see [Typed names and payloads](#typed-names-and-payloads)): the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `decryptField(resource, key, field)` reads an encrypted field's value, audited, see [Reading in jobs and functions](data-config.md#reading-in-jobs-and-functions). `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. It is `undefined` in an app without [`notifications`](config/jobs-and-events.md#notifications). |
56
+ | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, decryptField, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`, its payload `JobPayload<typeof config, '<name>'>` (see [Typed names and payloads](#typed-names-and-payloads)): the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `db` works in the organization of the `db` the job was enqueued with, such as a function's in a request, and sees only that organization's rows of the [organization's tables](../guides/api-functions.md#the-organizations-tables); a job enqueued with `db.unscoped(...)`, a plain database or from SQL, and a recurring job, works in none, so `db` reads no row of those tables and writes none, unless `db.unscoped('<reason>')`. The payload never sets the organization. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `decryptField(resource, key, field)` reads an encrypted field's value, audited, see [Reading in jobs and functions](data-config.md#reading-in-jobs-and-functions). `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. It is `undefined` in an app without [`notifications`](config/jobs-and-events.md#notifications). |
57
57
  | `maxAttempts` | Tries before the job is kept as failed; default 10. |
58
58
  | `retryDelay`, `maxRetryDelay` | The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default `2s` and `1 hour`. Milliseconds or text such as `30 seconds`. |
59
59
  | `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
@@ -114,7 +114,7 @@ select jobs.enqueue('send-invoice', '{"invoiceId": 7}', run_at => now() + interv
114
114
  select jobs.enqueue('sync-customer', '{"customerId": 3, "fields": ["email"]}', group_key => 'customer:3');
115
115
  ```
116
116
 
117
- `jobs.enqueue(job_name, payload, run_at, key, group_key, priority)` returns the job's id. A `key` dedupes as `mode: 'dedupe'` does. The job takes its retry settings from its definition, as the workers last saw it; a job no worker has started yet gets pg-boss's defaults until one does.
117
+ `jobs.enqueue(job_name, payload, run_at, key, group_key, priority)` returns the job's id. The job works in no organization. The payload is stored as given, and the runtime keeps a job's organization under a top-level `~organization` key beside it, so never pass an object a request shapes, whose keys it chooses, as the whole payload. <gap>`jobs.enqueue` cannot keep a payload's own `~organization` key as payload because an organization argument of its own is not implemented.</gap> A `key` dedupes as `mode: 'dedupe'` does. The job takes its retry settings from its definition, as the workers last saw it; a job no worker has started yet gets pg-boss's defaults until one does.
118
118
 
119
119
  ## Mail
120
120
 
@@ -174,13 +174,13 @@ A host that stops an idle app needs to know when a job is due, and to have it ru
174
174
 
175
175
  ## The `jobs` schema
176
176
 
177
- The schema is pg-boss's tables at its pinned schema version, plus Protobase's `jobs.enqueue`, `jobs.next_due` and `jobs.failed`. It is created and upgraded like the [auth schema](auth.md#migrations), by the project's migrations:
177
+ The schema is pg-boss's tables at its pinned schema version, plus Protobase's `jobs.enqueue`, `jobs.next_due` and `jobs.failed`. It is a module with numbered steps, like the [auth schema](auth.md#migrations), created and upgraded by the project's migrations:
178
178
 
179
179
  ```sh
180
- bun run protobase migration # writes db/migrations/NNN_jobs.sql when the jobs schema is missing or behind
180
+ bun run protobase migration # writes db/migrations/NNN_jobs.sql when the snapshot lacks the jobs schema's steps
181
181
  bun run db:migrate
182
182
  ```
183
183
 
184
- [`protobase migration`](cli.md#migration) writes what the database lacks, taken from pg-boss's own construction and migration plans for the pinned version, without their `BEGIN` and `COMMIT` and with any `CONCURRENTLY` index build made a plain one, so the file runs in the project's migration transaction. The server never creates or migrates it: `protobase dev` and `protobase serve` read its version at startup and refuse to start while it is missing or behind, naming the command. A database whose jobs schema is newer than the running Protobase is refused too.
184
+ Step 1 is pg-boss's own construction plan for schema version 45, copied into Protobase without its `BEGIN` and `COMMIT` and with any `CONCURRENTLY` index build made a plain one, so the file runs in the project's migration transaction; pg-boss stays pinned to an exact version, and a newer pg-boss comes with a step of its own holding its migration plan. Protobase's functions are written whole at their version after the steps, and again when a newer Protobase changes them. [`protobase migration`](cli.md#migration) writes both from `protobase.snapshot.json` alone, which records the step and the functions' version. The server never creates or migrates it: `protobase dev`, `protobase serve` and `protobase worker` read the [record of migrations](../guides/deploy.md#the-record-of-migrations) at startup and refuse to start while it lacks the jobs schema or has it at an older step or functions version, naming what is missing. A jobs schema an earlier version's `protobase migration` wrote, before the snapshot recorded it, is described once with [`protobase migration baseline`](cli.md#migration).
185
185
 
186
186
  pg-boss runs here without what needs a session of its own: no `LISTEN`/`NOTIFY` (a job enqueued in the same process wakes its worker directly, the rest is polled), only transaction-scoped advisory locks, unnamed prepared statements, no index rebuilds and no instance registry. It works through PgBouncer in transaction mode, over the app's own connection pool.