@protobase/cli 0.51.2 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/build/app-icons.js +2 -1
  2. package/dist/build/favicon-file.js +5 -0
  3. package/dist/build/favicon-ico.js +20 -0
  4. package/dist/build/favicon.js +1 -2
  5. package/dist/build/service-worker-code.js +1 -1
  6. package/dist/cli/package.js +1 -1
  7. package/dist/config/build-project.js +1 -0
  8. package/dist/dev/entry.js +2 -1
  9. package/dist/doctor/relation-issues.js +13 -0
  10. package/dist/doctor/run.js +6 -1
  11. package/dist/migration/adopt-public-record.js +15 -0
  12. package/dist/migration/apply-migrations.js +8 -4
  13. package/dist/migration/load-project.js +1 -0
  14. package/dist/migration/parts.js +6 -1
  15. package/dist/project/favicon-link.js +12 -2
  16. package/dist/project/project-admin.js +1 -0
  17. package/dist/project/service-worker.js +1 -1
  18. package/dist/scaffold/plan.d.ts +2 -0
  19. package/dist/scaffold/plan.js +7 -3
  20. package/dist/scaffold/protobase-tables.d.ts +1 -1
  21. package/dist/scaffold/protobase-tables.js +8 -1
  22. package/dist/scaffold/referenced.d.ts +6 -0
  23. package/dist/scaffold/referenced.js +38 -0
  24. package/dist/scaffold/run.js +2 -1
  25. package/dist/scaffold/tables.d.ts +2 -1
  26. package/dist/scaffold/tables.js +18 -9
  27. package/dist/scaffold-api.d.ts +2 -1
  28. package/dist/scaffold-api.js +2 -1
  29. package/dist/serve/lifecycle.js +2 -1
  30. package/dist/serve/static-site.js +3 -0
  31. package/dist/supabase/dump-phase.js +12 -10
  32. package/dist/supabase/load-phase.js +5 -6
  33. package/dist/supabase/platform-schemas.js +42 -0
  34. package/dist/supabase/project-users.d.ts +10 -0
  35. package/dist/supabase/project-users.js +38 -0
  36. package/dist/supabase/realtime-policies.js +8 -24
  37. package/dist/supabase/realtime-schema.js +73 -0
  38. package/dist/supabase/report.js +1 -1
  39. package/dist/supabase/source-facts.js +3 -35
  40. package/dist/supabase/users-migrations.js +2 -2
  41. package/package.json +7 -7
  42. package/skills/protobase/references/features/ai.md +5 -0
  43. package/skills/protobase/references/features/compatibility.md +1 -1
  44. package/skills/protobase/references/features/look-and-language.md +1 -1
  45. package/skills/protobase/references/getting-started.md +5 -3
  46. package/skills/protobase/references/guides/deploy.md +1 -1
  47. package/skills/protobase/references/reference/app-identity.md +3 -1
  48. package/skills/protobase/references/reference/assistant.md +2 -2
  49. package/skills/protobase/references/reference/cli.md +8 -8
  50. package/skills/protobase/references/reference/comments.md +2 -0
  51. package/skills/protobase/references/reference/config/api.md +13 -2
  52. package/skills/protobase/references/reference/config.md +1 -1
  53. package/skills/protobase/references/reference/mcp.md +43 -10
  54. package/skills/protobase/references/reference/notifications.md +1 -1
  55. package/skills/protobase/references/reference/supabase-realtime.md +30 -4
  56. package/skills/protobase/references/reference/webhooks.md +1 -0
@@ -1,24 +1,23 @@
1
1
  import { loadProjectAuth } from "../users/load-auth.js";
2
2
  import { connect } from "../db/connect.js";
3
+ import { authStorageSchemas } from "./platform-schemas.js";
3
4
  import { runScaffold } from "../scaffold/run.js";
4
5
  import { writeAuthMigration } from "../auth/write-migration.js";
6
+ import { writeMigration } from "./migration-files.js";
7
+ import { providerCounts } from "./identity-providers.js";
8
+ import { accountsMigration } from "./users-migrations.js";
5
9
  import { runDoctor } from "../doctor/run.js";
6
10
  import { convertedCronJobs } from "./cron-plan.js";
7
11
  import { importState } from "./import-state.js";
8
- import { writeMigration } from "./migration-files.js";
9
12
  import { runPgTool } from "./pg-tools.js";
10
13
  import { loadScript, qualified } from "./load-script.js";
11
14
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
12
- import { providerCounts } from "./identity-providers.js";
13
- import { accountsMigration } from "./users-migrations.js";
14
15
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
15
16
  import { importReport } from "./report.js";
16
17
  import { existsSync } from "node:fs";
17
18
  import path from "node:path";
18
19
  import { rm, writeFile } from "node:fs/promises";
19
20
  //#region src/supabase/load-phase.ts
