Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
docs: require one database entity per migration and rollback
spacesdrive5d237f1c5231
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 66dcb9b..6798156 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).- The Automations page shows each account's state with pause and resume, counts for the period, and the activity of every comment with its status and a retry (#90)- New tables `automation_accounts`, `automation_rules`, `automation_comments`, `automation_attempts` and `audit_events`, and their functions; existing instances run `npm run db:push` before deploying (#88)- An audit record of connecting, reconnecting and removing accounts and of every automation change, kept a year (#89)+- Every migration now holds one database entity (a table, its access, a trigger, an index or a function) with a rollback of the same size, and the migration test enforces it for new migrations (#93, ADR-041)### Changeddiff --git a/DECISIONS.md b/DECISIONS.mdindex 9cd4bae..51ec3fe 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -878,3 +878,20 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts- `expires_at` is measured from Meta's notification time, which can be later than the comment on a redelivery; a late reply is refused by Instagram and recorded as failed.- Reconnecting renews the token in place, so the "already connected" refusal is gone; the audit table records each reconnect.- A burst over `AUTOMATION_BATCH_SIZE` in one notification waits for the sweep; the cap of 15 follows the free plan's subrequests and can be raised in the code on Workers Paid.++## ADR-041: One database entity per migration file++**Date:** 2026-10-16+**Status:** Accepted++**Decision:** Every migration and its rollback is as small as possible: one database entity per file. A table file holds the table with its columns, keys and checks; its browser access (row level security and the revokes), each trigger, each index and each function have files of their own. A new table is therefore at least four migrations. `backend/tests/database/migrations.test.ts` refuses a migration from version 20261016100000 on that creates more than one entity, or has an empty rollback.++**Context:** The owner asked for migrations divided into the smallest queries possible, at entity level (#93). ADR-038 already split the first migrations per table or function, but the comment automation migrations in #92 put a table, its access, its trigger and up to six indexes in one file. They were not yet applied, so they were split into 36 files before reaching production.++**Alternatives considered:**+- One file per table with everything that belongs to it. Fewer files, but a failed index takes the table's whole file with it, and a rollback cannot remove one index alone.+- One file per SQL statement. A table's access is two statements (enable row level security, revoke) that only make sense together, and a function's grants belong with the function, which the migration test already requires.++**Trade-offs:**+- Many more files per feature; the version numbers order them, and the names say what each holds.+- Migrations before the cut-over version stay as production recorded them; rewriting applied migrations would break the history in `supabase_migrations.schema_migrations`.diff --git a/README.md b/README.mdindex e42dc9a..274359e 100644--- a/README.md+++ b/README.md@@ -509,7 +509,7 @@ twiligent/│ └── types/ # API contract shared by backend and frontend (types only)│├── supabase/-│ ├── migrations/ # Versioned schema changes, one table or function per file, applied with npm run db:push+│ ├── migrations/ # Versioned schema changes, one table, access, trigger, index or function per file, applied with npm run db:push│ ├── rollbacks/ # The reverse of each migration, same file name, run by hand│ └── config.toml # Supabase CLI config (Postgres 17)│diff --git a/claude.md b/claude.mdindex 057e3b7..1f41f10 100644--- a/claude.md+++ b/claude.md@@ -47,7 +47,7 @@ site/ public marketing site and docs (Vite, React, MDX); docs pabuild plugins in site/build/, tests in site/tests/scripts/ publish-scheduled.ts, run by GitHub Actions with no dependencies; check-platform-packages.ts,run after npm ci in every workflow-supabase/ the database schema: migrations/ (versioned SQL, one table or function per file, applied+supabase/ the database schema: migrations/ (versioned SQL, one table, access, trigger, index or function per file, appliedwith the Supabase CLI), rollbacks/ (the reverse of each migration, same file name),config.toml (CLI config, Postgres 17)```@@ -209,7 +209,8 @@ Read `docs/guidelines/CODE_STYLE.md` before writing code and run its checklist b- Formatting follows the file: 4 spaces in `backend/`, 2 elsewhere, single quotes, semicolons, trailing commas- Pure logic goes in a plain `.ts` helper (`lib/`) so Node can test it; markup used twice becomes a component; copy that changes by mode lives in a typed table- `scripts/` stays free of npm packages but may import a `backend/lib/` helper that imports nothing at runtime, so both schedulers share one set of rules (`scheduledPublishing.ts`)-- The schema changes only through a migration in `supabase/migrations/` plus its rollback in `supabase/rollbacks/`, one table or one function per file; repositories update `data` through the merge functions, never by reading it and writing it back+- The schema changes only through a migration in `supabase/migrations/` plus its rollback in `supabase/rollbacks/`; repositories update `data` through the merge functions, never by reading it and writing it back+- Every migration and its rollback is as small as possible, one database entity per file: a table (with its columns, keys and checks), its browser access, one trigger, one index or one function. A new table is at least four migrations (the table, its access, its `updated_at` trigger, each index). Split any large query into one file per entity before it is applied; never edit a migration production already recorded. `backend/tests/database/migrations.test.ts` enforces it- New row ids come from `newRowId()` in `backend/lib/ids.ts` (`crypto.randomUUID()`)- Tests use `node:test` with sentence names that describe behaviour, live in `tests/` mirroring the source path, and use the smallest typed fake- When the code and `CODE_STYLE.md` disagree, update the guide in the same changediff --git a/docs/architecture/data-flows/AUTOMATION.md b/docs/architecture/data-flows/AUTOMATION.mdindex cf0da7c..58c199a 100644--- a/docs/architecture/data-flows/AUTOMATION.md+++ b/docs/architecture/data-flows/AUTOMATION.md@@ -189,5 +189,5 @@ Everything runs on the existing Worker, Supabase project and Workers Free plan;| Platform | `services/instagram/instagramMessaging.ts` || Rules | `lib/automationMatching.ts`, `lib/automationDelivery.ts`, `lib/metaWebhookSignature.ts` || Repositories | `repositories/automationRuleRepository.ts`, `automationCommentRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` |-| Database | `supabase/migrations/20261016100000` to `20261016101000` |+| Database | `supabase/migrations/20261016100000` to `20261016103500`, one entity per file || App | `frontend/src/features/automations/` |diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex 54a06ae..377b2d9 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -18,7 +18,7 @@ The schema lives in versioned migrations in `supabase/migrations/`, applied with| Path | Holds ||---|---|-| `supabase/migrations/<version>_<name>.sql` | One change to one table or one function. The 14 digit version orders the files |+| `supabase/migrations/<version>_<name>.sql` | One database entity: a table, its browser access, one trigger, one index or one function. The 14 digit version orders the files || `supabase/rollbacks/<version>_<name>.sql` | The reverse of the migration with the same file name. The CLI has no down migrations, so these are run by hand || `supabase/config.toml` | The CLI's default config, with `major_version = 17` to match the hosted database || `supabase/.gitignore` | Keeps the CLI's `.temp` and `.branches` folders and local env files out of git |@@ -36,10 +36,12 @@ The first four files are baselines. Each recreates one table as it stood before| 7 | `create_set_updated_at_function`, `add_<table>_updated_at` (three files), `add_tracked_posts_updated_at_trigger` | The `updated_at` column and its trigger on every table || 8 | `create_merge_account_data_function`, `create_merge_scheduled_post_function`, `create_merge_tracked_post_data_function` | The merge functions below || 9 | `index_accounts_list`, `index_scheduled_posts_list`, `index_scheduled_posts_schedulers`, `index_tracked_posts_list` | The indexes below |-| 10 | `create_automation_accounts`, `create_automation_rules`, `create_automation_comments`, `create_automation_attempts`, `create_audit_events` | The automation and audit tables, each with its constraints, row level security, trigger and indexes |+| 10 | For each of `automation_accounts`, `automation_rules`, `automation_comments`, `automation_attempts` and `audit_events`: `create_<table>`, `revoke_browser_access_<table>`, `add_<table>_updated_at_trigger`, then one `index_<table>_<purpose>` per index | The automation and audit tables, one entity per file (29 files) || 11 | `index_accounts_instagram_user` | The webhook's lookup of an account by its Instagram id || 12 | `create_automation_rules_for_ig_user_function`, `create_claim_automation_comments_function`, `create_reserve_automation_send_function`, `create_finish_automation_send_function`, `create_automation_stats_function` | The automation functions below |+From order 10 on, every migration creates at most one entity, and the migration test enforces it. The files before it were applied to production first and stay as recorded.+To change the schema, follow `docs/features/NEW_DATABASE_TABLE.md` (Write the Migration). The commands are in `docs/workflows/DEPLOYMENT.md`.---diff --git a/docs/features/NEW_DATABASE_TABLE.md b/docs/features/NEW_DATABASE_TABLE.mdindex c7bde4e..c2371d5 100644--- a/docs/features/NEW_DATABASE_TABLE.md+++ b/docs/features/NEW_DATABASE_TABLE.md@@ -23,13 +23,27 @@ Decide the column structure. Follow the existing conventions:### Step 2: Write the Migration-The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI. Never create or change a table in the SQL editor or the Table Editor. One file holds one change to one table or one function.+The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI. Never create or change a table in the SQL editor or the Table Editor.++**Keep every migration as small as possible: one database entity per file.** A table file holds the table with its columns, keys and checks. Its browser access, each trigger, each index and each function get files of their own, and every file gets a rollback of the same size under the same name. A small file is easy to review, fails alone when it fails, and rolls back one thing. `backend/tests/database/migrations.test.ts` refuses a migration that creates more than one entity. Never split or edit a migration production has already recorded; write a new one instead.++A new table is therefore four or more migrations, run in this order:++| File | Holds | Rollback |+|---|---|---|+| `create_content_drafts` | `create table` with columns, keys and checks | `drop table if exists` |+| `revoke_browser_access_content_drafts` | `enable row level security` and `revoke all ... from anon, authenticated` | `disable row level security` (new tables start without browser grants) |+| `add_content_drafts_updated_at_trigger` | The `set_updated_at()` trigger | `drop trigger if exists` |+| `index_content_drafts_<purpose>` | One index, named for the query it serves | `drop index if exists` |```bashnpm run db:new create_content_drafts+npm run db:new revoke_browser_access_content_drafts+npm run db:new add_content_drafts_updated_at_trigger+npm run db:new index_content_drafts_user_id_created_at```-This creates `supabase/migrations/<timestamp>_create_content_drafts.sql`. Write the table with its constraints, row level security, trigger and index:+`create_content_drafts`:```sql-- drafts a user prepares before scheduling them@@ -47,25 +61,40 @@ create table public.content_drafts (constraint content_drafts_status_check check (status in ('draft', 'ready', 'archived')),constraint content_drafts_data_check check (jsonb_typeof(data) = 'object'));+```--- only the Worker's service role reads the table; the anon key ships in every browser+`revoke_browser_access_content_drafts`:++```sql+-- only the Worker's service role reads content_drafts; the anon key ships in every browseralter table public.content_drafts enable row level security;revoke all on table public.content_drafts from anon, authenticated;+```+`add_content_drafts_updated_at_trigger`:++```sql+-- set_updated_at() keeps updated_at, so no query has to set itcreate trigger content_drafts_set_updated_at before update on public.content_draftsfor each row execute function public.set_updated_at();+```+`index_content_drafts_user_id_created_at`:++```sql-- contentDrafts.listForUser: where user_id = $1 order by created_at desccreate index content_drafts_user_id_created_at_idx on public.content_drafts (user_id, created_at desc);```-Write the reverse in `supabase/rollbacks/` with the same file name. `backend/tests/database/migrations.test.ts` fails when a migration has no rollback:+Write the reverse of each in `supabase/rollbacks/` with the same file name. `backend/tests/database/migrations.test.ts` fails when a migration has no rollback or an empty one. The table's rollback:```sql-- removes the table and every draft in itdrop table if exists public.content_drafts;```+The others are one line each: `alter table public.content_drafts disable row level security;`, `drop trigger if exists content_drafts_set_updated_at on public.content_drafts;` and `drop index if exists public.content_drafts_user_id_created_at_idx;`. Roll them back newest first, so the table goes last.+If the repository updates `data`, add a merge function in its own migration (`npm run db:new create_merge_content_draft_function`), so an update is one statement and two writers never undo each other. Copy `create_merge_scheduled_post_function.sql`. A function in `public` is exposed through the Data API, so it always revokes execute from the browser roles and grants it only to the service role; the migration test enforces the revoke:```sqldiff --git a/docs/guidelines/CODE_STYLE.md b/docs/guidelines/CODE_STYLE.mdindex c06f39a..47017b1 100644--- a/docs/guidelines/CODE_STYLE.md+++ b/docs/guidelines/CODE_STYLE.md@@ -82,7 +82,7 @@ The layers are in `docs/architecture/backend/REQUEST_PIPELINE.md`; the recipes a- Redis code catches every failure and falls back; nothing else swallows errors, with two exceptions that log instead: a job that works through many items (the scheduled publisher, the reply processor, the token refresh) catches one item's failure and moves on, and a secondary step after the main write (subscribing an account when a rule is turned on) is logged with `context.log.warn` so the main result still stands.- A platform call whose every failure leads somewhere different may answer a result union instead of throwing (`sendPrivateReply` returns `{ kind: 'accepted' | 'error' | 'ambiguous' | 'not_sent' }`); the decision table lives in a pure `lib/` helper (`finishPlan` in `lib/automationDelivery.ts`) with its tests.- Work after a response goes through `inBackground(c, label, work)` in `controllers/http.ts`, which gives it its own deadline, never `c.executionCtx.waitUntil()` with the request's services.-- The schema changes only through a migration in `supabase/migrations/` (`npm run db:new <verb>_<object>`) with its reverse in `supabase/rollbacks/` under the same name, one table or one function per file; a repository updates `data` through a merge function with `db.rpc()`, never by reading and writing it back. See `docs/features/NEW_DATABASE_TABLE.md`.+- The schema changes only through a migration in `supabase/migrations/` (`npm run db:new <verb>_<object>`) with its reverse in `supabase/rollbacks/` under the same name, one database entity per file: a table (with its columns, keys and checks), its browser access, one trigger, one index or one function (a new table is at least four files; the test in `tests/database/migrations.test.ts` refuses a file that creates more); a repository updates `data` through a merge function with `db.rpc()`, never by reading and writing it back. See `docs/features/NEW_DATABASE_TABLE.md`.- New row ids come from `newRowId()` in `lib/ids.ts`; tests pin them with `mockRowIds()` from `tests/fixtures/rowIds.ts`.- No new runtime dependency in the Worker without approval: call HTTP APIs with `fetch` (Resend is called this way, not through its SDK).diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.mdindex e42bd8f..9a3ba93 100644--- a/docs/guidelines/NAMING.md+++ b/docs/guidelines/NAMING.md@@ -75,7 +75,7 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.| Object | Convention | Examples ||---|---|---|-| Migration name | verb first, then the object; one table or one function per file | `baseline_accounts`, `add_accounts_updated_at`, `create_merge_account_data_function`, `revoke_browser_access_settings` |+| Migration name | verb first, then the object; one entity per file | `create_automation_rules`, `revoke_browser_access_automation_rules`, `add_automation_rules_updated_at_trigger`, `index_automation_rules_enabled_account`, `create_merge_account_data_function` || Value checks migration | `check_<table>_values` | `check_scheduled_posts_values` || Index migration | `index_<table>_<query>`, named for the query the index serves | `index_accounts_list`, `index_scheduled_posts_schedulers` || Index | `<table>_<columns>_idx`, or the purpose for a partial index | `accounts_user_id_created_at_idx`, `scheduled_posts_due_idx`, `scheduled_posts_claimed_idx` |diff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.mdindex 8629784..b563f8e 100644--- a/docs/guidelines/SUPABASE.md+++ b/docs/guidelines/SUPABASE.md@@ -90,7 +90,7 @@ Each function returns `true` when a row matched and `null` when none did, so the## Schema Changes-The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI (`npm run db:check`, then `npm run db:push`). Never change a table, index or function in the SQL editor. Each change is one file for one table or one function, with its reverse in `supabase/rollbacks/` under the same name. A new function in `public` revokes execute from `public, anon, authenticated` and grants it only to `service_role`. The workflow is in `docs/features/NEW_DATABASE_TABLE.md`.+The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI (`npm run db:check`, then `npm run db:push`). Never change a table, index or function in the SQL editor. Each migration is as small as possible, one database entity per file: a table (with its columns, keys and checks), its browser access, one trigger, one index or one function, with its reverse in `supabase/rollbacks/` under the same name. A new function in `public` revokes execute from `public, anon, authenticated` and grants it only to `service_role`. The workflow is in `docs/features/NEW_DATABASE_TABLE.md`.New row ids come from `newRowId()` in `backend/lib/ids.ts` (`crypto.randomUUID()`), never from the time or `Math.random`.diff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.mdindex 2863b39..e06363d 100644--- a/docs/workflows/FEATURE_DEVELOPMENT.md+++ b/docs/workflows/FEATURE_DEVELOPMENT.md@@ -81,7 +81,7 @@ Before creating new patterns, check:## Phase 4: Implement**Step 11 - Implement in this order:**-1. DB schema changes (if any): a migration from `npm run db:new <verb>_<object>` and its rollback in `supabase/rollbacks/`, one table or one function per file - see `docs/features/NEW_DATABASE_TABLE.md`+1. DB schema changes (if any): a migration from `npm run db:new <verb>_<object>` and its rollback in `supabase/rollbacks/`, one entity per file (a table, its access, a trigger, an index or a function) - see `docs/features/NEW_DATABASE_TABLE.md`2. Types: request, response and entity shapes in `shared/types/` (types only, no runtime code); see `docs/guidelines/TYPESCRIPT.md`3. Backend: `validators/` parsers for new request bodies and query strings4. Backend: `repositories/` additions (new query methods; user-scoped ones end in `ForUser`)diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 1527524..ed11094 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -76,7 +76,7 @@ Backend route and cron service tests (`tests/routes/*Routes.test.ts`, `tests/serScheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.test.ts` covers the shared rules: the 20 minute lease outlasts the 14 minute limit of both schedulers, what a run does for each container status, which Graph API codes count as temporary, when a failure retries or fails, and when the final message says publishing stopped. `tests/repositories/scheduledPostRepository.test.ts` runs the claim against the fake Supabase client: two schedulers claiming the same listed post (only the first gets it, and the claim counts an attempt), which claims are stale and that a takeover must match the expired claim it saw, that a post being published is not deleted, and that an edit only lands while the post is pending. The `scheduled publisher recovery` block in `tests/services/scheduledPublisher.test.ts` runs the whole publisher: a publish reply lost on the way back is checked on Instagram and marked published, an unreadable container status leaves the post claimed, an expired claim is taken over and found published or publishes its ready container, a claim inside its lease is left alone, a passing failure goes back to `pending` and the third fails the post, a run past its deadline claims nothing, and a post taken over after its last attempt is only checked. On the frontend, `tests/features/publishing/scheduleHelpers.test.ts` covers when the overdue alert counts a retried post (from its last claim) and a stuck claim (after the lease and 30 minutes).-The database migrations have their own test. `tests/database/migrations.test.ts` reads `supabase/migrations/` and `supabase/rollbacks/` and checks that every file is named `<14 digit version>_<lowercase name>.sql` with a unique version, that the baseline files come before every change, that every change has a rollback with the same name and every rollback has its migration, that the baselines use only `if not exists` for tables, indexes and columns so they can run again, that every function a migration creates revokes execute from `public, anon, authenticated`, and that no file uses an em or en dash. It does not run the SQL; CI has no database. The migrations themselves were checked once on a local Postgres before the first push (ADR-038).+The database migrations have their own test. `tests/database/migrations.test.ts` reads `supabase/migrations/` and `supabase/rollbacks/` and checks that every file is named `<14 digit version>_<lowercase name>.sql` with a unique version, that the baseline files come before every change, that every change has a rollback with the same name and every rollback has its migration, that the baselines use only `if not exists` for tables, indexes and columns so they can run again, that every function a migration creates revokes execute from `public, anon, authenticated`, that every migration from version 20261016100000 on creates at most one entity (a table, its access, a trigger, an index or a function) and has a rollback that is not empty, and that no file uses an em or en dash. It does not run the SQL; CI has no database. The migrations themselves were checked once on a local Postgres before the first push (ADR-038).Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, a cancelled run and one without time for a whole send handing their jobs back unstarted, and a run claiming only what its subrequests pay for. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/repositories/automationCommentRepository.test.ts` pages through comments stored in the same instant without skipping or repeating one, and checks the hand-back of unstarted jobs. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.