# From 0.82 to 0.83

> What to change when upgrading from better-supabase 0.82 to 0.83. Direct dependencies, the blocks list, project-level defaults, config the render already supplies, authorization facts that move into the provider, Supabase CLI 3.2.0, and the task coordination changes with the tasks module at version 7, claimNext picking only your own tasks by default, category stages, hold kinds, task reservations and before_task_close on every close.

Source: https://bettersupabase.com/docs/migration/0.82-to-0.83

0.83 shrinks the config. Facts the project, the schema files or the
authorization provider already state are no longer written twice. It is a minor
release, and below 1.0 a minor version may carry breaking changes. Each change
is also in the
[changelog](https://github.com/ScaleDockHQ/better-supabase/blob/main/packages/better-supabase/CHANGELOG.md).

0.83 also closes five gaps in the task coordination that shipped in 0.82. Run
`better-supabase upgrade` to move the `tasks` module to version 7; the
[Task coordination](#task-coordination) section lists what each change needs.

0.82.0 on npm has none of this work: it has no `actionKeys`, no
`operations[].approval`, no `doctor.command`, no grouped baseline, no BS427 and
no `codemod config --prune`. 0.83.0 is the first version with the features on
this page, so read it as the one guide for the step from 0.82.

Run the codemods in this order, then review the diff and the render:

```bash
pnpm better-supabase codemod blocks-list
pnpm better-supabase codemod config --prune
pnpm better-supabase gen sql
```

| Section                                                                   | Needs code                                                                                |
| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| [Direct dependencies](#direct-dependencies)                               | Remove pg-delta and pg-topo from your `package.json`                                      |
| [The blocks list](#the-blocks-list)                                       | Run `codemod blocks-list`                                                                 |
| [Project-level defaults](#project-level-defaults)                         | Review the numbering tenant column                                                        |
| [Config the render already supplies](#config-the-render-already-supplies) | Run `codemod config --prune`                                                              |
| [Provider fields](#provider-fields)                                       | Move keys and floors to the provider                                                      |
| [Record types](#record-types)                                             | Run `codemod record-types`                                                                |
| [Table facts in comments](#table-facts-in-comments)                       | Run `codemod table-tags`                                                                  |
| [Optional columns](#optional-columns)                                     | Declare `startPart`, `endPart` or `confidential` columns, or run `codemod config --prune` |
| [Block names first](#block-names-first)                                   | Optional: run `codemod adopt-names --table <block>.<table>`, or tag the table             |
| [Declared rows](#declared-rows)                                           | Optional: run `codemod declared-rows`, then `db rows`                                     |
| [Schemas by module reference](#schemas-by-module-reference)               | None                                                                                      |
| [Task coordination](#task-coordination)                                   | Review the five task changes below, then run `better-supabase upgrade`                    |
| [claimNext picks assigned tasks](#claimnext)                              | Set `claims.next: "any"` to keep the old pick                                             |
| [Category stages](#category-stages)                                       | None; new option form                                                                     |
| [Hold kinds](#hold-kinds)                                                 | None; new options                                                                         |
| [Reserve a task for a profile](#reserve-a-task)                           | Read `delegateProfile` if you stored the old label                                        |
| [before_task_close on every close](#before-task-close)                    | Check a hook that relied on running only in close                                         |
| [SQL reading](#sql-reading)                                               | Stop importing the SQL text readers from `better-supabase/sql`                            |
| [Doctor](#doctor)                                                         | Run `codemod doctor-baseline`                                                             |

## What the codemods did to CentraKit [#what-the-codemods-did-to-centrakit]

`scripts/cutover-report.ts` copies a project, renders it with the 0.82 baseline, runs the
codemods in the order above, and renders again with this release. For CentraKit it
reported these config lines per top-level key of `better-supabase.config.ts`.

| Section       | Before | After |
| ------------- | -----: | ----: |
| `blocks`      |   2931 |  2614 |
| preamble      |    239 |   239 |
| `recordTypes` |    225 |   225 |
| `database`    |    174 |   104 |
| `gen`         |     54 |    20 |
| `auth`        |     27 |    27 |
| `tooling`     |      7 |     7 |
| **Total**     |   3657 |  3236 |

The target of 2500 lines is not met: 737 lines remain over it, 2614 of them in `blocks`, led by
`memberships` (215), `calendar` (126), `invoices` (115), `audit` (112) and `data-lifecycle` (105). The 564
entries that stay each state a fact the SQL does not hold.

| Kept entries | Reason                                                          |
| -----------: | --------------------------------------------------------------- |
|          206 | the database column differs from the convention's name          |
|          129 | a choice the SQL does not declare: it exists only in the config |
|           68 | the database table differs from the block's default             |
|           60 | drops a generated column the database lacks                     |
|           40 | the api schema or exposure differs from the preset              |
|           31 | a block setting the convention does not cover                   |
|           22 | the block has no table here                                     |
|            8 | an api object with an explicit function list                    |

No codemod can remove these. Reaching 2500 needs the app to drop options it no longer uses (doctor
BS707 lists them), to rename database columns to the convention, or to move more facts into the
provider and the schema comments.

The render differs in 16 files. These changes are expected: the tax code index, the cancel hooks, the
numbering default, template clone and import functions, and the render comments. The other files
come from block fixes and features that landed between 0.82.0 and this release, not from the
codemods:

| File                                                                       | Change                                                                                                                                   |
| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `module_000_prelude.sql`                                                   | `better_supabase.declared_defaults` and its lookup `declared_defaults_of` hold declared rows                                             |
| `module_092_pipelines.sql`, `module_184_option_sets.sql`                   | the default stages and items come from declared rows when a declaration exists; with none, the lookup returns null and the old rows seed |
| `module_004_memberships.sql`                                               | `inventory_level_signals` and `inventory_reorder_rules` gain a same-tenant check on `variant_id`, one trigger on each table              |
| `module_145_tax.sql`                                                       | the tax data module is at version 2                                                                                                      |
| `module_023_outbox.sql`                                                    | a consumer's start never passes the snapshot's xmax                                                                                      |
| `module_034_attachments.sql`                                               | a subject id that is not a uuid reads as not found instead of failing the cast                                                           |
| `module_064_imports.sql`                                                   | supplier and customer entities resolve earlier records; a dry run's cancel clears chunks                                                 |
| `module_069_catalog.sql`                                                   | a supplier item takes its supplier from an earlier imported entity                                                                       |
| `module_077_approvals.sql`                                                 | cancelling an approval calls the timesheet and expense cancel functions                                                                  |
| `module_088_time_entries.sql`                                              | `timesheet_approval_cancelled` returns a submitted week to open                                                                          |
| `module_121_expenses.sql`                                                  | `expense_approval_cancelled`; a rejected expense stays visible to an employee without a user                                             |
| `module_091_tasks.sql`, `module_097_quotes.sql`, `module_098_invoices.sql` | a clone may move to another tenant with `tenantId`, checked against the target                                                           |
| `module_110_leave.sql`                                                     | a request that was approved and later rejected is no longer treated as rejected                                                          |

The report found one regression of this branch and fixed it: the `table-tags` codemod appends
`; grant ...` after a `@bsb fields` list, and the list reader dropped its last column
(`start_time`, `vat_regime`, `workflow_run_id`, `description`). That rendered fields away in five
files. The reader now ends the list at the next tag.
Five adopter files become deletable: `secret_fields.sql`, `packages/supabase-runtime/src/db.ts`
field helpers, the `gen.functions` section, and the two import runner files.

## Codemod and render checks [#codemod-and-render-checks]

The codemods read TypeScript through a syntax tree. A file that does not parse
is listed with its line and the parser's message instead of being skipped, so a
file that needs a change never looks like a file with nothing to change. Fix it
and run the codemod again. `codemod naming` renames an environment variable where
code names it and leaves comments alone, and it lists a string that holds the
name among other words.

`gen` now parses the SQL of every installed module and every SQL fragment in the
config before it writes anything. An error names the module and the statement,
or the config key such as `vectorSearch.public.docs.predicate`.

## Direct dependencies [#direct-dependencies]

`better-supabase` now installs `oxc-parser`, `@supabase/pg-parser`,
`@supabase/pg-delta` and `@supabase/pg-topo` at exact versions. Only the CLI and
the Node entries import them, so deployed functions do not grow.

| 0.82                                                | 0.83                                                           |
| --------------------------------------------------- | -------------------------------------------------------------- |
| `pnpm add -D @supabase/pg-delta @supabase/pg-topo`  | Nothing to install; `better-supabase` brings both              |
| `@supabase/pg-delta` in the app's `devDependencies` | Remove it (`pnpm remove @supabase/pg-delta @supabase/pg-topo`) |
| BS239 reports the two packages as missing           | BS239 is retired; BS709 reports an own copy                    |

## The blocks list [#the-blocks-list]

`blocks` is a list of block names and `{ block, name?, ...entry }` objects. The
keyed object form is rejected when the config loads, with a hint to run the
codemod. A block with nothing to configure is a plain name.

| 0.82                                               | 0.83                                                   |
| -------------------------------------------------- | ------------------------------------------------------ |
| `blocks: { tags: {} }`                             | `blocks: ["tags"]`                                     |
| `blocks: { comments: { api: "api" } }`             | `blocks: [{ block: "comments", api: "api" }]`          |
| `blocks: { "ops-tasks": { block: "tasks", ... } }` | `blocks: [{ block: "tasks", name: "ops-tasks", ... }]` |

`codemod blocks-list` keeps comments and key order. It writes nothing when the
file already holds a list, and `--check` exits 1 while a file still needs it.

## Project-level defaults [#project-level-defaults]

These facts are set once under `database.sql` and every block that needs one
reads it.

| 0.82                                                                       | 0.83                                             |
| -------------------------------------------------------------------------- | ------------------------------------------------ |
| `tenant: "org_id"` on each table, data-lifecycle table and tag link        | `database.sql.tenantColumn: "org_id"`            |
| `numbering` entry without a tenant column uses `organization_id`           | the entry uses `sql.tenantColumn` when it is set |
| `format: "{n}"`, `period: "none"`, `column: "number"` on each entity       | the same values are the defaults; remove them    |
| `brand: { table, column }` on each templates, option set or pipeline block | `database.sql.brand: { table, column, tenant? }` |

The numbering tenant default changes from `organization_id` to
`sql.tenantColumn`. An app whose numbering entity set no tenant column and
whose project column differs sees the render change: run `gen sql` and read the
diff before you deploy.

## Config the render already supplies [#config-the-render-already-supplies]

`codemod config --prune` removes each entry that `doctor` reports as BS427:
identity column mappings, empty maps, a tenant that repeats `sql.tenantColumn`,
an `api` or `audit` equal to `sql`'s, a permission key equal to the one the
block would use, an option equal to its default, and the numbering values above.
It renders the blocks with the old and the new config and writes nothing when a
generated file differs. It removes the entries in batches and halves a batch
whose render changes or throws, so it lists the block groups it kept and why
instead of stopping at the first entry another option needs.

| 0.82                                                                  | 0.83                                       |
| --------------------------------------------------------------------- | ------------------------------------------ |
| `columns: { tasks: { title: "title" } }`                              | removed; the column has the same name      |
| `tenant: "org_id"` equal to `sql.tenantColumn`                        | removed                                    |
| `api: "api"` equal to `database.sql.api`                              | removed                                    |
| `permissions: { read: "tasks.read" }` equal to the key the block uses | removed                                    |
| `options.feed.names: false` equal to the default                      | removed                                    |
| `api: { schema: "api" }` equal to `database.sql.api`                  | removed                                    |
| `api: "api"` on most blocks and no `database.sql.api`                 | `sql.api: "api"`, `api: false` on the rest |

When no `database.sql.api` is set and more than half of the blocks (at least
two) name the same schema without a function list, the codemod sets
`database.sql.api`, removes the matching entries and writes `api: false` on each
block that had no entry, so it still writes no wrappers. It keeps the change
only when the render stays the same.

The BS427 target for a record type permission that repeats the provider's
`actionKeys` is now `recordTypes.<type>.permissions.<action>` (it said
`subjects.` before). A doctor baseline entry for the old target is stale: run
`codemod doctor-baseline` or edit the target.

## Provider fields [#provider-fields]

An `AuthorizationProvider` can now state the permission keys, the approvers and
the approval floors that the config used to repeat. Every field is optional, so
a provider that sets none of them keeps working.

| 0.82                                                   | 0.83                                                                      |
| ------------------------------------------------------ | ------------------------------------------------------------------------- |
| `blocks.<name>.permissions` in every app               | `actionKeys.blocks.<name>` in the provider; the config entry still wins   |
| `subjects.<type>.permissions` in every app             | `actionKeys.recordTypes.<type>`                                           |
| bucket and topic keys written in policies              | `actionKeys.buckets` and `actionKeys.topics`, checked by `gen` and doctor |
| `options.decider` on leave, expenses and time entries  | `functions.approverFor` with `{kind}` and `{id}`; the option still wins   |
| manager chains read from the employees block           | `functions.managedUsers`, read next to the employees manager              |
| `options.policies.<subjectType>.<action>` on approvals | `operations["<subjectType>:<action>"].approval`; the option still wins    |

`codemod config --prune` removes a `permissions` entry that equals the
provider's `actionKeys`. Drop `options.decider` by hand once the provider
supplies `approverFor`: the codemod can't know the function does the same.

`gen sql` and doctor (BS411) now check the keys of operations, bucket and topic
`actionKeys` and `@bsb access` tags the way they check module keys, and refuse
a key the provider does not mark `sqlComplete: true`. Doctor reports at info
level when leave, expenses or time entries are installed and the provider sets
no `approverFor` or `managedUsers`.

`actionKeys.buckets` and `actionKeys.topics` are typed and checked only. The
storage and realtime policies are code in your schema files, so they do not
read the map.

## Entries the render answers [#entries-the-render-answers]

`codemod config --prune` renders the config with and without an entry and removes the entry when
the files are byte-equal. Besides `permissions` and `options`, it now tries the hook entries under
`callbacks`, the `api` entries, `tables` and `columns` entries that keep the block's default name,
`on` entries (`links`, `column`, `table`) and the `idType`, `table` and `cascade` of a record type.
It tries a hook that keeps its name, such as `after_invoice_clone: "after_invoice_clone"`, and a
`callbacks.schema` of `public`. On CentraKit this removed 17 hook and 17 `api` lines. The probe
stops after 400 renders, and options nested deeper than three keys (workflow `steps` and `effects`)
are left alone, because they are data, not defaults. Run it again to try the rest.

## Record types [#record-types]

A record type is declared once, in `recordTypes` or with `@bsb subject`, and
the blocks read it from there.

| Before                                                             | After                                                     |
| ------------------------------------------------------------------ | --------------------------------------------------------- |
| `on` repeats the table, id and tenant for each block               | `on: ["task"]`; the registry supplies them                |
| `idType` on every record type                                      | read from the schema files for `uuid` and integer ids     |
| `tags.on.<type>.links: { table, subject, tag }`                    | inferred from the foreign keys into the type and the tags |
| `time-entries.on.<type>.column`                                    | inferred from the foreign key into the type's table       |
| a type named `time-entry` in `on` and `time_entry` in the registry | one name; `alias` sets the name stored and sent           |

An explicit `links` or `column` entry wins. When more than one foreign key or
link table could match, the render fails and lists them, so you name the one to
use. `codemod config --prune` removes a `links` or `column` entry that equals
what the foreign keys give.

`recordTypes.<type>.alias` is the wire name: the value stored in `subject_type`
columns and sent to the client. The registry key stays the name in your config
and code. An alias is lowercase letters, digits, hyphens and underscores, and
no two types may share a wire name.

`@bsb subject blocks=tags,time-entries` adds the type to the `on` of each
installed block it names.

`codemod record-types` rewrites the names in `blocks.<name>.on` that differ from
a registered type only by `-` and `_`, or that are its alias, as the registered
name. Doctor rule BS346 suggests it when a name matches after that change.

An inferred `uuid` or integer id type casts a stored text id only when the id
has that type's shape, so a malformed id reads as not found instead of raising.

## Table facts in comments [#table-facts-in-comments]

Four facts about one table now sit in a `comment on table` next to the table,
where a review of the schema shows them. The config entry still works. For
audit, data lifecycle and privileges it wins when both exist; a `same-tenant`
tag replaces the entries for its column.

| Fact                | Config in 0.82                                     | Comment in 0.83                                      |
| ------------------- | -------------------------------------------------- | ---------------------------------------------------- |
| Audit exemption     | `blocks.audit.options.exempt: [{ table, reason }]` | `@bsb audit-exempt reason="rebuilt nightly"`         |
| Data lifecycle      | `blocks.data-lifecycle.options.tables.<table>`     | `@bsb data-lifecycle user=owner_id export=false`     |
| Data API privileges | `database.expose.<table>`                          | `@bsb grant authenticated="select,update(title)"`    |
| Same-tenant check   | `blocks.memberships.options.sameTenant` entry      | `@bsb same-tenant match=region=region` on the column |

```sql
comment on table public.invoices is '@bsb data-lifecycle user=owner_id; grant authenticated=select';
comment on column public.tasks.project_id is '@bsb same-tenant';
```

One `@bsb` starts the tag block, and `;` separates the tags in it.

`audit-exempt` needs a reason, and doctor rule BS315 reports a tag without one.
`grant` on a table a block adopts exposes the table, so the block only enables
row level security on it and the `grants` module writes the privileges.

`codemod table-tags` writes the comments into the schema file that creates each
table and removes the config entries. A fact whose table no schema file creates,
or whose comment already holds the tag, stays in the config and is listed.
The codemod also moves a `blocks.memberships.options.sameTenant` entry into a
`@bsb same-tenant` tag on its column, but only when it can show that the tag
renders the same trigger statement. It renders the memberships module with the
entry and again with the tag, compares the statement of that column, and moves
the entry when the two are the same string. An entry that equals what the block
derives from the foreign keys stays, and `codemod config --prune` removes it.
An entry that does not move is listed with the reason: no foreign key holds the
column, a `through` hop has its own key column, or the statement would change.
A baseline entry
for BS315 is not moved either: the baseline lists accepted findings, not
exemptions, so add the `audit-exempt` tag with its reason instead. Doctor rule BS702
lists the facts a comment can hold, and BS703 reports a tag that cannot take
effect.

### Same-tenant checks from every foreign key [#same-tenant-checks-from-every-foreign-key]

Without a `sameTenant` option, the block now derives a check from every foreign
key between two tenant tables, not only the single-column ones. A composite key
leads with its first column and checks the others as `match` pairs. A key with a
nullable column besides the first is left to the database, because a foreign key
does not check a row where one of its columns is null. A key that pairs the
tenant column on both sides stays unchecked, as before.

| Before                                                                    | After                                                                                    |
| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| A `same-tenant` tag always let a referenced row with no tenant pass       | The tag follows the referenced tenant column; `shared=true` or `shared=false` decides it |
| A `same-tenant` tag needed a single-column foreign key                    | A tag works on any foreign key that holds the column                                     |
| `sameTenant` entries stayed in the config                                 | `codemod table-tags` moves the ones a tag renders byte for byte                          |
| `recordTypes`, `realtime` and `vectorSearch` entries stayed in the config | `codemod table-tags` moves the ones a tag reads back to the same value                   |

A tagged column whose referenced tenant column is `not null` now refuses a row
with no tenant. Before, the tag wrote `shared` whatever the column said, so it
let such a row pass. Add `shared=true` to the tag to keep the old behaviour.

## Optional columns [#optional-columns]

A block's optional column is on when your table declares it. The config entry that said so is
no longer read for leave: `startPart` and `endPart` switch the parts of the day on and
`confidential` filters confidential types, both from the columns of your own `requests` and
`types` tables. A requests table that declares only one of the two part columns is refused.

| 0.82                                                       | 0.83                                                  |
| ---------------------------------------------------------- | ----------------------------------------------------- |
| `columns.requests.startPart: "start_part"` turns parts on  | the table declares `start_part` and `end_part`        |
| `columns.types.confidential` on your own types table threw | the table declares `confidential`; no entry is needed |
| `null` for an optional column your table lacks             | remove it; `codemod config --prune` does              |
| BS622 asked for optional columns a block could use         | BS622 reports required columns only                   |

`codemod config --prune` also drops an entry that repeats the convention's name. Other modules
still read their entries (catalog, invoices, profiles, webhooks); they convert one at a time.
The reasons are in [ADR 1189](https://github.com/ScaleDockHQ/better-supabase/blob/main/docs/decisions/1184-optional-columns-follow-the-table.md).

## Block names first [#block-names-first]

A block can create its table under its own names while your schema files extend it, and an app
that keeps its names can say so in a comment. Nothing breaks: a `tables` or `columns` entry still
works and wins over a tag. The generated `fields` now carry the columns your files add for every
block, memberships included.

| 0.82                                                          | 0.83                                                                          |
| ------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `tables: { memberships: "public.seats" }`                     | `comment on table public.seats is '@bsb block-table=memberships.memberships'` |
| `columns: { memberships: { tenant: "organization_id" } }`     | `comment on column public.seats.organization_id is '@bsb column=tenant'`      |
| rename the table by hand and edit the config                  | `codemod adopt-names --table memberships.memberships`                         |
| a block without a legacy `extraColumns` table had no `fields` | the first table of the block your files extend gives them                     |

`adopt-names` renames one table per run, writes the rename migration, rewrites the statements of
your schema files that name the table and removes its `tables` and `columns` entries. It refuses a
table outside the block's schema, and a `values` entry stays. See
[ADR 1190](https://github.com/ScaleDockHQ/better-supabase/blob/main/docs/decisions/1185-base-first-tables.md).

## Declared rows [#declared-rows]

Option set items, pipeline stages, approval floors and numbering formats can live as rows the app
owns. Nothing breaks: the block functions read `better_supabase.declared_defaults` first and keep
the config literal as the fallback, so a config without declared rows behaves as before. A field
with neither declared nor literal items raises `OPTION_SET_DEFAULTS_MISSING`.

| 0.82                                                          | 0.83                                                                    |
| ------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `on: { project: { priority: { items: [...] } } }`             | `option_set_item` rows in `supabase/rows/option-sets.sql`               |
| `on: { deal: { stages: [...] } }` or `taskStages(...)`        | `pipeline_stage` rows in `supabase/rows/pipelines.sql`                  |
| `options.policies: { invoice: { send: { steps: [...] } } }`   | `approval_floor` rows in `supabase/rows/approvals.sql`                  |
| a changed default needs a regenerated config and a new deploy | edit the rows file and run `better-supabase db rows` (a data migration) |
| `approval_policy` was `immutable`                             | `stable`, because it reads the declared floors                          |

`codemod declared-rows` writes the rows files from your resolved config and removes the moved keys.
`db rows` then writes one data migration for each rows file, stamped with the hash of its
statements, and `db rows --check` exits 1 in CI when a file has none. A row you remove from a file
stays in the database and is reported, unless the file carries `-- bsb-rows: delete-removed`. See
[ADR 1197](https://github.com/ScaleDockHQ/better-supabase/blob/main/docs/decisions/1192-declared-defaults-table.md)
and [ADR 1198](https://github.com/ScaleDockHQ/better-supabase/blob/main/docs/decisions/1193-declared-rows-migrations.md).

## Schemas by module reference [#schemas-by-module-reference]

A `gen.json` column and a `blocks.settings.options.schemas` entry can name an
exported Standard Schema as `"./schemas.ts#name"`. The CLI loads the export,
reads its JSON Schema for the pg_jsonschema check, and types the column as its
output, so the config no longer imports a schema library or repeats the type.

| 0.82                                                                           | 0.83                                                  |
| ------------------------------------------------------------------------------ | ----------------------------------------------------- |
| `json: { "t.c": { import: "./s.ts#C", schema: C } }` with `import { C }` above | `json: { "t.c": { schema: "./s.ts#C" } }`             |
| `schemas: { user: { theme: theme } }` with the schema imported                 | `schemas: { user: { theme: "./settings.ts#theme" } }` |

An inline JSON Schema and a schema value still work, and `import` or `type` still
set a different column type. No codemod moves these: the inline form has no name
to point at. Doctor rule BS704 reports an inline schema that an exported schema
in a module the `standardSchema()` generator names already produces.

## Task coordination [#task-coordination]

0.83 closes five gaps in the task coordination that shipped in 0.82. Run
`better-supabase upgrade` to move the `tasks` module to version 7.

### claimNext [#claimnext]

`claimNext` took the oldest ready task, assigned ones first, and fell back to
unassigned tasks. It now takes only tasks assigned to the caller unless the
config sets `claims.next: "any"`. A session with an `act` claim of kind `agent`
always picks assigned tasks, whatever the option says, and the filters
`assigneeId` of someone else are refused with `TASK_FILTER_FORBIDDEN`. Claiming
a task that is not assigned to an agent is `TASK_NOT_ASSIGNED`. The pick is
ordered by `number`.

### Category stages [#category-stages]

`hold.stage`, `claims.startStage` and `claims.expiredStage` take a stage key or
`{ category }`. A category resolves to the first stage of that category in the
task's pipeline. Doctor reports BS245 when the live pipeline has no stage for a
configured key or category.

### Hold kinds [#hold-kinds]

`hold.kinds` lists the kinds `hold` accepts, and anything else is
`TASK_HOLD_INVALID`. `hold.approval.kinds` limits which kinds open an approval
request and must be a subset of `hold.kinds`. Releasing a hold, moving the task
out of the hold stage and closing it now cancel the pending approval request.
`releaseHold` then reports `approvalCancelled` in the `task.hold_released` event.

### Reserve a task [#reserve-a-task]

`delegate({ taskId, toUserId, toProfile })` reserves the task for a named
profile of that user. Only that profile of that user can claim it, or a person
with write access, who takes it over. Anyone else gets `TASK_RESERVED`.
`claimNext` takes `filter.delegateProfile`. The task reads back
`delegateProfile: { name, userId }`. A re-delegate, an unassign and a close clear
the reservation, and `task.delegated` carries `toProfile`. Before 0.83 the column
stored the delegating label, which the client never read; the upgrade step clears
those values.

### before_task_close [#before_task_close]

The `before_task_close(task uuid, outcome text, note text)` hook now runs once
on every path that closes a task, from an after-update trigger, and a hook that
raises refuses the close with its own error. Templates are skipped. It no longer
runs when `reopen` sets the outcome `open`, and it is not called for a task
inserted already closed.

## SQL reading [#sql-reading]

The CLI reads every SQL file with one reader on `@supabase/pg-parser`. This is
a breaking change for code that imports from `better-supabase/sql`: the text
readers are removed from that entry, and the CLI no longer calls them (ADR
1212). The render functions take what a file declares as plain data, so they
still run on every runtime without the parser.

| Removed from `better-supabase/sql`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Replace with                                                           |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `addedColumnTypes`, `adoptedColumnProblems`, `adoptedTables`, `adoptedViews`, `appColumnsOf`, `auditRegistrations`, `buildModel`, `checkValues`, `columnTagComments`, `conflicts`, `declaredCheckValues`, `declaredColumnTypes`, `declaredForeignKeys`, `declaredIndexes`, `declaredPolicies`, `declaredTableColumns`, `declaredTables`, `declaredUpdatedAtTriggers`, `declaredViews`, `duplicateObjects`, `duplicatePolicies`, `extensionSchema`, `mappingTagsOf`, `moduleWritesText`, `ownedColumns`, `ownerOf`, `parseDeclared`, `policyGrants`, `rlsTables`, `sameTenantLayout`, `sameTenantTagsOf`, `setParseStore`, `splitStatements`, `widenedCommands`, `withMappingTags`, `writtenValues` and the types `AdoptedTable`, `AdoptedView`, `CheckValues`, `ColumnTagComment`, `Declaration`, `DuplicateObject`, `OwnedColumn`, `ParseStore`, `SameTenantTags`, `SchemaModel`, `SqlStatement`, `TableCheckValues` | Run `doctor`, `gen` or `sync`; the reader is not a public API          |
| `splitStatements(sql)`, `SqlStatement`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Your own splitter. `SqlStatement` was `{ text: string; line: number }` |

The project codemods (`table-tags`, `extra-columns`, `same-tenant`,
`naming-pins`) edit SQL by the reader's facts and token positions instead of
regular expressions. A file the scanner cannot read (an unterminated quote or
dollar tag) is listed in the codemod's review and left as it is, where the old
codemod rewrote it by pattern. The naming codemod no longer rewrites comments.

`sync` compares statements by their canonical text, so a statement that differs
only in spacing, keyword case or quoting is not written again. The migration
file name carries a versioned hash: new files end in `_v2-<8 hex digits>.sql`.
A migration an earlier release wrote keeps its name and is still recognized as
the same file, so upgrading writes no new migration (ADR 1213).

## Doctor [#doctor]

`tooling.doctor.baseline` accepts a grouped form next to the flat one. A group
names the code, one reason and every target it covers, so a hundred accepted
findings read as a few lines.

```json
[
  {
    "code": "BS112",
    "reason": "Helpers the access module calls; checked in review",
    "targets": ["public.a", "public.b"]
  }
]
```

An entry with an empty reason is an error, and a stale entry is still reported.
`doctor --update` is an alias of `--update-baseline`, and it writes the grouped
form when the file is already grouped. `codemod doctor-baseline` rewrites a
`{ "BS112": { "reason": "...", "targets": [] } }` file into the grouped list.

An authorization provider can set `doctor: { command: [...] }`. Doctor runs it in
the project root and reports its JSON findings as BS705, so the baseline can
accept them.

Rules that were wrong now agree with the code:

| Rule  | Change                                                                                                                                                  |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BS112 | Comments and strings never count as a call, an unqualified call to a provider function is a check, and a wrapper over a checked app function passes     |
| BS116 | A helper a policy reaches through another helper, a trigger function and a function the provider's templates name count as uses                         |
| BS352 | A trigger whose body calls `better_supabase.field_seal` counts as sealing, with no `sealTriggers` entry                                                 |
| BS365 | Table names are normalized, a policy with no `for` clause is `for all`, every app file is read, and the finding targets the table                       |
| BS239 | Fires only when a `package.json` script runs `better-supabase db diff`; a Supabase CLI declarative project never loads pg-delta's library               |
| BS217 | A same-tenant trigger, generated or an app trigger that BS398 accepts, satisfies it; an info finding recommends the composite key where a unique exists |

Source rules that read TypeScript (BS2xx scale rules, BS3xx block rules, BS4xx
and BS5xx wiring, cookie and cache rules, BS6xx) read the syntax tree. A comment
or a string that mentions a call no longer counts, and findings, codes and lines
are the same for real code. BS260 reports only imported function and type names,
BS511 and BS621 count dynamic imports, and the shim check ignores comments.
BS210, BS219, BS227 and BS351 join the rules that check receiver types when
`typescript` 7.1 or newer is installed. Rules that read SQL or dotenv files still
match text.

With `typescript` 7.1 or newer, `codemod prune`, `declared-rows`, `adopt-names`
and `extra-columns` also edit config values that the config imports from other
files, and list those files for review.

BS706 warns about a shim of a feature the library ships: a seal trigger beside
`field-encryption`, a `decider` option where the provider has `approverFor`,
`approvals: false` with `standaloneApprovals`, and an app file that redefines a
block function.

## Generated SQL that doctor BS725 reads [#generated-sql-that-doctor-bs725-reads]

Under pg-delta, BS725 reads the module files better-supabase writes. Three
rendered statements changed so the files hold what pg-delta can see:

- Every module's `alter default privileges ... revoke all` now names
  `for role postgres`. Without a role the statement attaches to whichever role
  loads the file, which differs between the shadow database and yours. On a
  Supabase project migrations run as `postgres`, so nothing changes there.
  Run `better-supabase gen` and review the diff of the module files.
- With `autoEmbed` on a table, the embeddings drain is a plain top-level
  `select cron.schedule(...)`. The same file already runs
  `create extension if not exists pg_cron`, so the guard in a `do` block
  added nothing.
- With `blocks.queue.options.httpTick`, the tick job is a plain
  `select cron.schedule(...)` after the check that raises
  `QUEUE_TICK_NO_PG_CRON` when `cron` is missing.

The other `cron.schedule` calls (knowledge embeddings, computed usage meters,
the workflow retention job, the maintenance and stream purge schedules and
`schedule_job`) check that pg_cron is installed first, because a plain
statement would make the extension mandatory. BS725 accepts a body with that
check. It still reports `blocks.notifications.options.realtime: "changes"`,
which adds the table to `supabase_realtime` through `execute format`; accept
that finding in `tooling.doctor.baseline` with the reason. The entry stays
because the module adds the table only when the publication exists and does not
list it yet, and a plain `alter publication ... add table` fails on a second
load.

Doctor reads the SQL and dotenv rules as tokens in 0.83. A comment or a quoted
string that names a function, a trigger or a pooler URL no longer produces a
finding, and the codes, messages and lines stay the same for real code.

## Generators [#generators]

BS244 now names the five largest blocks by generated SQL size when the module SQL passes 2 MB, so you
can see which block to install in a smaller form or leave out.

Four generator items from the 0.83 plan did not change code, and the reasons are on record for the ADR:

- **Insert optionality.** `columnsSchema` already reads `not null default` from each column's type text, and a column
  with a default is optional on insert and required on output. The type test in `tests/core/columns-schema.test.ts`
  covers it, so there is nothing upstream left to fix.
- **Empty `saas`, `finance` and `recruiting` slices.** Loading the validation-centrakit config and rendering every
  block slice produces no slice with an empty composite for those names. The composite entry is only built when
  every part is installed, so the slice did not reproduce.
- **`better-supabase sql size`.** The `sql` engine is internal (reached through `add`, `upgrade`, `blocks` and
  `gen`), so there is no such command to extend. The per-block breakdown lives in the existing size checks.

Block function not-null results are declared in the block manifests (announcements, settings and webhooks list
their eleven client functions), and `gen` reads them after the function's own `@notNull` tag and before it infers from the function source.
`gen.functions.<name>.notNull` stays the override that wins, so the order is config, tag, block, inference. `codemod config --prune` and doctor BS427 report a
`gen.functions` entry whose `notNull` repeats what the block declares, so the entry can be deleted.

Every block slice exports `fields`, built from the block's columns plus the `@bsb fields` and adopted extra
columns, so a `not null default` column is optional on insert. The new `tests/cli/gen/block-fields.test.ts` covers
expenses, leave, catalog, tasks, time-entries, teams and flags. The "configured schema generator" is the Standard
Schema one `columnsSchema` builds, so no separate generator option exists. `tests/blocks/generated-fields.test-d.ts`
checks the insert types: a `not null` column without a default is required, any other column is optional. Delete
your hand-written field schemas and `insertableFields` helper, and `blocks.<name>.using((options) => ...)` receives
the generated `fields` in `options`.

A disabled feature renders no SQL. `blocks.inventory.tables.allocations: null` drops the stock allocation table,
its eleven functions, the import target and the contract entries (599 fewer lines). `blocks.accounting.tables.budgets: null`
or `budgetLines: null` drops the budgets table, the four budget functions and their contract entries (232 fewer
lines). Inventory and invoices already gated their other optional tables: turning off the e-invoice and dunning tables of
invoices drops 823 of 4634 rendered lines.

Doctor BS707 (info) lists `blocks.<name>.columns` entries that no enabled feature reads. The render records each
`table.column` it reads, so an entry for a feature that is off is reported with the block, table and column. The
report names the block, table, column and what gates it: `tables.<table>: null` when the config switched the table
off, `options.<name>` when rendering again with that boolean option on makes the block read the column, or
`no option found`.

Doctor BS708 (info) lists the generated SQL of each installed block in kilobytes, largest first, and
`doctor --json` carries it under that code. It replaces the idea of a `sql size` command.

## Block fixes [#block-fixes]

**Tax.** `tax_codes` gets a unique index on `(id, tenant_id)` and `tax_rates` a composite foreign key from
`(tax_code_id, tenant_id)`, so a rate cannot point at another tenant's code. The tax block is now version 2.
`better-supabase upgrade` adds the index and the key as `not valid`, so old rows never block the upgrade. Run
`alter table <schema>.tax_rates validate constraint tax_rates_tenant_code_fkey` once after you have checked that
no rate belongs to a code of another tenant.

**Cancelling an approval.** `cancel_approval` now reaches expenses and time entries, as it already did for
leave. A submitted standalone expense goes back to draft (as `withdraw_expense` does) and a submitted week kept in
a status column is open again (as `withdraw_timesheet` does); a decided one stays as it is. Expense reports and
weeks whose status follows the approval request already read a cancelled request as a draft or open week, so
they need no hook. The new functions are `expense_approval_cancelled` and `timesheet_approval_cancelled`, which
`add` and `upgrade` write into your schema files without a version bump, because `create or replace` covers them.

**Email to people who are not members.** Set `options.externalRecipients` on `notifications` and
`send_notification` takes an `external` list of `{ address }` or `{ contact }` entries, reached on the email
channel through the same claim and bounce suppression as members. A contact resolves through your
`resolveAddress` function. It is off by default, because it makes the recipient `user` column nullable.

**Import runner.** Five gaps that apps worked around with their own copy of the functions are closed, each in
`create or replace` functions that `add` and `upgrade` rewrite without a version bump. A dry run now keeps its
conflict and error rows in `list_import_issues`, which the rolled-back batch used to take with it, and cancelling
a dry run removes its stored chunks and issue rows. `import_apply_batch` reads the record map of a whole batch in
one query instead of one query per item. `enqueue_import_chunks` sends a failed chunk back to pending with a new
job, so calling it again retries what failed. `import_supplier_item` takes the supplier from a `supplier` or
`customer` ref when `supplierId` is missing. The import gaps note the plan names was not in the repository, so
these five follow the plan's wording; compare them with your override before you delete it.

**Template clones.** `instantiate_template` now checks the apply permission of the target tenant before it
clones, passes that tenant to the clone as `overrides.tenantId`, and `clone_invoice`, `clone_quote` and
`clone_task` copy every header column the table has, not only the title and currency. A clone into another tenant
is allowed only for a row a template owns or for the service role, so a user cannot copy a row from a tenant they
cannot read. These are `create or replace` changes, so `add` and `upgrade` need no version bump.

**Audit statement trigger and squash.** With the restricted table, the statement-level audit trigger matches each
restricted row to its entry by record and operation instead of by the order `RETURNING` emits, which SQL does not
promise. A log without a record or op column keeps the order match. `db squash` stamps the kept data migrations with
`stampAfter` over the whole migrations folder, so a baseline stamped later than the CLI's clock no longer shares a
stamp with the data. A test now lists the tenant tables that declare no `lifecycle` (35 today, the data-lifecycle
module's own tables among them) and fails when the list grows.

**Fake client filters.** A second filter on the same column used to replace the first, so `.gte("price", 1).lte("price", 5)`
recorded only the upper bound. The fake client now records both in an `and` query parameter (`and=(price.gte.1,price.lte.5)`),
also for two `or` groups. List values that hold a comma are quoted and objects are written as JSON for `contains`. It adds
`textSearch`, `rangeGt`, `rangeGte`, `rangeLt`, `rangeLte`, `rangeAdjacent`, `isDistinct`, `likeAnyOf`, `likeAllOf`,
`ilikeAnyOf` and `ilikeAllOf`. The plan 057 note that lists B15 is not in the repository, so this is what reproduced
against supabase-js; a handler that read `query.price` for a range now reads `query.and`.