20
- /** Schemas the import restores that scaffolding leaves alone: Supabase Auth's and Storage's own tables are no resources. */
21
- const platformSchemas = ["auth", "storage"];
22
21
  /**
23
22
  * Fails unless every dumped table exists on the target, created by the applied migration, and holds no rows yet, and
24
23
  * the project has none of the files the converted pg_cron jobs go to.
@@ -76,7 +75,7 @@ const runLoadPhase = async (options, out) => {
76
75
  await rm(state.data);
77
76
  if (replay) await rm(replay);
78
77
  out(`loaded ${manifest.tables.reduce((sum, table) => sum + table.rows, 0)} rows into ${manifest.tables.length} tables; each count matches the source\n`);
79
- const schemas = manifest.schemas.filter((schema) => !platformSchemas.includes(schema));
78
+ const schemas = manifest.schemas.filter((schema) => !authStorageSchemas.includes(schema));
80
79
  const sql = connect(options.targetUrl);
81
80
  const excludes = await otherTables(sql, schemas, manifest.tables).finally(() => sql.end());
82
81
  const realtime = manifest.realtimeTables.map((table) => `${table.schema}.${table.table}`);
@@ -0,0 +1,42 @@
1
+ //#region src/supabase/platform-schemas.ts
2
+ /**
3
+ * Schemas of a Supabase database that belong to the platform rather than the app: its services' own (Realtime, Vault,
4
+ * GraphQL, webhooks, migrations, the pooler) and those of its extensions, which the migration makes with them (pgmq's
5
+ * holds only its own tables, but is no member of it). The import leaves them behind.
6
+ */
7
+ const serviceSchemas = [
8
+ "extensions",
9
+ "graphql",
10
+ "graphql_public",
11
+ "realtime",
12
+ "_realtime",
13
+ "vault",
14
+ "pgsodium",
15
+ "pgsodium_masks",
16
+ "supabase_functions",
17
+ "supabase_migrations",
18
+ "cron",
19
+ "net",
20
+ "pgmq",
21
+ "pgbouncer",
22
+ "_analytics",
23
+ "pgtle"
24
+ ];
25
+ /**
26
+ * Supabase Auth's and Storage's own schemas, which are the platform's too, but the app's tables point at them and its
27
+ * triggers and policies live in them, so the import carries them over; their tables are no resources.
28
+ */
29
+ const authStorageSchemas = ["auth", "storage"];
30
+ /** What marks a database as Supabase's: its auth, storage and migrations schemas and its roles. */
31
+ const databaseMarkers = async (sql) => {
32
+ const [row] = await sql`
33
+ select
34
+ array(select nspname::text from pg_namespace where nspname in ('auth', 'storage', 'supabase_migrations') order by 1) as schemas,
35
+ array(select rolname::text from pg_roles where rolname in ('anon', 'authenticated', 'service_role', 'supabase_admin') order by 1) as roles
36
+ `;
37
+ return row;
38
+ };
39
+ /** What `markers` lack of a Supabase database, its auth and storage schemas and its own admin role: nothing for one. */
40
+ const missingMarkers = (markers) => [...authStorageSchemas.filter((schema) => !markers.schemas.includes(schema)).map((schema) => `schema ${schema}`), ...markers.roles.includes("supabase_admin") ? [] : ["role supabase_admin"]];
41
+ //#endregion
42
+ export { authStorageSchemas, databaseMarkers, missingMarkers, serviceSchemas };
@@ -0,0 +1,10 @@
1
+ //#region src/supabase/project-users.d.ts
2
+ /**
3
+ * Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own auth.users, as `protobase import
4
+ * supabase` does on its copy: points its Better Auth setup at auth.users, removes the migrations of Protobase's own user
5
+ * table, and writes, in `db/migrations`, the columns Better Auth needs on auth.users, Better Auth's tables next to it
6
+ * and the users' accounts with their Supabase passwords and social providers. It only reads the database, which the
7
+ * project's auth keeps a connection pool open on, so the process must end itself.
8
+ */
9
+ export declare const useSupabaseUsers: (projectDir: string, out: (text: string) => void) => Promise<void>;
10
+ //#endregion
@@ -0,0 +1,38 @@
1
+ import { loadProjectAuth } from "../users/load-auth.js";
2
+ import { writeAuthMigration } from "../auth/write-migration.js";
3
+ import { planAuthConfig } from "./auth-config.js";
4
+ import { writeMigration } from "./migration-files.js";
5
+ import { authStoreMigrations } from "./store-migrations.js";
6
+ import { accountsMigration, usersColumnsMigration } from "./users-migrations.js";
7
+ import path from "node:path";
8
+ import { mkdir, rm } from "node:fs/promises";
9
+ //#region src/supabase/project-users.ts
10
+ /**
11
+ * Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own auth.users, as `protobase import
12
+ * supabase` does on its copy: points its Better Auth setup at auth.users, removes the migrations of Protobase's own user
13
+ * table, and writes, in `db/migrations`, the columns Better Auth needs on auth.users, Better Auth's tables next to it
14
+ * and the users' accounts with their Supabase passwords and social providers. It only reads the database, which the
15
+ * project's auth keeps a connection pool open on, so the process must end itself.
16
+ */
17
+ const useSupabaseUsers = async (projectDir, out) => {
18
+ const migrationsDir = path.join(projectDir, "db", "migrations");
19
+ const authConfig = await planAuthConfig(projectDir);
20
+ const storeMigrations = await authStoreMigrations(migrationsDir);
21
+ const relative = (to) => path.relative(projectDir, to);
22
+ for (const store of storeMigrations) await rm(path.join(migrationsDir, store));
23
+ await mkdir(migrationsDir, { recursive: true });
24
+ const usersFile = await writeMigration(migrationsDir, "supabase_users", usersColumnsMigration());
25
+ await authConfig.write();
26
+ if (storeMigrations.length > 0) out(`removed ${storeMigrations.length} migrations of Protobase's own user table: auth.users replaces it\n`);
27
+ out(`wrote ${relative(path.join(migrationsDir, usersFile))}, the columns Better Auth needs on auth.users, and pointed ${relative(authConfig.file)} at it\n`);
28
+ const authFile = await writeAuthMigration({
29
+ auth: await loadProjectAuth(projectDir),
30
+ dir: migrationsDir,
31
+ name: "auth"
32
+ });
33
+ if (authFile) out(`wrote ${relative(authFile)}, Better Auth's tables next to auth.users\n`);
34
+ const accountsFile = await writeMigration(migrationsDir, "supabase_accounts", accountsMigration());
35
+ out(`wrote ${relative(path.join(migrationsDir, accountsFile))}, the users' accounts with their Supabase passwords and social providers\n`);
36
+ };
37
+ //#endregion
38
+ export { useSupabaseUsers };
@@ -1,3 +1,4 @@
1
+ import { realtimeSchemaSql } from "./realtime-schema.js";
1
2
  import { isSupabaseRole } from "./rewrite.js";
2
3
  //#region src/supabase/realtime-policies.ts
