Runbook: migrations (additive by default)
Policy
Section titled “Policy”- Migrations are additive (from 2026-09-24). A change lands as NEW timestamped folders appended to
packages/db/src/migrations/— one per schema change or re-emitted artifact — exactly as in normal development. A committed migration folder is never edited, deleted, renamed or regenerated. - Whole-set regeneration is exceptional. Deleting the committed folders and rebuilding the set from
the Drizzle schema (
bun run db:regenerate) needs the maintainer’s (Anton’s) explicit approval, obtained before it runs and given for that specific occasion — an earlier approval does not carry over — and it is only worth asking for when it buys a significant advantage. An AI agent never initiates it. The script refuses to delete anything without--confirm; see “Whole-set regeneration” at the end of this runbook. - Applying migrations to any database is the maintainer’s step, never an agent’s.
How the migration framework works here
Section titled “How the migration framework works here”drizzle-kit1.0+ emits one folder per migration containingmigration.sql+snapshot.json. There is no centralmeta/_journal.json— ordering is the timestamped folder prefix, and applied state is tracked in the DB tabledrizzle.__drizzle_migrations.- Two kinds of migrations live in
packages/db/src/migrations/:- Schema migrations — produced by plain
drizzle-kit generate(diffs the Drizzle schema against the latestsnapshot.json). Theinitial_baselineis one of these. - Custom migrations — scaffolded empty via
drizzle-kit generate --custom --name Xand then filled, either by a builder insrc/migration-sql/(governance/auth-hooks/claim/sync/…) or from a checked-in.sqlfile inscripts/manual-migrations/(the storage buckets and the signing roles). Theirsnapshot.jsonis an empty diff against the prior snapshot; only theirmigration.sqlcarries content.
- Schema migrations — produced by plain
- Generating into an empty migrations dir produces a clean full baseline with no
interactive rename prompts (there is no prior snapshot to diff against). That is what the
approval-gated whole-set regeneration does. An additive
drizzle-kit generatediffs against the latest committedsnapshot.jsoninstead, so a rename can raise a question it cannot answer on its own — see step 1 of the procedure.
The ordered migration set
Section titled “The ordered migration set”The committed set carries the dependency order below — the order a first install on an empty
database walks. packages/db/scripts/regenerate-migration-set.ts is this order, executable, with
the dependency reason recorded against each position — bun run db:regenerate --list prints it
(listing changes nothing and is always allowed). Any NEW migration appends after this set — its
folder timestamp is later than every committed one — followed by a fresh client_role_acl folder, so
the ACL floor keeps last place (procedure step 3).
| # | name | kind | how |
|---|---|---|---|
| 1 | pgxsinkit_utilities |
custom (script) | bun run db:generate:pgxsinkit-utilities — pre-baseline |
| 2 | offering_membership_authority_floor |
custom (script) | bun run db:generate:membership-authority-floor — pre-baseline |
| 3 | assessment_native_attempt_floor |
custom (script) | bun run db:generate:assessment-native-attempt-floor — pre-baseline |
| 4 | platform_bridge_survey_floor |
custom (script) | bun run db:generate:platform-bridge-survey-floor — pre-baseline |
| 5 | initial_baseline |
schema | drizzle-kit generate |
| 6 | authorization_claim_projection |
custom (script) | bun run db:generate:authorization-claim-projection |
| 7 | identity_linking |
custom (script) | bun run db:generate:identity-linking |
| 8 | supabase_auth_hooks |
custom (script) | bun run db:generate:auth-hooks |
| 9 | registry_governance |
custom (script) | bun run db:generate:governance |
| 10 | sync_artifact |
custom (script) | bun run db:generate:sync-function |
| 11 | event_lane_artifact |
custom (script) | bun run db:generate:event-lane |
| 12 | storage_buckets |
custom (manual SQL) | scripts/manual-migrations/storage_buckets.sql |
| 13 | credential_signing_role |
custom (manual SQL) | scripts/manual-migrations/credential_signing_role.sql |
| 14 | platform_bridge_custody |
custom (script) | bun run db:generate:platform-bridge-custody |
| 15 | qti_item_asset_storage_policies |
custom (script) | bun run db:generate:qti-asset-storage-policies |
| 16 | assessment_pnp_proxy_policies |
custom (script) | bun run db:generate:pnp-proxy-policies |
| 17 | learner_submission_storage_policies |
custom (script) | bun run db:generate:learner-submission-policies |
| 18 | post_safeguarding_audit |
custom (script) | bun run db:generate:post-safeguarding-audit |
| 19 | content_origin_freeze |
custom (script) | bun run db:generate:content-origin-freeze |
| 20 | content_artifact_freeze |
custom (script) | bun run db:generate:content-artifact-freeze |
| 21 | observation_evidence_clock |
custom (script) | bun run db:generate:observation-evidence-clock |
| 22 | observation_meeting_records |
custom (script) | bun run db:generate:observation-meeting-records |
| 23 | platform_primitive_organizations |
custom (script) | bun run db:generate:platform-primitives |
| 24 | lang_launch_vocabulary |
custom (script) | bun run db:generate:lang-launch-vocabulary |
| 25 | gradebook_entry_origin |
custom (script) | bun run db:generate:gradebook-entry-origin |
| 26 | assessment_native_delivery_guard |
custom (script) | bun run db:generate:assessment-native-delivery |
| 27 | platform_bridge_survey_guards |
custom (script) | bun run db:generate:platform-bridge-survey-guards |
| 28 | item_session_grading_floor |
custom (script) | bun run db:generate:item-session-grading-floor |
| 29 | client_role_acl |
custom (script) | bun run db:generate:client-role-acl — must be LAST |
Order matters. pgxsinkit_utilities (step 1) is the exception that comes before the baseline:
it renders public.pgxsinkit_clock_us() — the canonical microsecond clock the audit/LWW column
DEFAULTs call (created_at_us/updated_at_us bigint DEFAULT public.pgxsinkit_clock_us()) and the
sync-function apply artifact emits — so the function must install first, or the baseline’s DEFAULTs
reference a missing function. It rides its own render step (renderPgxsinkitUtilitiesMigration() from
@pgxsinkit/server, wrapped by buildPgxsinkitUtilitiesMigrationSql in
packages/db/src/migration-sql/pgxsinkit-utilities.ts), generated into an empty migrations dir so it
takes the earliest timestamp and sorts first.
offering_membership_authority_floor (step 2) is the second pre-baseline exception (ADR-0056
decision 5): it renders public.fn_offering_allows_membership_insert(), the SECURITY DEFINER helper the
baseline’s RESTRICTIVE offering_membership_insert_non_personal_offering policy calls — and Postgres
resolves a policy’s functions at CREATE POLICY time, so the helper must exist before the baseline runs.
Its body is deliberately plpgsql: a LANGUAGE sql body is parsed and its relations resolved at
CREATE FUNCTION time, which would fail here because public.offering does not exist yet; a plpgsql body
is only syntax-checked at creation and resolved on first execution. (The same helper is installed ahead of
pushSchema by the pgwasm test harness, packages/db/src/testing/pgwasm.ts, for exactly this reason.)
assessment_native_attempt_floor (step 3) is the third pre-baseline function artifact. Its narrow
SECURITY DEFINER helper returns only whether a Definition permits native delivery; an invoker lookup
would apply the Definition’s teacher-only SELECT policy and reject ordinary learner starts. The
restrictive Attempt INSERT policy needs this helper before schema creation. Its parent FOR SHARE
lock serializes direct native inserts with Bridge attachment. The separate
assessment_native_delivery_guard (step 26) follows the baseline: it backfills attached Definitions
and installs an invoker trigger protecting the server-owned flag while preserving teacher edits.
platform_bridge_survey_floor (step 4) installs the narrow private native-response provenance lookup
before the Item Response INSERT policy resolves it. It does not expose anonymous parent SELECT.
platform_bridge_survey_guards (step 27) follows the canonical and private schema: its invoker
triggers protect imported response graphs and freeze attached Survey/Questionnaire semantics.
An unlinked native index writer takes parent SHARE NOWAIT and rechecks the private attachment;
linked edits refuse before waiting on a parent. Top-level titles, status and windows remain editable.
item_session_grading_floor (step 28) follows the baseline’s Item Session table. Its invoker
trigger prevents client roles from introducing human-grader metadata or altering human-graded
responses, marks and scoring context. Privileged teacher corrections and Person erasure remain
valid. Existing markers are retained; this write boundary does not establish historical provenance.
observation_meeting_records follows the baseline’s observation tables. It
corrects exact original spoken preset copies to the 0–5 scale, preserves extra
historical samples and installs the ordinary learner/Meeting record guard.
client_role_acl (the last row) is the mirror-image exception at the other end: it must sort LAST, after
every table-creating migration and after registry_governance (#9). Its sweep is REVOKE ALL ON ALL TABLES / SEQUENCES / ROUTINES IN SCHEMA public FROM anon, authenticated, PUBLIC, and ALL <class> IN SCHEMA is resolved at execution time against the objects that exist then — a table or function created
by a migration that time-sorts after it would keep the grant it inherited at CREATE time (the Supabase
bootstrap’s for a table, Postgres’s own EXECUTE TO PUBLIC for a function). The migration’s second
half (ALTER DEFAULT PRIVILEGES ... REVOKE for both grantor roles) protects everything created after it
on that same database, so the exposure would be confined to a first install — which is exactly the
install every fresh cluster performs. The sweep also takes the registry-derived authenticated grants
governance installed and the EXECUTE grants the function artifacts (#1, #2, #3) installed, which is why the
migration re-asserts them (see “The client-role ACL floor” below) — and why it has to run after those rather
than before. Adding any new migration therefore means appending a fresh client_role_acl folder
(bun run db:generate:client-role-acl --force-new) so it takes a later timestamp;
migration-drift.test.ts asserts both the content and the last position, so forgetting fails the unit
lane rather than shipping.
Everything after those four: the baseline must come before the
other custom migrations (they reference its tables/policies), and each generator appends a later
timestamp. Rows 6–8 are
order-enforced by DO-block guards that raise at apply time: identity_linking
requires refresh_person_identity_claims (row 6), and supabase_auth_hooks
(trigger v2’s verified-email resolve step, identity-linking-v1) requires
person_contact_point (baseline) and identity_enqueue_merge_review (row 7).
The builders behind every script live in packages/db/src/migration-sql/;
migration-drift.test.ts fails if a committed migration ever lags its builder.
Procedure (additive)
Section titled “Procedure (additive)”Generating migrations is the agent’s job and needs no database. drizzle-kit generate diffs the
Drizzle schema against snapshot.json on disk — it never reads the dev DB — and every
db:generate:<artifact> script compares a builder’s output with the committed files. The dev/smoke
database is the maintainer’s personal database; no integration test depends on it, so it never
gates this work, and an agent never touches it. Applying is the maintainer’s separate step (next
section).
All commands run from packages/db unless noted. Generate in dependency order: a folder’s
timestamp is its apply order, so whatever a migration references must already sit in a folder
generated before it. A builder-backed artifact that references a new table comes after the schema
migration that creates it (step 1, then step 2); a new pgPolicy that calls a new helper function
comes after the helper’s artifact (step 2 first), because Postgres resolves a policy’s functions at
CREATE POLICY time — the reason offering_membership_authority_floor precedes the baseline.
1. Schema change → one drizzle-kit migration (agent)
Section titled “1. Schema change → one drizzle-kit migration (agent)”bun run db:generate --name <snake_name> # snake_case, naming what changedThis writes one new <timestamp>_<snake_name>/ folder (migration.sql + snapshot.json) holding
only the diff since the latest committed snapshot. bun run db:generate --explain prints the planned
SQL without writing anything.
- If drizzle-kit asks a question, stop. A rename — anything it cannot tell apart from a drop +
create — or any other decision it asks for needs a human answer: on a terminal drizzle-kit prompts,
and without one it cannot resolve the decision. An agent never answers or guesses these (no
--hints): it leaves the schema change in place and hands thatdb:generateto the maintainer. - Policies in a schema migration. If the new
migration.sqlcontainsCREATE POLICY(orCREATE FUNCTION), append its name toDRIZZLE_SCHEMA_MIGRATION_NAMESinpackages/db/src/migration-sql/migration-drift.test.ts. The posture-source gate there fails on any unlisted migration that installs apublicfunction or a policy; a drizzle-generated migration is exempt because the ACL derivation reads itspgPolicyobjects from the registry, but it has to be on that list to say so.
2. Builder-backed artifact change → append that artifact (agent)
Section titled “2. Builder-backed artifact change → append that artifact (agent)”A change that a builder in src/migration-sql/ derives from — the sync registry, the erasure registry,
a policy builder, a seed constant, a @pgxsinkit/* bump that changes a rendered artifact — leaves the
committed artifact stale. The drift test names every stale one (from the repo root):
bun test packages/db/src/migration-sql/migration-drift.test.tsEach failing <name> — regenerate with bun run db:generate:… test names its script (the “how” column
of the table above). Run each of them:
bun run db:generate:<artifact> # e.g. db:generate:sync-function, db:generate:identity-linkingEvery db:generate:<artifact> script appends: it compares its builder’s output with the latest
committed *_<name> folder, does nothing when the two are identical, and otherwise scaffolds a new
<timestamp>_<name>/ folder (drizzle-kit generate --custom --name <name>) and writes the builder’s
SQL into its migration.sql. Leave client_role_acl to step 3, even when the drift test names it.
3. Re-emit the ACL floor, last, every time (agent)
Section titled “3. Re-emit the ACL floor, last, every time (agent)”bun run db:generate:client-role-acl --force-newOnce steps 1–2 have appended anything, the ACL floor must become the newest folder again (see its
ordering note above). --force-new appends it even when its content is unchanged — without the flag
the script finds an identical latest folder, does nothing, and the ACL no longer sorts last. Run it
once, after every other generate. migration-drift.test.ts fails on an ACL that is stale and on one
that is not last.
4. Check formatting (agent)
Section titled “4. Check formatting (agent)”Drizzle owns snapshot.json formatting. .oxfmtrc.jsonc excludes those snapshots, and Bun has no
SQL formatter, so both snapshots and migration.sql stay exactly as generated. Check the authored
files through the normal script, from the repo root:
bun run format5. Validate, then hand over (agent)
Section titled “5. Validate, then hand over (agent)”bun run validate # from repo root — typecheck/lint/format + migration-drift testsvalidate is filesystem-only here: its tests run against pgwasm, never the maintainer’s dev
Postgres, so an agent runs it. The agent stops here. The new folders are commit-ready; the most
an agent does next is tell the maintainer that there are new migrations to apply.
Manual-SQL migrations
Section titled “Manual-SQL migrations”The manual-SQL migrations are files, not a paste-from-the-runbook step. storage_buckets
(storage.buckets rows) and credential_signing_role (cluster ROLEs + vault-scoped views + GRANTs)
are DDL Drizzle cannot express and no builder owns, so they live verbatim in
packages/db/scripts/manual-migrations/ and the regeneration script copies them in.
migration-drift.test.ts does not cover them (there is no builder to diff against) — those two
.sql files ARE the source of truth for what a regeneration emits.
Changing one additively is two edits: update the .sql file (it stays the complete definition), and
append a custom migration that carries the change — bun run db:generate --custom --name <snake_name>,
then fill that folder’s migration.sql. Re-copying the whole file is enough when the change only adds
(a new bucket, a new role or grant), because both files re-apply cleanly on a database that already
holds them. It is not enough to change a value an existing row already holds: the bucket inserts are
ON CONFLICT (id) DO NOTHING, so that change needs its own statement.
Re-applying an appended artifact on an existing database
Section titled “Re-applying an appended artifact on an existing database”An appended builder-backed folder re-runs the artifact’s WHOLE SQL on a database that already holds
the previous version. Checked against each committed migration.sql, every artifact is written as an
install-or-replace, so identical or additive changes re-apply cleanly:
- Functions:
CREATE OR REPLACE FUNCTIONthroughout.sync_artifactalso runsDROP FUNCTION IF EXISTSon its current signature first, because its return type is generated. - Triggers:
DROP TRIGGER IF EXISTSthenCREATE TRIGGER(authorization_claim_projection,identity_linking,supabase_auth_hooks,post_safeguarding_audit,content_origin_freeze,content_artifact_freeze). - Policies:
DROP POLICY IF EXISTSthenCREATE POLICY(qti_item_asset_storage_policies,assessment_pnp_proxy_policies,learner_submission_storage_policies). - Grants: plain or role-guarded (
IF EXISTS (SELECT 1 FROM pg_roles …))GRANT/REVOKE/ALTER DEFAULT PRIVILEGES(registry_governance,client_role_acl, and theEXECUTEposture of the function artifacts). - Seeds:
INSERT … ON CONFLICT … DO NOTHING(platform_primitive_organizations,lang_launch_vocabulary). - Queues:
event_lane_artifactisCREATE EXTENSION IF NOT EXISTS pgmqplus onepgmq.create()per queue; the rendered artifact documentspgmq.create()as idempotent. - Guards: the prerequisite DO blocks in
authorization_claim_projection,identity_linkingandsupabase_auth_hooksonly check that what they depend on exists, which it does on such a database.
What install-or-replace does not do:
- It never removes what a builder stopped emitting. A function, trigger or policy that a builder
drops or renames stays on an existing database, because each
DROP … IF EXISTSnames only the current object. The removal has to be explicit — emitted by the builder, or in a separate--custommigration; a hand edit to a builder-backed folder fails the drift gate, which comparesmigration.sqlwith the builder byte for byte. Client-role grants are the exception: every re-emitted ACL floor sweepsREVOKE ALLand re-grants exactly the derived set. CREATE OR REPLACE FUNCTIONcannot change an existing function’s return type or rename its parameters — Postgres refuses — and changing its argument types creates a second overload beside the old one. Onlysync_artifactdrops first, and only its current signature. A change of that kind to any function artifact needs theDROP FUNCTIONemitted before itsCREATE— and a policy or trigger that calls the function blocks that drop until it is handled too.ON CONFLICT DO NOTHINGnever updates a row that is already there. A new seed row re-applies cleanly; a changed seed value does not reach an existing database.lang_launch_vocabularygoes further on purpose: its verification blocksRAISEwhen the row already present contradicts a pinned value, so an appended version that changes a pinned value for an already-seeded language fails on apply. That change needs its own data migration.- Re-running is not free everywhere.
authorization_claim_projectionends with a backfill that callsrefresh_person_identity_claimsfor every person — correct to repeat, but it rewrites every person’s claims inauth.users.
Applying migrations (maintainer only)
Section titled “Applying migrations (maintainer only)”The dev/smoke database is the maintainer’s personal database. No integration test depends on it, so it never blocks generating migrations. An AI assistant or agent is categorically forbidden from dropping, truncating, applying migrations to, or otherwise writing to it — or to any other database.
From packages/db; the connection is DATABASE_URL from ../../.env.development.local:
bun run db:migrate:local # applies the folders the database has not recorded yetbun run db:check:local # snapshot ↔ DB drift checkNo reset is needed for additive migrations: applied state lives in drizzle.__drizzle_migrations,
and the new folders sort after everything already applied. (A regenerated set is different — see the
last section.)
Reference: why each position is what it is
Section titled “Reference: why each position is what it is”The dependency reasons are recorded per step in the script (bun run db:regenerate --list) and, at
length, in the ordering notes above and the sections that follow. Read them before moving a step.
The storage policies and the seeds
Section titled “The storage policies and the seeds”qti_item_asset_storage_policies (ADR-0023 amendment) adds RLS policies on storage.objects (gating
teacher uploads to the item-assets bucket) plus the public.can_manage_offering_assets helper, so it
must time-sort after storage_buckets (#10). Its builder reuses the centralized grant predicate, so
migration-drift.test.ts covers it (bun run db:generate:qti-asset-storage-policies).
It emits CREATE POLICY only — never structural DDL on the Supabase-owned storage schema.
assessment_pnp_proxy_policies (ADR-0021 §6 slice D, O-1) is also script-based and ordered after the
baseline: it adds the public.fn_person_pnp_proxy_allowed SECURITY DEFINER helper plus the permissive
proxy policies on assessment_person_pnp_profile (a teacher/assistant/org-admin of an offering the
learner is enrolled in, or a platform admin, may manage that learner’s PNP profile — OR’d with the
owner policies). It touches only our own public table, so migration-drift.test.ts covers it:
bun run db:generate:pnp-proxy-policieslearner_submission_storage_policies (ADR-0027 §1) is script-based and ordered after the manual
customs (it adds RLS on storage.objects for the learner-submission-artifacts bucket, #10, plus the
public.can_submit_to_attempt SECURITY DEFINER helper). Owner-only (the uploader’s
app_metadata.person_id must own the attempt named in the key’s first segment); CREATE POLICY only.
Covered by migration-drift.test.ts:
bun run db:generate:learner-submission-policiespost_safeguarding_audit (ADR-0029 §6, Slice 4) is script-based and ordered after the baseline: it
adds the public.fn_post_safeguarding_audit SECURITY DEFINER trigger function plus the
post_safeguarding_audit trigger on post, recording every body/status change into the scrub-class
change_audit_entry. It depends only on post + change_audit_entry (baseline). Touches only our
own public schema, so migration-drift.test.ts covers it:
bun run db:generate:post-safeguarding-auditcontent_origin_freeze (ADR-0061; import/content restructure slice R1) is script-based and ordered after
the baseline: it adds the public.fn_content_origin_freeze() trigger function plus the
content_origin_freeze BEFORE INSERT OR UPDATE trigger on content, carrying the two ADR-0061 rules no
declarative construct can express — a reference Content is STAMPED processed on insert (the
vacuous-processed rule; a BEFORE ROW trigger runs before the content_reference_is_processed_ck CHECK, so
an insert that omits the state still lands legal), and a processed Content’s origin + processing outputs
are FROZEN thereafter (RLS cannot compare OLD with NEW, and the sync apply path bypasses any app-layer
guard). SECURITY INVOKER — the body touches no relation, only NEW/OLD. It depends on content, which the
schema migration creates, so it must sort after that; touches only our own public schema, so
migration-drift.test.ts covers it. The pgwasm test harness installs the same SQL AFTER pushSchema for
the same ordering reason (packages/db/src/testing/pgwasm.ts):
bun run db:generate:content-origin-freezecontent_artifact_freeze (ADR-0061; restructure slice R3) is its sibling, and it is ordered after the
same schema migration: it adds public.fn_content_artifact_freeze() plus the content_artifact_freeze
BEFORE UPDATE trigger on content_artifact, refusing any change to an artifact row whose owning Content
is processed — ADR-0061’s “write-once; frozen with their Content”, which R1 shipped as prose and the R3
adversarial review reproduced as a live rewrite of a frozen Content’s pointer and publication claim. A
CHECK cannot see another table and this table carries no RLS, so it has to be a trigger. Unlike the origin
freeze it is SECURITY DEFINER, because the body reads public.content and the writing role may hold no
SELECT on it. UPDATE only: INSERT is how the row-first model works (the row lands before the Content is
processed, and R2’s pass-through rows are inserted alongside a Content minted processed), and DELETE is
what the cascade and the erasure pass need. The pgwasm harness installs it after pushSchema for the same
reason as the origin freeze:
bun run db:generate:content-artifact-freezeplatform_primitive_organizations (ADR-0056 decision 1) is script-based and ordered after the baseline: it
seeds the personal-0 sentinel Organization — the platform-managed host of every personal Offering — as an
idempotent INSERT … ON CONFLICT (id) DO NOTHING. It is a PLATFORM PRIMITIVE, deliberately unlike
ADR-0034’s customer-0 (which the English Planet importer mints as a side effect): the lazy per-person
provisioner must be able to assume the org exists on any fresh database. The id/slug/name come from the
shared TS constants in packages/db/src/schema/platform-primitives.ts, so the migration and app code can
never disagree. Depends only on organization (baseline); covered by migration-drift.test.ts:
bun run db:generate:platform-primitiveslang_launch_vocabulary (ADR-0060; Phase-2 slice 2a-1) is script-based and ordered after the
baseline: it seeds, per launch language, the core subject a person pursues, the module’s
lang_subject_language mapping row, and the language’s ONE machine-lexicon competency_framework +
its permanent rolling current edition (ADR-0057 decision 6) — all as idempotent
INSERT … ON CONFLICT DO NOTHING keyed on natural keys. The pinned ids come from the shared TS
constants in packages/db/src/schema/lang-launch-languages.ts, which the module’s per-language shape
predicates also pin, so the seeded rows and the shipped shapes can never disagree. Depends on
subject, competency_framework, competency_framework_version, and lang_subject_language (all
baseline); covered by migration-drift.test.ts:
bun run db:generate:lang-launch-vocabularyObservation evidence change metadata (step 20)
Section titled “Observation evidence change metadata (step 20)”observation_evidence_clock installs the parent clock guard and the Observation change trigger.
It follows the baseline because it references observation and observation_assessment. Accepted
Observation inserts, updates and deletes advance evidence_changed_at_us, including erasure’s
severing update. This preserves export change metadata after the newest or last fact is removed.
It never changes the declaration’s authored LWW timestamp or stores a projected grade. The clock is
server-owned; both functions are trigger-only and have no client EXECUTE grant. Covered by the native
clock tests and migration-drift.test.ts:
bun run db:generate:observation-evidence-clockItem Session human-grading protection (step 27)
Section titled “Item Session human-grading protection (step 27)”item_session_grading_floor installs the BEFORE INSERT/UPDATE/DELETE trigger protecting the
server-owned humanScored and humanScoredByPersonId keys. Authenticated and anonymous native
roles cannot introduce either key, including false/null values, or modify/delete an already
human-graded row’s protected response, score or identity/context fields. Audit-only reassertions
and ordinary ungraded learner writes remain valid. Native role tests cover direct DML and the
generated apply artifact; API tests cover real teacher evaluation and correction. The trigger
function has no client EXECUTE grant. Generate the additive artifact with:
bun run db:generate:item-session-grading-floorThe migration does not strip legacy markers or backfill trusted score snapshots. Item-level attainment must separately require exact authoritative grading provenance.
The client-role ACL floor (step 28 — always last)
Section titled “The client-role ACL floor (step 28 — always last)”client_role_acl must time-sort after every other migration in the set — see the ordering note above
for why (ALL TABLES IN SCHEMA resolves at execution time). Procedure step 3 re-emits it last after
every additive change, it is the last declared step of regenerate-migration-set.ts, and
migration-drift.test.ts asserts the resulting position.
It installs deny-by-default for the two PostgREST/Supabase client-facing roles on public, then grants
back exactly what the registry and the function artifacts declare:
REVOKE ALL ON ALL TABLES / SEQUENCES / ROUTINES IN SCHEMA public FROM anon, authenticated, PUBLIC— the one-time sweep of what the bootstrap already granted (each Supabase role guarded onpg_rolesexistence, since the same migration set applies to plain Postgres/pgwasm clusters that have no such role).ROUTINES, notFUNCTIONS:ALL FUNCTIONS IN SCHEMAcovers functions/aggregates/window functions but not procedures. TheFROM PUBLICline on routines is the only one of the six that is never a no-op — Postgres grantsEXECUTEtoPUBLICby default on every function created;ALTER DEFAULT PRIVILEGES FOR ROLE supabase_adminandFOR ROLE postgresIN SCHEMA public REVOKE ALL ON TABLES / SEQUENCES / FUNCTIONS FROM anon, authenticated— the durable half, so objects created later never inherit the grant. Both grantors are required: the Supabase bootstrap arms both (for all three object classes), and the fix would be a one-time sweep if either were left armed.FUNCTIONSis the right spelling here —pg_default_aclhas a single object type covering functions and procedures, and it is the spelling the bootstrap used. If the executing role is not a member of a grantor role the blockRAISE WARNINGs and skips rather than failing, so a half-applied floor is visible in the migration log instead of reporting success;- a re-assertion of every
GRANT ... TO authenticatedthatregistry_governance(#9) derives fromauthoritativeSyncRegistry, rendered by the same builder (buildRegistryTableGrants()/renderRegistryTableGrantSql()inpackages/db/src/migration-sql/registry-governance.ts) so the two migrations cannot spell the same grant differently; GRANT EXECUTEon exactly six(function, role)pairs — the deliberate function surface, derived from the other migrations’ own SQL, never hand-listed here:pgxsinkit_clock_us()toanonandauthenticated(re-asserted from what thepgxsinkit_utilitiesartifact declares: 385 baseline column DEFAULTs call the clock and a DEFAULT is evaluated as the writing role),fn_offering_allows_membership_insert(uuid),fn_person_pnp_proxy_allowed(uuid),can_manage_offering_assets(uuid)andcan_submit_to_attempt(uuid)toauthenticated(each is called from an RLS policy — the last two from thestorage.objectspolicies of #12/#14 — and a policy’sUSING/WITH CHECKis evaluated as the querying role, so without EXECUTE the statement fails 42501 before RLS is consulted). Everything else the repo installs inpublic—pgxsinkit_apply_mutations(owner-only by its own artifact’s declaration),build_authorization_claim_payload,refresh_person_identity_claims, theidentity_*helpers,person_is_pristine,identity_issuerand the trigger functions — is granted to no client role. Trigger functions are safe to revoke: Postgres checksEXECUTEon them atCREATE TRIGGERtime, not at fire time.
Why the grant-back is not a loophole. anon ends with nothing on any table or sequence — no connection
and no table policy in this repo names it — and with exactly one privilege in the whole schema:
EXECUTE on public.pgxsinkit_clock_us(). That one is not an oversight and not this migration’s decision:
the pgxsinkit_utilities artifact (#1) declares that posture itself (ADR-0054 decision 5), this floor sorts
after it, and the rule here is that an artifact’s own declaration is re-asserted, never overridden. The
clock is a pure SELECT floor(extract(epoch from clock_timestamp()) * 1000000) — it reads nothing and
writes nothing — so the reachable surface it adds is the current time in microseconds. authenticated is a
different case again: the write path is the owner-executed
pgxsinkit_apply_mutations, and with RLS enabled that function deliberately does
set_config('role', <claims role, default 'authenticated'>, true) before touching a table so the policies
actually evaluate (see the IF p_rls_enabled THEN block at the top of the sync_artifact migration). The
write path therefore runs as authenticated even though nothing connects as it, and a blanket revoke
takes the product’s writes down with it. So the posture is the pgxsinkit one — deny by default, grant back
deliberately — and “deliberately” means the registry, not the bootstrap. The 59 governed tables keep
exactly their declared verbs (a SELECT-only table loses the inherited INSERT/UPDATE/DELETE); the other
~125 hold nothing for either client role.
Why this is needed at all: Supabase’s bootstrap ships ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO anon, authenticated — and the same on SEQUENCES
and on FUNCTIONS, and the same again for postgres — see
infra/compose/entrypoint-masks/init-scripts/02-clean-db.sql. Our migrations run as supabase_admin, so
every table and every function this repo creates in public inherited ALL for both client roles.
Measured on a booted stack before this migration existed: 126 of 184 public tables had no RLS and were
fully reachable by anon. Functions did not even need the bootstrap — Postgres grants EXECUTE to
PUBLIC by default — and measured on a booted stack with the routine sweep neutered, 16 of the 17
functions in public were callable by anon (all but pgxsinkit_apply_mutations, which its own artifact
revokes), and a SET ROLE anon call into the SECURITY DEFINER build_authorization_claim_payload(uuid)
(returns any person’s platform/org/offering grant payload, filtered only on its argument) succeeded.
refresh_person_identity_claims(uuid) — a definer write into auth.users.raw_app_meta_data — was
equally reachable.
Why it is safe: nothing in emergent connects as anon/authenticated — clients reach data through
the API and the native read path (both on the server role), the write path is the owner-executed
pgxsinkit_apply_mutations, and PostgREST is not deployed. What the two roles retain is stated above and
asserted whole-set by the integration lane: anon keeps only EXECUTE on the pgxsinkit clock;
authenticated keeps the registry-declared table verbs, SELECT on the tables those policies join, and
EXECUTE on the four helpers those policies call — every one of which is load-bearing for a path that runs
as authenticated (the apply function’s role switch, and the storage.objects policies on user-JWT
uploads). The migration never names service_role, the app’s own role, or the
credential_signer/holder_signer grants from #11, so those are untouched. If PostgREST is ever exposed,
client reach becomes an explicit per-table GRANT decision.
Dormant, but do not be surprised by it: the apply function’s operations_log INSERT (IF p_log_enabled THEN …) runs inside the role switch — i.e. as authenticated — so if that flag is ever turned on
(p_log_enabled is passed false today, and no operations_log table exists in the schema at all), the
table it creates will need an explicit authenticated INSERT grant or every logged batch will fail 42501
against this floor. Registering it in authoritativeSyncRegistry with governance is the derived way to get
that grant; a hand-written one would be swept away by this migration the next time the ACL floor is re-emitted.
Grants and RLS are independent controls. This is only the grant half — every RLS policy stays exactly
as it is. Do not “simplify” one into the other: RLS decides which rows a privileged role may touch, the
ACL decides whether it is privileged at all, and the tables with no RLS have nothing but this ACL in front
of them. The resulting posture is asserted against a booted stack by
tests/integration/public-table-acl.integration.test.ts (registered in the root test:integration:compose
list), which enumerates every public table, sequence and pg_proc entry rather than sampling —
anon must hold nothing at all beyond the one artifact-declared EXECUTE, and authenticated must hold
exactly the derived set, so both an object that re-opens the hole and a grant that quietly goes missing
fail there. That lane derives its expectation from the migration’s own builder, so it proves the database
matches the builder, not that the builder’s derivation is complete; completeness is gated separately by
the client_role_acl derivation block in packages/db/src/migration-sql/migration-drift.test.ts, which
compares the derivation against the RENDERED policy SQL.
- D4a’s private Push ledger appends
20261003052105_platform_bridge_push, followed by20261003052155_identity_linkingand20261003052254_client_role_acl. These remain unapplied during development. The ledger has no client grants or sync entry; live nullable links sever without deleting uncertain effect history. Sync and registry-governance generators were genuine no-ops. Previously committed folders were not changed. - A new builder-backed migration (a new builder and generator script, i.e. a new migration name)
also needs its drift test in
migration-drift.test.ts; an entry inPOSTURE_SOURCE_MIGRATIONS(packages/db/src/migration-sql/client-role-acl.ts) if it installs apublicfunction or a policy — the posture-source gate fails otherwise; and aSTEPinpackages/db/scripts/regenerate-migration-set.tsin its dependency position (with thebecause:that says why it belongs there) plus a row in the table above, so an approved regeneration reproduces it. The ACL floor stays last there automatically, because it is the last declared step. - A new manual-SQL migration: its
.sqlbody goes inpackages/db/scripts/manual-migrations/, its first folder is appended as in “Manual-SQL migrations”, and itsSTEPnames the file. Nothing is ever pasted from this runbook.
Whole-set regeneration (exceptional, approval-gated)
Section titled “Whole-set regeneration (exceptional, approval-gated)”Never the default, and never an agent’s decision. It runs only with the maintainer’s explicit approval, obtained before it runs and given for that specific occasion, and only when it buys a significant advantage — for example a schema reshape that would otherwise need a long chain of rename migrations, where a baseline stating the end shape directly is clearly worth a database reset. An agent that thinks a regeneration would pay off says so, with the reason, and stops until the approval is given.
bun run db:regenerate --list # from packages/db — print the ordered plan; changes nothing, always allowedbun run db:regenerate --confirm # from packages/db — ONLY with the maintainer's approval for this occasionWithout --confirm the script prints the plan, refuses, and exits 1; nothing is deleted.
With it, one command rebuilds the set, because the ORDER is the whole difficulty and it is declared
once in packages/db/scripts/regenerate-migration-set.ts. The script deletes every
<timestamp>_<name> folder, then walks the declared steps: the four pre-baseline function artifacts,
drizzle-kit generate --name initial_baseline, each builder-backed generator, the two manual-SQL
migrations (filled from scripts/manual-migrations/*.sql), and the client-role ACL floor last — all 28. It pauses ~1s between steps because drizzle-kit’s folder timestamps are second-grained, and it
fails loudly if the emitted order ever differs from the declared one.
The baseline absorbs everything currently in the Drizzle schema, so every migration appended since the
last regeneration collapses: schema migrations into initial_baseline, re-emitted artifacts into their
one step. Leave generated snapshots and SQL unchanged, then validate as in procedure step 5:
bun run validate # from repo rootA regenerated set needs a database reset. None of its folders is recorded in a database that applied the previous set, so applying on top would run the new baseline against objects that already exist. The maintainer resets first.
Reset the dev database (maintainer only)
Section titled “Reset the dev database (maintainer only)”Drop our objects without touching Supabase internals (auth, storage, extensions, …). The
full purge-and-rebuild lives at infra/utils/cloudnativepg/supabase/db/recreate-database.sh
(--with-real-user also loads the language module’s reference data); the SQL below is the lighter
reset that keeps the cluster. Run against the dev DB:
DROP SCHEMA IF EXISTS lti_tool CASCADE;DROP SCHEMA IF EXISTS lrs CASCADE;DROP SCHEMA IF EXISTS caliper CASCADE;DROP SCHEMA IF EXISTS archive CASCADE; -- archive lane (Phase-1 slice C1)DROP EXTENSION IF EXISTS pgmq CASCADE; -- event-lane queues (slice 2a-5); takes the pgmq schema with itDROP SCHEMA IF EXISTS drizzle CASCADE; -- drizzle migration trackingDROP SCHEMA public CASCADE;CREATE SCHEMA public;GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role;GRANT ALL ON SCHEMA public TO postgres, service_role;(Recreating lti_tool/lrs/caliper/archive/pgmq is unnecessary — the baseline creates the
schemas and event_lane_artifact re-creates the extension and its queues. archive carries the
language module’s three native stream tables since Phase-2 slice 2a-4; it was empty in Phase 1, and
drizzle-kit emits CREATE SCHEMA even for a declared-but-empty pgSchema, which is why a reset has
always had to drop it. Dropping pgmq discards any undelivered events — correct for a wipe-and-replay
dev reset, and never a thing to do anywhere else.)
Apply and verify (maintainer only)
Section titled “Apply and verify (maintainer only)”From packages/db:
bun run db:migrate:localbun run db:check:local # snapshot ↔ DB drift checkbun run db:seed:small # optional: load deterministic fixtures