3
4
  /**
@@ -14,25 +15,6 @@ const realtimePolicies = async (query) => {
14
15
  return policies;
15
16
  };
16
17
  const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
17
- const schema = `create schema realtime;
18
-
19
- create table realtime.messages (
20
- topic text not null,
21
- extension text not null,
22
- payload jsonb,
23
- event text,
24
- private boolean,
25
- updated_at timestamp without time zone not null default now(),
26
- inserted_at timestamp without time zone not null default now(),
27
- id uuid not null default gen_random_uuid() primary key
28
- );
29
-
30
- create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
31
-
32
- alter table realtime.messages enable row level security;
33
- grant usage on schema realtime to anon, authenticated, service_role;
34
- grant select, insert, update, delete on realtime.messages to anon, authenticated, service_role;
35
- `;
36
18
  const policySql = (policy) => {
37
19
  const roles = policy.roles.filter((role) => !isSupabaseRole(role));
38
20
  if (roles.length === 0) return `-- Left out by protobase import supabase: the policy ${JSON.stringify(policy.name)} names only Supabase's own roles.\n`;
@@ -45,14 +27,16 @@ const policySql = (policy) => {
45
27
  ].join("");
46
28
  };
47
29
  /**
48
- * The migration that makes Supabase's `realtime.messages` and `realtime.topic()` with the source's policies on it, which
49
- * decide who may join, hear and send on a private channel of `/api/sb/realtime/v1`. The role that applies it owns the
50
- * table; the server's probes need the app's database role to own it or to bypass row security.
30
+ * The migration that makes Supabase's `realtime` schema (`realtimeSchemaSql`) with the source's policies on
31
+ * `realtime.messages`, which decide who may join, hear and send on a private channel of `/api/sb/realtime/v1`. The
32
+ * role that applies it owns the table; the server's probes, and its reads of the messages the database broadcasts,
33
+ * need the app's database role to own it or to bypass row security.
51
34
  */
52
35
  const realtimeMigration = (policies) => [
53
36
  "-- realtime.messages of a Supabase database with its row security policies, which authorize private Realtime\n",
54
- "-- channels, written by `protobase import supabase`.\n\n",
55
- schema,
37
+ "-- channels, and realtime.send() and realtime.broadcast_changes(), which broadcast from the database, written by\n",
38
+ "-- `protobase import supabase`.\n\n",
39
+ realtimeSchemaSql,
56
40
  "\n",
57
41
  ...policies.map(policySql)
58
42
  ].join("");
@@ -0,0 +1,73 @@
1
+ //#region src/supabase/realtime-schema.ts
2
+ /**
3
+ * Supabase's `realtime.messages`, unpartitioned, with the columns its policies may read, `realtime.topic()`, and
4
+ * `realtime.send()` and `realtime.broadcast_changes()` as Supabase Realtime defines them, which broadcast from the
5
+ * database: a message inserted in the table, which the server takes out of it once its transaction commits and sends to
6
+ * the channels joined on its topic. `send()` stamps a message with the clock rather than the transaction's start, so
7
+ * the messages of one transaction keep their order. The server's probes of a private channel's policies insert in
8
+ * transactions they roll back, which send nothing.
9
+ */
10
+ const realtimeSchemaSql = `create schema realtime;
11
+
12
+ create table realtime.messages (
13
+ topic text not null,
14
+ extension text not null,
15
+ payload jsonb,
16
+ event text,
17
+ private boolean,
18
+ updated_at timestamp without time zone not null default now(),
19
+ inserted_at timestamp without time zone not null default now(),
20
+ id uuid not null default gen_random_uuid() primary key
21
+ );
22
+
23
+ create index messages_broadcasts on realtime.messages (inserted_at) where extension = 'broadcast';
24
+
25
+ create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
26
+
27
+ create function realtime.send(payload jsonb, event text, topic text, private boolean default true) returns void language plpgsql as $$
28
+ declare
29
+ generated_id uuid;
30
+ final_payload jsonb;
31
+ begin
32
+ begin
33
+ generated_id := gen_random_uuid();
34
+ if payload ? 'id' then
35
+ final_payload := payload;
36
+ else
37
+ final_payload := jsonb_set(payload, '{id}', to_jsonb(generated_id));
38
+ end if;
39
+ execute format('set local realtime.topic to %L', topic);
40
+ insert into realtime.messages (id, payload, event, topic, private, extension, inserted_at)
41
+ values (generated_id, final_payload, event, topic, private, 'broadcast', clock_timestamp());
42
+ exception
43
+ when others then
44
+ raise warning 'WarnSendingBroadcastMessage: %', sqlerrm;
45
+ end;
46
+ end;
47
+ $$;
48
+
49
+ create function realtime.broadcast_changes(topic_name text, event_name text, operation text, table_name text, table_schema text, new record, old record, level text default 'ROW') returns void language plpgsql as $$
50
+ declare
51
+ row_data jsonb := '{}'::jsonb;
52
+ begin
53
+ if level = 'STATEMENT' then
54
+ raise exception 'function can only be triggered for each row, not for each statement';
55
+ end if;
56
+ if operation = 'INSERT' or operation = 'UPDATE' or operation = 'DELETE' then
57
+ row_data := jsonb_build_object('old_record', old, 'record', new, 'operation', operation, 'table', table_name, 'schema', table_schema);
58
+ perform realtime.send(row_data, event_name, topic_name);
59
+ else
60
+ raise exception 'Unexpected operation type: %', operation;
61
+ end if;
62
+ exception
63
+ when others then
64
+ raise exception 'Failed to process the row: %', sqlerrm;
65
+ end;
66
+ $$;
67
+
68
+ alter table realtime.messages enable row level security;
69
+ grant usage on schema realtime to anon, authenticated, service_role;
70
+ grant select, insert, update, delete on realtime.messages to anon, authenticated, service_role;
71
+ `;
72
+ //#endregion
73
+ export { realtimeSchemaSql };
@@ -1,5 +1,5 @@
1
- import { convertedCronJobs } from "./cron-plan.js";
2
1
  import { providerFate } from "./identity-providers.js";
2
+ import { convertedCronJobs } from "./cron-plan.js";
3
3
  //#region src/supabase/report.ts
4
4
  /** Protobase Cloud's Starter plan holds this much data; the import reports a larger database, it does not refuse it. */
5
5
  const starterBytes = 524288e3;
@@ -1,44 +1,12 @@
1
+ import { serviceSchemas } from "./platform-schemas.js";
1
2
  //#region src/supabase/source-facts.ts
2
- /**
3
- * Schemas of a Supabase database that belong to the platform rather than the app: its services' own (Realtime, Vault,
4
- * GraphQL, webhooks, migrations, the pooler) and those of its extensions, which the migration makes with them (pgmq's
5
- * holds only its own tables, but is no member of it). auth and storage are the platform's too, but the app's tables
6
- * point at them and its triggers and policies live in them, so the import carries them over.
7
- */
8
- const platformSchemas = [
9
- "extensions",
10
- "graphql",
11
- "graphql_public",
12
- "realtime",
13
- "_realtime",
14
- "vault",
15
- "pgsodium",
16
- "pgsodium_masks",
17
- "supabase_functions",
18
- "supabase_migrations",
19
- "cron",
20
- "net",
21
- "pgmq",
22
- "pgbouncer",
23
- "_analytics",
24
- "pgtle"
25
- ];
26
3
  /** The tables in auth and storage that record the platform's own migrations, which Protobase never runs. */
27
4
  const platformMigrationTables = ["auth.schema_migrations", "storage.migrations"];
28
- /** What marks a database as Supabase's: its auth, storage and migrations schemas and its roles. */
29
- const databaseMarkers = async (sql) => {
30
- const [row] = await sql`
31
- select
32
- array(select nspname::text from pg_namespace where nspname in ('auth', 'storage', 'supabase_migrations') order by 1) as schemas,
33
- array(select rolname::text from pg_roles where rolname in ('anon', 'authenticated', 'service_role', 'supabase_admin') order by 1) as roles
34
- `;
35
- return row;
36
- };
37
5
  /** auth, storage and every schema the app made, which the dumps take. */
38
6
  const appSchemas = async (sql) => {
39
7
  return (await sql`
40
8
  select n.nspname as name from pg_namespace n
41
- where not starts_with(n.nspname, 'pg_') and n.nspname <> 'information_schema' and n.nspname <> all(${platformSchemas})
9
+ where not starts_with(n.nspname, 'pg_') and n.nspname <> 'information_schema' and n.nspname <> all(${serviceSchemas})
42
10
  and not exists (select 1 from pg_depend d where d.classid = 'pg_namespace'::regclass and d.objid = n.oid and d.deptype = 'e')
43
11
  order by 1
44
12
  `).map((row) => row.name);
@@ -190,4 +158,4 @@ const httpTriggers = (sql, schemas) => sql`
190
158
  order by 1, 2, 3
191
159
  `;
192
160
  //#endregion
193
- export { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
161
+ export { appSchemas, cronJobs, cronTimezone, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
@@ -1,6 +1,6 @@
1
1
  import { accountIdSql, accountProviderSql, carriesAccountSql, confirmedOwnerSql } from "./identity-providers.js";
2
2
  //#region src/supabase/users-migrations.ts
3
- /** The import's first run: the user columns Better Auth needs that GoTrue's auth.users lacks, empty for now. */
3
+ /** The user columns Better Auth needs that GoTrue's auth.users lacks, empty for now. */
4
4
  const usersColumnsMigration = () => `-- The columns Better Auth needs on Supabase's auth.users, written by \`protobase import supabase\`.
5
5
  -- Empty until the import's accounts migration fills them from what Supabase recorded; NULL where it recorded nothing.
6
6
  alter table auth.users
@@ -15,7 +15,7 @@ alter table auth.users
15
15
  -- The value GoTrue writes into every user it makes, for the triggers and policies that read it on new sign-ups.
16
16
  alter table auth.users alter column role set default 'authenticated', alter column aud set default 'authenticated';
17
17
  `;
18
- /** The import's second run, once the data is loaded and Better Auth's tables are planned: the users' columns and accounts. */
18
+ /** Once auth.users has its rows and Better Auth's tables are planned: the users' columns and accounts. */
19
19
  const accountsMigration = () => `-- Supabase's users signing in with Better Auth, written by \`protobase import supabase\` once their rows were loaded.
20
20
 
21
21
  -- The user columns, from what Supabase Auth recorded. A ban lasts until banned_until, as on Supabase: Better Auth lifts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.51.2",
3
+ "version": "0.52.0",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -42,12 +42,12 @@
42
42
  "dependencies": {
43
43
  "@better-auth/core": "^1.7.12",
44
44
  "@hono/node-server": "^2.1.3",
45
- "@protobase/config": "0.51.2",
46
- "@protobase/layout": "0.51.2",
47
- "@protobase/query": "0.51.2",
48
- "@protobase/schema": "0.51.2",
49
- "@protobase/server": "0.51.2",
50
- "@protobase/ui": "0.51.2",
45
+ "@protobase/config": "0.52.0",
46
+ "@protobase/layout": "0.52.0",
47
+ "@protobase/query": "0.52.0",
48
+ "@protobase/schema": "0.52.0",
49
+ "@protobase/server": "0.52.0",
50
+ "@protobase/ui": "0.52.0",
51
51
  "@react-email/render": "^2.1.0",
52
52
  "@scalar/hono-api-reference": "^0.12.10",
53
53
  "@tailwindcss/vite": "^4.3.3",
@@ -10,7 +10,12 @@ Fields and actions filled by a model, the assistant beside the admin, and MCP.
10
10
  - [Choice of model](../reference/assistant.md#which-backend): The assistant runs on OpenRouter or any OpenAI-compatible endpoint, also a local one.
11
11
  - [Assistant tools](../reference/assistant.md#the-apps-own-tools): Your own tools for the assistant, acting on records as the user.
12
12
  - [MCP server](../reference/mcp.md#the-tools): AI clients connect to the app over MCP as the signed-in person, and list, find and read records within that person's access, soft-deleted ones too when asked.
13
+ - [MCP counts](../reference/mcp.md#the-tools): AI clients count the records a filter finds, in all or per value of a field such as a status, without reading the records.
14
+ - [MCP result size](../reference/mcp.md#result-size): Every tool result fits what AI clients take, as valid JSON: long values are cut and named, a page holds fewer records, and the client reads the rest in pieces.
15
+ - [MCP app icon](../reference/mcp.md#the-apps-icon): AI clients show the app's own icon beside its name when someone adds its MCP endpoint.
13
16
  - [MCP writes](../reference/mcp.md#writes): When turned on, for every resource or only those you list, AI clients create, update and delete records after the person approves each write.
17
+ - [Small MCP write results](../reference/mcp.md#what-a-write-returns): A write over MCP returns the record's key, new ETag, the fields written and the read-only fields that changed, not the whole record; `fields` asks for more.
14
18
  - [MCP writes without approval](../reference/mcp.md#writes-without-approval): Roles you name, such as service accounts, write over MCP without being asked to approve each write; everyone else is still asked.
19
+ - [MCP comments](../reference/mcp.md#comments): AI clients read a record's comments, and with MCP writes on add one after the person approves it.
15
20
  - [MCP batch writes](../reference/mcp.md#batch-writes): When MCP writes are on, AI clients make many creates, updates and deletes across resources in one transaction, after the person approves the batch.
16
21
  - [Connected apps](../reference/auth.md#oauth-for-mcp-clients): People allow an AI client to sign in, and disconnect it later.
@@ -10,5 +10,5 @@ Apps written for other systems that keep working on Protobase, and moving their
10
10
  - [Supabase client API](../reference/supabase-rest.md): supabase-js `from()` and `rpc()` calls keep working, under the tables' RLS policies.
11
11
  - [Supabase Auth](../reference/auth.md#supabase-js-and-supabasessr): `supabase.auth` and `@supabase/ssr` calls keep working.
12
12
  - [Supabase Storage](../reference/supabase-storage.md): supabase-js storage calls keep working, over the app's file storage.
13
- - [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels, private ones authorized by the policies on `realtime.messages`, and broadcasts sent from a server without joining a channel.
13
+ - [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels, private ones authorized by the policies on `realtime.messages`, broadcasts sent from a server without joining a channel, and broadcasts from the database with `realtime.send()` and `realtime.broadcast_changes()`, across [several processes](../reference/supabase-realtime.md#several-processes) serving one app.
14
14
  - [Edge Functions](../guides/api-functions.md#functions-moved-from-supabase): Functions moved from Supabase answer at their old addresses.
@@ -6,7 +6,7 @@ The app's colours, name, icon, language and installation.
6
6
 
7
7
  - [Theme](../reference/theme.md): One CSS file sets the app's colours, corners and fonts for light and dark, and keeps working on every release.
8
8
  - [Dark mode](../reference/theme.md#light-dark-or-the-system): Each user picks light, dark or the system setting.
9
- - [App name, icon and colours](../reference/app-identity.md): The app's own name, icon and colours in the sidebar, browser tabs, home-screen icon and mail.
9
+ - [App name, icon and colours](../reference/app-identity.md): The app's own name, icon and colours in the sidebar, browser tabs, `/favicon.ico`, home-screen icon and mail.
10
10
  - [Logo and favicon](../reference/theme.md#logo-and-favicon): Your own favicon or logo replaces Protobase's.
11
11
  - [English and Dutch](../reference/languages.md): The built-in screens come in English and Dutch, with numbers and dates written to match.
12
12
  - [Installable app](../reference/installable-app.md): The admin installs as an app on phones and computers, and says when the server cannot be reached.
@@ -35,11 +35,11 @@ A scratch app starts without resources, so `protobase doctor` refuses it until i
35
35
  ```sh
36
36
  # db/migrations/007_customers.sql: create table customers (id bigint generated always as identity primary key, name text not null);
37
37
  bun run db:migrate
38
- bun run protobase scaffold --ui --yes --exclude public.schema_migrations
38
+ bun run protobase scaffold --ui --yes
39
39
  bun run protobase doctor
40
40
  ```
41
41
 
42
- `scaffold` writes `config/customers/data.ts` and `ui.ts` and exports them from `config/index.ts`, where Protobase finds every resource, view and page; `--exclude public.schema_migrations` leaves out the table the migrate script records its migrations in. `bun run dev` shows the new list at once. The [Data config](reference/data-config.md) and [UI config](reference/ui-config.md) say what else a resource can be.
42
+ `scaffold` writes `config/customers/data.ts` and `ui.ts` and exports them from `config/index.ts`, where Protobase finds every resource, view and page. `bun run dev` shows the new list at once. The [Data config](reference/data-config.md) and [UI config](reference/ui-config.md) say what else a resource can be.
43
43
 
44
44
  ### On an existing database
45
45
 
@@ -59,7 +59,9 @@ It connects read-only and names the database and its Postgres version, then asks
59
59
 
60
60
  Then it runs that `scaffold` in the project and prints the next steps. Without a terminal it asks nothing: the folder is the database's name, and every table gets a resource and a `ui.ts`. Quote the URL, as a shell reads `?` and `&` in it. `--preset` is refused with a URL: the project starts from scratch.
61
61
 
62
- It never writes to the database. The first of the next steps does: `bun run db:migrate` adds the `auth` schema that sign-in keeps its users in, and `public.schema_migrations`, where the script records the migrations it applied.
62
+ It never writes to the database. The first of the next steps does: `bun run db:migrate` adds the `auth` schema that sign-in keeps its users in, and the `migrations` schema, where the script records the migrations it applied in `migrations.applied`. A `public.schema_migrations` another migration tool keeps is left as it is.
63
+
64
+ On a Supabase database, which it knows by its `auth` and `storage` schemas and its `supabase_admin` role, as [`import supabase`](reference/cli.md#import-supabase) does, the `auth` schema is Supabase Auth's, not Protobase's. It leaves out `auth`, `storage` and the platform's other schemas, such as `realtime` and `supabase_migrations`, as Supabase's own tables, and signs the project in on Supabase's `auth.users`, as the import does: it points `protobase.config.ts` at `auth.users` and writes migrations in place of those of Protobase's own user table, the columns Better Auth needs on `auth.users`, Better Auth's tables next to it, and each user's account with their Supabase password and social providers. `bun run db:migrate` then applies them, and Supabase's users sign in with their own passwords. <gap>A user who signs up through Supabase Auth after that cannot sign in to the app with their password because carrying later sign-ups over is not implemented.</gap>
63
65
 
64
66
  ```sh
65
67
  cd shop
@@ -32,7 +32,7 @@ The host serves `public/` itself and sends only the manifest's `api` paths to th
32
32
 
33
33
  ## Migrations
34
34
 
35
- Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `public.schema_migrations` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth store has not applied every auth migration of the new version, which it reads from the store's `auth_migrations` table without comparing its tables (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts.
35
+ Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `migrations.applied` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A database an earlier version migrated keeps its record in `public.schema_migrations`, which `migrate` copies over the first time; a `public.schema_migrations` of another migration tool, without Protobase's `name` and `applied_at` columns, is never read or written. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth store has not applied every auth migration of the new version, which it reads from the store's `auth_migrations` table without comparing its tables (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts.
36
36
 
37
37
  ## Images
38
38
 
@@ -9,7 +9,7 @@ An app looks like its own everywhere from three things in its project: its name,
9
9
  | What | Where | Used by |
10
10
  | --- | --- | --- |
11
11
  | Name | `name` in `protobase.config.ts` ([config](config.md)), overridden at run time by `PROTOBASE_APP_NAME` | the sidebar's logo, the end of every tab title, the installed app's name, the [mobile app](../guides/mobile-app.md)'s name on the phone, passkey and authenticator prompts, auth mail and its sender's name |
12
- | Icon | `protobase.favicon.svg` at the project's root | the browser tab, the sidebar's logo, the installed app's icon; the [mobile app](../guides/mobile-app.md) shows Protobase's icon instead |
12
+ | Icon | `protobase.favicon.svg` at the project's root | the browser tab, `/favicon.ico`, the sidebar's logo, the installed app's icon, the [MCP endpoint](mcp.md#the-apps-icon)'s icon in AI clients; the [mobile app](../guides/mobile-app.md) shows Protobase's icon instead |
13
13
  | Raster icons | optional PNGs beside the SVG, below | the iPhone home screen and Android launchers, which take no SVG |
14
14
  | Colours | `themeColor` and `backgroundColor` in `protobase.config.ts` | the installed app's title bar and its start screen |
15
15
 
@@ -41,6 +41,8 @@ Some platforms take no SVG, so a project may put PNGs of the same icon beside it
41
41
  | `protobase.icon-512.png` | 512 × 512 | the web manifest, for Android's install screens |
42
42
  | `protobase.icon-maskable.png` | 512 × 512 | the web manifest's maskable icon, which Android crops to its own shape: keep the mark within the middle 80% |
43
43
 
44
+ The app answers `/favicon.ico`, which browsers and favicon services ask for when they have not read the page, with its icon: the 192 pixel PNG, else the touch icon, else the 512 pixel PNG, else the SVG, each with its own content type. Without a favicon of its own the app answers Protobase's.
45
+
44
46
  Each is optional, and none is made from the SVG: without the touch icon an iPhone's home screen shows a picture of the page. `protobase build` copies the ones the project has to the bundle's `public/`, and fails on a file that is no PNG or not its size; `protobase dev` serves them from the project's root.
45
47
 
46
48
  ## The colours
@@ -57,7 +57,7 @@ The model needs tool calling for the queries. A refused key, an exhausted accoun
57
57
 
58
58
  It lives at `/api/assistant` on the app's own origin and answers with the user's token like the rest of the API. Its system prompt describes the resources, tables and fields the user can see in `/meta`. It has two tools of its own, and [the app's](#the-apps-own-tools):
59
59
 
60
- - **`run_read_only_query`** runs one `SELECT` (or `VALUES`, or a `WITH` query) and shows its rows as a table in the chat. It runs in a `READ ONLY` transaction that is always rolled back, with a statement timeout of 5 seconds and at most 200 rows. Postgres refuses every write inside (`SET TRANSACTION READ WRITE`, writable CTEs, `nextval`, `DO` blocks, functions that write), and settings it changes go with the rollback. The statement runs through the function `query.run_read_only` as the role `<database>_query`, which [`protobase migration`](cli.md#migration) makes: that role may read every column of the resources' tables, `.sensitive()` fields and the [webhook subscriptions'](webhooks.md) signing secrets included, and nothing else: not the auth store, nor a table without a resource. The function opens the statement as a cursor, so only one statement runs, and Postgres refuses a change of role inside it. Numbers other than integers of up to 15 digits come back as their exact text, such as `"12.50"`.
60
+ - **`run_read_only_query`** runs one `SELECT` (or `VALUES`, or a `WITH` query) and shows its rows as a table in the chat. It runs in a `READ ONLY` transaction that is always rolled back, with a statement timeout of 5 seconds and at most 200 rows. Postgres refuses every write inside (`SET TRANSACTION READ WRITE`, writable CTEs, `nextval`, `DO` blocks, functions that write), and settings it changes go with the rollback. The statement runs through the function `query.run_read_only` as the role `<database>_query`, which [`protobase migration`](cli.md#migration) makes: that role may read every column of the resources' tables, `.sensitive()` fields and the [webhook subscriptions'](webhooks.md) signing secrets included, and nothing else: not the auth store, nor a table without a resource. The function opens the statement as a cursor, so only one statement runs, and Postgres refuses a change of role inside it. Numbers other than integers of up to 15 digits come back as their exact text, such as `"12.50"`. The model reads the rows within the [result size](mcp.md#result-size) of MCP's tools, as every built-in tool's result.
61
61
  - **`propose_write_query`** never runs on its own. It shows the statement and a summary on a card with **Approve** and **Reject**. Only Approve runs it, as one statement in a read-write transaction; Reject, or no answer within 10 minutes, runs nothing. The model gets the returned rows, or that nothing ran. Statements are `INSERT`, `UPDATE` or `DELETE` with a `RETURNING` clause.
62
62
 
63
63
  Both run **outside Protobase's access rules and tenant scoping**: whoever has the `admin` or `ai` role can read every resource's table, and with approval change everything the app's database role can, since `propose_write_query` still runs as that role. Give the app a database role without superuser rights, and those roles only to people who may see all of the data.
@@ -68,7 +68,7 @@ Making the query role needs `CREATEROLE` once, for the role that applies the mig
68
68
 
69
69
  `assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores; the same tools can be offered over the app's [MCP endpoint](mcp.md#building-on-it).
70
70
 
71
- `context` holds the user's `session`, `locale` (the language they read, `'en'` or `'nl'`, for the texts a tool shows them such as its approvals; set over MCP, absent in the dock), `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
71
+ `context` holds the user's `session`, `locale` (the language they read, `'en'` or `'nl'`, for the texts a tool shows them such as its approvals; set over MCP, absent in the dock), `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `aggregate(resource, { group_by, filter?, limit?, label? })` with its counts per value as `:aggregate` gives them, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
72
72
 
73
73
  A tool with a [widget](#widget-parts) creates or finds what it is about, shows a widget with its id, and returns the id and the state at that moment:
74
74
 
@@ -49,9 +49,9 @@ The serve runtime is bundled by `protobase build-serve` into one JavaScript file
49
49
  protobase scaffold [connection string | --env VAR] [target] [options]
50
50
  ```
51
51
 
52
- Without a connection string or `--env`, the URL is `DATABASE_URL`, from the environment or the nearest `.env` at or above the current directory, as `dev` reads it. `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended.
52
+ Without a connection string or `--env`, the URL is `DATABASE_URL`, from the environment or the nearest `.env` at or above the current directory, as `dev` reads it. `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended. A table that a written one points to with a foreign key is written too, outside the target or excluded, unless it has a resource already, since the app refuses a relation to a resource it does not have; a line names each.
53
53
 
54
- Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_migrations` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), and pg-boss's `jobs` schema. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
54
+ Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_migrations` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), pg-boss's `jobs` schema, and the `migrations` schema whose `applied` table records the migrations applied. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` or `migrations` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
55
55
 
56
56
  | Option | Effect |
57
57
  | --- | --- |
@@ -85,7 +85,7 @@ The list `--ui` writes shows five columns at most: the key unless it is a uuid,
85
85
  - Computed defaults (function, sequence, expression, `GENERATED BY DEFAULT` identity): `.dbDefault()`. It also gets `.readOnly()` when the column is an identity column, a primary-key column, or an audit timestamp (`created_at`, `inserted_at`, `updated_at`, `modified_at`, or the same in camelCase, such as `createdAt`); other computed defaults, such as `order_date DEFAULT current_date`, stay editable. `GENERATED ALWAYS` identity and generated columns are only `.readOnly()`.
86
86
  - Leading column of a non-partial index: `.filterable()`; of a btree: also `.sortable()`. Not applied to json.
87
87
  - The text field that names a record (`name`, `title`, `number`, `sku`, `email`, `code` or `description`, else the first text field) becomes the resource's `.search(...)` when a non-partial pg_trgm index (`gin_trgm_ops` or `gist_trgm_ops`) serves it, so the [global search](client.md#global-search) finds its records by name. Without one the API would refuse the search, so it is left out; add the index and run `protobase scaffold` on a new resource, or add `.search` by hand.
88
- - Key: primary key (composite supported), else the first unique index with only `NOT NULL` columns, else the table is skipped with a warning. A view or materialized view is skipped with a warning too, as Postgres knows no key for it: declare a resource over one by hand.
88
+ - Key: primary key (composite supported), else the first unique index with only `NOT NULL` columns, else the table is skipped with a warning. <gap>A table that points to a skipped table without a key cannot start, as writing its foreign key as a plain field instead of a relation is not implemented; `doctor` reports the relation.</gap> A view or materialized view is skipped with a warning too, as Postgres knows no key for it: declare a resource over one by hand.
89
89
  - `deleted_at`, `removed_at`, `archived_at` (nullable timestamp/date) become `.softDelete`; `organization_id` and `tenant_id` become `.tenant`.
90
90
  - Unique indexes are listed in the doc comment above the resource.
91
91
  - Field names are the column names in snake_case; `.column()` is written only when the schema builder's default mapping would not give the column back (always for `hr."EMP_MASTER"`).
@@ -109,7 +109,7 @@ The URL comes as for [`scaffold`](#scaffold): the connection string, the variabl
109
109
 
110
110
  Imports `config/index.ts` and the views of `config/*/ui.ts`, as the config module has them by convention, and checks every exported resource against the database:
111
111
 
112
- - error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index
112
+ - error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index, relation to a resource the config does not declare
113
113
  - error: a read the [scan guard](api.md#safety) refuses, because no index serves a column it filters, sorts, searches or counts by. Doctor reads each table's indexes from the catalog, as the server does, and judges with the scan guard's own rule every read the API takes and the app makes: a filter on each `.filterable()` field, a sort by each `.sortable()` one, `search()` over the search fields, a role's own records (`.owner()`) and the names a relation shows; each view's list in its order and with the filter it opens with, its filter widgets and their counts, its chart, its map, board, calendar and timeline, its card photos, its order by hand, its related sections, galleries and charts, its named lists, its recent records and a saved search's new records; and each block of a [composed page](layouts.md) that lists records, and each `Chart` block's grouped and split fields. Each error is an index to add, with every request that needs it and where it comes from:
114
114
 
115
115
  ```
@@ -513,7 +513,7 @@ For a project with [organizations](auth.md#organizations); `<organization>` is a
513
513
  protobase migration [--dir db/migrations] [--extend <dir>]
514
514
  ```
515
515
 
516
- Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when sign-in is on (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks` or `notifications`, or a resource has events, history, comments or an [AI field](ai.md) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas) and the triggers that keep the rollups (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`NNN_webhooks.sql`), and the [devices and history tables](notifications.md#table-names) of `notifications` (`NNN_notifications.sql`). It compares the database, with the project's migrations applied, with the config (for the auth schema, it reads the store's record of the migrations it applied), merged with those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL`.
516
+ Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when sign-in is on (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks` or `notifications`, or a resource has events, history, comments or an [AI field](ai.md) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas) and the triggers that keep the rollups (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`NNN_webhooks.sql`), the [devices and history tables](notifications.md#table-names) of `notifications` (`NNN_notifications.sql`), and the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`NNN_realtime_relay.sql`). It compares the database, with the project's migrations applied, with the config (for the auth schema, it reads the store's record of the migrations it applied), merged with those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL`.
517
517
 
518
518
  ```sh
519
519
  bun run db:migrate # the database at the project's current schema
@@ -538,7 +538,7 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
538
538
 
539
539
  Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
540
540
 
541
- 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. When the source has row security policies on `realtime.messages`, it writes `NNN_supabase_realtime.sql`, which makes `realtime.messages` and `realtime.topic()` with those policies, so the app's [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
541
+ 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. It writes `NNN_supabase_realtime.sql`, which makes `realtime.messages`, `realtime.topic()`, and Supabase's `realtime.send()` and `realtime.broadcast_changes()`, so the app's triggers and SQL keep [broadcasting from the database](supabase-realtime.md#broadcast-from-the-database), with the source's row security policies on `realtime.messages`, so its [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
542
542
  2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
543
543
  3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, and declares it in the `jobs` of `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md) so [`/api/sb/realtime/v1`](supabase-realtime.md) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, writes Better Auth's other tables next to `auth.users` as [`auth migration`](#auth-migration) does (`NNN_auth.sql`), then `NNN_supabase_accounts.sql`, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, each sign-in provider's identities, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing. `NNN_supabase_accounts.sql` fills the user columns from what Supabase Auth recorded and leaves them empty where it recorded nothing: the name from `raw_user_meta_data`'s `full_name` or `name`, the picture from its `avatar_url` or `picture`, `email_verified` from `email_confirmed_at`, and a ban from `banned_until`, which Better Auth lifts once it has passed. It gives each password of a confirmed address, as Supabase hashed it, a `credential` account (a user who never confirmed theirs signs in by code or resets the password, since GoTrue refused their password sign-in too), and each identity of a social provider an account under Better Auth's name for it (`azure` is `microsoft`, keyed on the `oid` claim; `linkedin_oidc` is `linkedin`, `slack_oidc` is `slack`, `x` is `twitter`), unless its user has an address they never confirmed, since GoTrue refused that sign-in too. Email, phone, anonymous and single sign-on identities and sessions do not carry over. <gap>The import cannot carry over MFA factors because that is not implemented.</gap> <gap>The import cannot carry over passkeys because that is not implemented.</gap>
544
544
  4. **Apply the migrations** again. Supabase's users then sign in with their own passwords, and with a social provider once it is in the `socialProviders` of the config's `auth`; new users get a UUID in `auth.users`, so the app's triggers there run for them.
@@ -594,10 +594,10 @@ Copies the agent skills of this CLI's version into the current project, or only
594
594
  ```sh
595
595
  bun run db:up && bun run --cwd tests/apps/erp db:migrate && bun run --cwd tests/apps/erp db:seed --scale small
596
596
  bun run --cwd tests/apps/erp protobase scaffold postgres://protobase:protobase@localhost:55432/protobase \
597
- --yes --ui --exclude public.schema_migrations --exclude public.seed_info
597
+ --yes --ui --exclude public.seed_info
598
598
  bun run --cwd tests/apps/erp protobase doctor postgres://protobase:protobase@localhost:55432/protobase
599
599
  ```
600
600
 
601
- The ERP keeps Better Auth's users, sessions and signing keys in the `auth` schema of the same database; scaffold leaves that store out on its own, so they are never exposed through the admin API. `--exclude` leaves out the migrations' and the seed's own bookkeeping tables.
601
+ The ERP keeps Better Auth's users, sessions and signing keys in the `auth` schema of the same database; scaffold leaves that store out on its own, so they are never exposed through the admin API. `--exclude` leaves out the seed's own bookkeeping table.
602
602
 
603
603
  The integration test (`packages/cli/tests/scaffold/scaffold.integration.test.ts`) scaffolds into a temp folder and is skipped when the database is unreachable.
@@ -56,6 +56,8 @@ Whoever may read the record may read its comments and add one: the same tenant,
56
56
 
57
57
  `GET /api/v1/{resource}/{key}:comments` reads them newest first, `POST` to the same path adds one, and `GET /api/v1/{resource}/{key}:mentionable?q=` lists whom a comment may mention. See [REST API](api.md#record-comments).
58
58
 
59
+ An AI client reads and adds them over the app's [MCP endpoint](mcp.md#comments), with `list_comments` and `add_comment`, under the same rules.
60
+
59
61
  ## Moderation
60
62
 
61
63
  Once a resource takes comments, admins get **Comments** (the built-in resource `record_comments`): every comment of every resource, newest first, filterable by resource, record, author and time. Only the `admin` role reads it, whatever the project's roles say; deleting a comment there is how a wrong or abusive one goes. When a resource with comments has a [tenant](data-config.md#resource), the list is scoped to the caller's tenant.