@simetrajs/designer 0.1.0 → 0.3.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +39 -4
  2. package/dist/{command-CRUaUglx.js → command-CHk1P9Dp.js} +91 -108
  3. package/dist/default-dir-DerxTbci.js +158 -0
  4. package/dist/errors-D1P2kKbL.js +62 -0
  5. package/dist/init-jr0Xsrpp.js +832 -0
  6. package/dist/invoke-BwP_5iN6.js +2676 -0
  7. package/dist/main.js +6 -6
  8. package/dist/mcp-args-D63akJ97.js +56 -0
  9. package/dist/mcp-jLOz0W7f.js +219 -0
  10. package/dist/package-hA0J8AMK.js +4 -0
  11. package/dist/{schema-engine-DAsJEc8K.js → schema-engine-8rVHcVYO.js} +704 -195
  12. package/dist/{types-CSc8XWLd.js → types-CMcZhIci.js} +8 -3
  13. package/package.json +16 -12
  14. package/skills/simetra-adoption/SKILL.md +82 -3
  15. package/skills/simetra-metadata/SKILL.md +126 -136
  16. package/skills/simetra-metadata/references/agents-over-mcp.md +236 -0
  17. package/skills/simetra-metadata/references/attribute-load-and-size.md +57 -0
  18. package/skills/simetra-metadata/references/list-order-indexes.md +17 -0
  19. package/skills/simetra-metadata/references/object-modules.md +78 -0
  20. package/skills/simetra-metadata/references/people-and-rights.md +702 -9
  21. package/skills/simetra-metadata/references/plan-and-apply.md +81 -0
  22. package/skills/simetra-metadata/references/project-setup.md +28 -0
  23. package/skills/simetra-metadata/references/row-version-epoch.md +39 -0
  24. package/skills/simetra-metadata/references/search-fields.md +28 -0
  25. package/skills/simetra-metadata/references/sql-trust-boundary.md +225 -0
  26. package/dist/errors-D5pJLrjP.js +0 -36
  27. package/dist/mcp-CJDCleh-.js +0 -241
  28. package/dist/package-DDuGk6yE.js +0 -5
  29. package/dist/report-D2jBS_04.js +0 -1550
@@ -7,6 +7,13 @@ Contents:
7
7
  - Users, authorship and membership
8
8
  - Rights declarations
9
9
  - Rights sets and roles
10
+ - Adopted membership and assignment sources
11
+ - Who reads what
12
+ - Who writes what
13
+ - Generated privileges
14
+ - Platform roles
15
+ - Reading past row-level security
16
+ - Carrier copies
10
17
 
11
18
  ## Users, authorship and membership
12
19
 
@@ -31,7 +38,12 @@ People are platform data, not tables you write yourself:
31
38
  the provider's account table.
32
39
  - **Authorship.** `trackAuthor: true` on a Catalog or a Document adds the
33
40
  standard `createdBy` and `updatedBy` references to the users catalog;
34
- without a users catalog it is an error (`users.catalog-missing`).
41
+ without a users catalog it is an error (`users.catalog-missing`). Under a
42
+ command the platform forces `createdBy`/`updatedBy` to the current user;
43
+ `createdBy` never changes; a `beforeWrite` handler may not assign them,
44
+ and a subscription may not list them in `whenChanged`.
45
+ Outside a command (an import, a migration) whoever writes the row sets
46
+ them.
35
47
  - **Membership.** A scoped catalog with `membership: { "user": "<attribute>" }`
36
48
  is the membership of its scope kind: the attribute is a scalar `Ref` to the
37
49
  users catalog, nullable for an invited member without an account. The
@@ -40,11 +52,26 @@ People are platform data, not tables you write yourself:
40
52
  its scope set function from that catalog. Use it instead of a hand-written
41
53
  member table and set function. One membership catalog per scope kind.
42
54
 
55
+ The platform layer (identities, the current user, provisioning) lives in the
56
+ PG schema `simetra`, generated when a users catalog exists, or when the
57
+ project has a membership source and its provider's user id is the `sub` claim
58
+ (then only the current-user function, no identities table). The schema is
59
+ reserved: no object, `defaultSchema`, set function, external reference,
60
+ event handler or SQL unit may use it, and there is no `metadata/sql/simetra/`
61
+ folder (`schema.reserved`). In SQL, the
62
+ current user is `(select simetra.current_user_id())`, written exactly so in a
63
+ policy (`sql.bare-current-user` rejects a bare call there); it is `NULL` for
64
+ an anonymous session or an anonymous sign-in of the provider, a service
65
+ session and an invalid user.
66
+
43
67
  ## Rights declarations
44
68
 
45
69
  A **carrier** is an attribute of the object, or a two-step path
46
70
  `["<ref attribute>", "<attribute of its target>"]`; every step stays inside
47
- the tenant (`rights.carrier-cross-tenant`).
71
+ the tenant (`rights.carrier-cross-tenant`), and the first step points to an
72
+ object of a kind, not to an adopted `CustomTable`
73
+ (`rights.carrier-path-adopted`: the platform keeps a copy of the path's value
74
+ with a trigger on the target table, see "Carrier copies").
48
75
 
49
76
  - **`customActions`** — actions beyond the standard ones of the kind; each
50
77
  gets an id, `requires` names standard action words or other custom actions
@@ -52,9 +79,15 @@ the tenant (`rights.carrier-cross-tenant`).
52
79
  object's attributes, tabular sections and custom actions.
53
80
  `{ "name": "<action>", "requires": ["update"], "effects": { "header": ["<attribute>"] } }`
54
81
  Effects only on a kind with a writing standard action (not an accumulation
55
- register or a recorder-subordinate information register), and
56
- `tabularSections: true` only on a kind with tabular sections
57
- (`rights.custom-action-effects`).
82
+ register or a recorder-subordinate information register),
83
+ `tabularSections: true` only on a kind with tabular sections, and never a
84
+ transition column (`posted`, the deletion mark) or an immutable column in
85
+ `header` (`rights.custom-action-effects`, reasons `transitionColumn` and
86
+ `immutableColumn`). On a catalog an immutable column is any column the
87
+ command role cannot update (the `ref` key, `createdBy`, `updatedBy`,
88
+ `createdAt`, `updatedAt`, `version`, `predefinedName`, the platform
89
+ attributes of the users catalog); on other kinds it is the `ref` key,
90
+ `createdBy` and `updatedBy`.
58
91
  - **`ownership`** — carriers whose `Ref` names the owner of a row (a member
59
92
  or a user). `"ownership": ["<attribute>", ["<ref attribute>", "<attribute>"]]`
60
93
  The target is the users catalog, the membership catalog of the object's own
@@ -69,25 +102,43 @@ the tenant (`rights.carrier-cross-tenant`).
69
102
  - **`access`** — the project access dimensions that narrow the rows, each with
70
103
  its carrier to the dimension's value catalog.
71
104
  `"access": [{ "attribute": "<attribute>", "dimension": "<dimension>" }]` or
72
- `{ "ref": ["<ref attribute>", "<attribute>"], "dimension": "<dimension>" }`
105
+ `{ "ref": ["<ref attribute>", "<attribute>"], "dimension": "<dimension>" }`.
106
+ A register maps only a dimension of its own (`"attribute"`), never a
107
+ resource, an attribute or a path (`rights.register-access-dimension`): its
108
+ movements and totals are read by the same dimensions.
73
109
  - **`accessDimensions`** (project) — a value catalog plus where the current
74
110
  user's values come from: a relation object or a verbatim SQL function.
75
111
  `{ "name": "<dimension>", "target": <catalog ref>, "values": { "relation": { "object": <ref>, "subject": "<field>", "value": "<field>" } } }`
76
112
  or `"values": { "function": { "name": "<function>" } }`.
113
+ A read policy is named after the dimension, so a name that is `any` or
114
+ `own`, or starts with `own_` or `in_` (in snake case), is
115
+ `rights.dimension-name-reserved`.
77
116
  The function is verbatim SQL of a closed form: no arguments,
78
117
  `RETURNS SETOF uuid LANGUAGE sql STABLE SECURITY DEFINER SET search_path = ''`
79
- with an `AS $$ … $$` body,
118
+ plus the pinned session settings of a head (the exact `SET` options are in
119
+ the hint of `sql.head-settings`; without them that error, the same for a
120
+ verbatim scope set function) with an `AS $$ … $$` body,
80
121
  every name schema-qualified (also in the views it reads and the `sql`
81
122
  functions it calls; a `plpgsql` function in that chain is refused), and no
82
123
  `simetra.*` object except `simetra.current_user_id()`
83
124
  (`rights.dimension-function-*`).
125
+ With system rights catalogs, every relation that this function or a
126
+ verbatim scope set function reads must be a table of a kind, an adopted
127
+ table (`CustomTable`) or a model view over them. Anything else fails with
128
+ `rights.snapshot-source-unknown`, which names the relation and the function
129
+ that reads it: the platform watches only those tables for the actor
130
+ snapshot ("Rights inside a transaction" below). Read the data from such a
131
+ table instead, or remove the read.
84
132
  - **`membershipSources`** (project) — an adopted table that holds the
85
133
  membership of a scope kind instead of a membership catalog.
86
- `{ "name": "<source>", "scopeKind": "<scope kind>", "table": <CustomTable ref>, "columns": { "scope": "<column>", "user": "<column>" } }`
134
+ `{ "name": "<source>", "scopeKind": "<scope kind>", "table": <CustomTable ref>, "columns": { "scope": "<column>", "user": "<column>", "active": "<column>" }, "where": [<condition>] }`
135
+ (`active` and `where` are optional). See "Adopted membership and assignment sources".
87
136
  - **`assignmentSources`** (project) — an adopted table that holds role
88
137
  assignments of one level: `"global"`, `{ "scopeKind": "<scope kind>" }` or
89
138
  `{ "container": <ref> }`.
90
- `{ "name": "<source>", "assignedOn": "global", "table": <CustomTable ref>, "columns": { "member": "<column>", "role": "<column>" } }`
139
+ `{ "name": "<source>", "assignedOn": "global", "table": <CustomTable ref>, "columns": { "member": "<column>", "role": "<column>" }, "where": [<condition>] }`
140
+ (`columns` also takes `scope`, `container` and `active`). See "Adopted
141
+ membership and assignment sources".
91
142
 
92
143
  Dimensions and sources are project elements: add them to the project root
93
144
  (`"target": { "kind": "Project" }`) and rename or delete them by
@@ -154,3 +205,645 @@ The compiler reports these as `rights.*` (for example `rights.grant-level`,
154
205
  the compiler's rule catalog. Changing a role's level is an
155
206
  `identity.assigned-once-changed` error; renaming its scope kind or container
156
207
  is not.
208
+
209
+ ## Adopted membership and assignment sources
210
+
211
+ A membership source and an assignment source make the rows of an adopted
212
+ table give rights: the platform reads them in its rights functions, the same
213
+ way as a membership catalog and the system rights catalogs. A role takes its
214
+ key in such a table through `sourceKeys`.
215
+
216
+ - **Member.** The member of a membership source is the table key, so the
217
+ table needs a primary key of one uuid column
218
+ (`rights.source-member-key`). The system rights catalogs of the scope kind
219
+ refer to the member by a composite foreign key within the scope, so the
220
+ table metadata also needs `UNIQUE (<scope column>, <key>)` in `uniques`
221
+ (`rights.source-member-unique`). The `scope`, `user`, `member` and
222
+ `container` columns are uuid, `active` is boolean
223
+ (`rights.source-column-type`). A table with
224
+ `rowLevelSecurity: forced` is refused (`rights.source-forced-rls`).
225
+ - **Without a users catalog.** The user is the `sub` claim of the session read
226
+ as a uuid; the source's user column holds that uuid.
227
+ - **Rows.** `where` is a conjunction of conditions on columns of the table,
228
+ `{ "column": "<column>", "equals": <string | boolean | integer> }` or
229
+ `{ "column": "<column>", "isNull": true | false }`; rows that fail it are
230
+ not part of the source. Use it when one table holds several kinds of rows.
231
+ The plan does not report rows cut off by `where` as unknown role keys.
232
+ - **Scope of an assignment row** (`columns.scope`, scope level only): a column
233
+ whose value must equal the scope of the member; `null` takes the scope from
234
+ the member; omitted means the `scopeColumn` of the table. Omitted on a
235
+ table without `scopeColumn` is `rights.source-scope-column`. The field on
236
+ another level is the same error.
237
+ - **Role through a reference.** `columns.role` is either a column holding the
238
+ role key or `{ "column": "<column>", "references": <CustomTable ref>, "key": "<column>", "where": [<condition>] }`:
239
+ the column is a uuid reference to an adopted role table, `key` is the role
240
+ key there, and the role `where` keeps only the roles of the source (custom
241
+ roles with the same key do not turn a system role on). The role table needs
242
+ a single-column uuid primary key (`rights.source-role-key`, reason
243
+ `primaryKey`). Without a role `where` the `key` column must be unique on
244
+ its own: a non-deferrable unique constraint or a unique index without
245
+ predicate, operator class or collation; otherwise
246
+ `rights.source-role-key`, reason `ambiguous`.
247
+ - **Two sources over one table** (for example global and per-scope
248
+ assignments in one table) need `where` conditions that provably exclude
249
+ each other on one column; add one discriminator column (for example
250
+ `scope_type`) and give each source a different literal, or a literal
251
+ against `isNull`. Otherwise `rights.source-where`, reason `shared`.
252
+ `rights.source-where` also reports a condition on a column that is not
253
+ text, uuid, boolean or integer, and an `equals` literal of the wrong type
254
+ (`isNull` is allowed on any column).
255
+ - **Verbatim set function.** A scope kind with its own `setFunction` (SQL you
256
+ write) must apply the same `where` and `active` conditions of its
257
+ membership source, or the tenant boundary will differ from the platform's
258
+ own "my scopes" function.
259
+ - **Grants.** The application role that applies the metadata owns the rights
260
+ functions (`SECURITY DEFINER`), so it needs `USAGE` on the schema of
261
+ every source and role table, `SELECT` on every such table, and, when a table has row level security enabled,
262
+ must own it or have `BYPASSRLS`; `plan` refuses to write a plan otherwise
263
+ (`plan.rights-source-access`). Rows with a role key no role declares in
264
+ `sourceKeys` grant nothing; `plan` reports them
265
+ (`plan.rights-source-unknown-keys`).
266
+ - **The platform only reads sources.** Whatever writes a source table
267
+ belongs to the application; the rights safeguards (last-holder guards,
268
+ versions, the rights journal) do not apply to those writes, which the
269
+ compiler notes as `rights.adopted-source-writes`.
270
+ - **Commands do not write sources.** The platform puts no actor snapshot
271
+ trigger on an adopted source, its role table or another `CustomTable` that
272
+ the rights facts read. So application SQL must not let the command role
273
+ (`simetra_command`) or `PUBLIC` write such a table, or the compiler fails
274
+ with `rights.snapshot-exempt-writer`. The message names what opens the
275
+ write; fix it as follows:
276
+ - a write grant (also through `ALTER DEFAULT PRIVILEGES`) — remove it;
277
+ - a view with a write grant and without `security_invoker` — remove the
278
+ grant or create the view `WITH (security_invoker = true)`;
279
+ - a `SECURITY DEFINER` function or procedure that writes the table — add
280
+ `REVOKE EXECUTE ON FUNCTION <name>(<argument types>) FROM PUBLIC` after
281
+ it, grant it to no command role, or drop `SECURITY DEFINER`; default
282
+ privileges do not count as that revoke;
283
+ - a `SECURITY DEFINER` trigger function that writes the table — remove its
284
+ trigger or drop `SECURITY DEFINER`.
285
+ - **Deleting a member.** A member of an adopted membership referenced by
286
+ platform role assignments cannot be deleted until those assignments are
287
+ removed (foreign key violation `23503`).
288
+
289
+ ## System rights catalogs
290
+
291
+ The system rights catalogs are Catalogs with `"role": "rightsRoles"` (custom
292
+ roles; standard tabular section `delta`) or `"role": "roleAssignments"`. Their
293
+ level is the catalog's own scope. A custom action on one is
294
+ `rights.system-catalog-custom-action`.
295
+ Run `simetra roles` before the first `plan` on a new database.
296
+
297
+ To administer rights, grant `read` and `administerRights` explicitly on the
298
+ system catalog at extent `any`. Neither `grantAll` nor `withAction` selects
299
+ system catalogs; a role with `fullAccess` includes their administration at
300
+ its own level. A container role cannot administer a scope's rights catalogs.
301
+ A rights administrator role must also grant `read` on the membership catalog
302
+ of its level; `administerRights` gives no implicit read, so without it an
303
+ assignment cannot address a member.
304
+ Use `administerRights` as the command's root action. It has no natural DML
305
+ counterpart, so another command cannot write a rights catalog as a side effect.
306
+
307
+ Rights changes are checked at transaction end against the actor's rights
308
+ captured before its first command change. The effective rights added by a
309
+ custom role or assignment must be covered by that snapshot. This includes
310
+ rights enabled by removing a denial or satisfying an action's requirements.
311
+ Changing an assignment's member or container checks the full new grant.
312
+ A transaction can create a role and then add its restricting denials before
313
+ the final check. A custom role that an assignment still references cannot be
314
+ deleted: marking it for deletion fails with `command.forbidden`, detail
315
+ `role-in-use`, and a physical delete fails with a foreign key violation
316
+ (`23503`). Other failures use `command.forbidden` with detail `escalation`.
317
+
318
+ Removing the last effective direct holder of a `fullAccess` archetype fails
319
+ with detail `last-full-access`. Custom roles based on that archetype do not
320
+ count as holders. Transfer the assignment within one transaction. Deleting
321
+ the scope root in that transaction removes the check when the assignment's
322
+ scope is bound to that root by a foreign key. Concurrent changes may need a
323
+ transaction retry after a serialization failure or deadlock.
324
+
325
+ An occupied membership row cannot be reassigned to another user. Only the
326
+ invited user can fill an empty user reference, and only if that user does not
327
+ already belong to the scope.
328
+ A row cannot be re-inserted under an id that a rights assignment still
329
+ references; for a user, a membership row also blocks it. Other application
330
+ references do not block re-insertion. Commands do not change the users
331
+ catalog's `invalid` or `userKind`; provider provisioning and invalidation
332
+ remain platform operations.
333
+
334
+ Direct writes without command context fail with detail `rights-context`.
335
+ Platform tools use a maintenance mode that bypasses only the actor's grant
336
+ subset check, preserving the in-use-role and last-holder checks. Application
337
+ SQL must not enable it, and neither provider service logins nor the
338
+ platform's runtime login `simetra_runtime` can enable it.
339
+ `TRUNCATE` is refused for guarded rights, membership, user and dimension
340
+ relation tables, including in maintenance mode.
341
+
342
+ For a rights cache key, combine `simetra.rights_projection_version()` with
343
+ `simetra.rights_versions()`: the former identifies the compiled rights rules,
344
+ the latter tracks changes in the caller's scopes. Writes to adopted tables
345
+ do not bump the rights version, because the platform puts no triggers on
346
+ them: this covers adopted membership and assignment sources and a dimension
347
+ relation that is an adopted `CustomTable`. The platform rights journal
348
+ records changes to system rights catalogs in the same transaction, including
349
+ the actor (null for maintenance), reason, and before/after images.
350
+
351
+ When applying metadata changes, inspect the plan's `plan.rights-orphans`
352
+ warnings about orphaned role, assignment and delta references; those rows
353
+ grant no matching rights. Clean them with commands ("Rights administration
354
+ commands" below). The plan refuses a code change that would remove
355
+ the last effective `fullAccess` holder with `plan.rights-full-access-lost`. Restore the holder or transfer administration before
356
+ applying that change.
357
+
358
+ ## Rights administration commands
359
+
360
+ Administer rights with the ordinary operations of the system rights
361
+ catalogs through `runtime.run` (`simetra/server`). Every operation on them
362
+ runs under `administerRights`:
363
+
364
+ - custom role: `create`, `update` with `expectedVersion` (the `delta`
365
+ tabular section is replaced whole: name every existing line in the array
366
+ or in `deleteIds`), `markDeletion` on the roles catalog;
367
+ - assignment: `create`, and `delete` with `expectedVersion`, on the role
368
+ assignments catalog.
369
+
370
+ The runtime adds no rights checks of its own. The database judges the
371
+ transaction at `COMMIT`, and the runtime maps its refusals:
372
+ `command.forbidden` with `escalation`, `role-in-use` or `last-full-access`,
373
+ and `command.conflict` for a stale version. Assigning a role to yourself
374
+ fails at `COMMIT` with `escalation`.
375
+
376
+ **Rights inside a transaction.** A command uses the rights its actor had
377
+ when its transaction started. Before the first change of a table that feeds
378
+ the actor's rights (role assignments, custom roles, membership, users,
379
+ dimension relations, tables read by verbatim dimension and scope set
380
+ functions), the database takes a snapshot of those rights. The command core,
381
+ row level security and the rights functions then read the snapshot until the
382
+ transaction ends. So a right granted inside a command's transaction takes
383
+ effect from the next transaction: a phase or hook that uses a role the batch
384
+ has just assigned to its own actor fails with `command.forbidden`, reason
385
+ `no-right`, and a read returns no rows. This also holds for host code that
386
+ writes with the runtime login directly. Phases and hooks may run in any
387
+ order: a membership `onWrite` that assigns a role with `ctx.run` does not
388
+ limit the next phases of the batch. A read only transaction does not take a
389
+ snapshot.
390
+
391
+ **Transfer `fullAccess`** in one batch: assign the archetype to the new
392
+ holder and delete your own assignment, in either order. The last-holder check
393
+ runs at `COMMIT`, and the command core reads your rights at the start of the
394
+ transaction.
395
+
396
+ **Clean orphans.** `simetra plan --format json` returns `rightsOrphans` with
397
+ `roles`, `assignments` and `deltas`, also when the status is `unchanged`.
398
+ Each entry has the catalog `object`, the row `id`, the expected `version`
399
+ and, on a scope level, the `scope`. A delta row and an assignment of an
400
+ orphan role also have the `role` id; the version of a delta row is its
401
+ role's version. The list is complete; the warning text shows only the first
402
+ rows. Send one batch in this order:
403
+
404
+ 1. `delete` every entry of `assignments`;
405
+ 2. `markDeletion` every entry of `roles`;
406
+ 3. `update` every role named in `deltas`, with its delta without those rows.
407
+
408
+ `update` replaces the whole delta, so send the rows that stay. The runtime
409
+ does not read tabular sections yet: read them with your own query. A stale
410
+ version fails with `command.conflict`; run `plan` again and rebuild the
411
+ batch.
412
+
413
+ ## Tenant creation
414
+
415
+ A tenant is a row of a scope root: the catalog its scope kind is rooted on.
416
+ The scope kind, not the creator's role, picks the model:
417
+
418
+ - **Creator model**: the scope kind has a scope role with `rootCreator: true`.
419
+ The `create` of the root also inserts the creator's member row and assigns
420
+ the creator that role, in the same transaction. The creator holds the role
421
+ in exactly the new scope already inside this transaction; `COMMIT` judges
422
+ everything else as usual.
423
+ - **Operator model**: no `rootCreator` role. The root is created without a
424
+ member, and the first owner comes from `tenantFullAccess` of the rights
425
+ maintenance tool.
426
+
427
+ **The right to create a root** comes only from an explicit `create` grant on
428
+ the root in a `global` or `everyUser` role. `grantAll`, `withAction` and
429
+ `fullAccess` do not give it, and a scope or container role cannot grant it
430
+ (`rights.grant-level`). Self-service is `everyUser` with `create@own`: the
431
+ root needs `trackAuthor` and `"createdBy"` in its `ownership`
432
+ (`rights.root-create-author`), because the new row has no other owner. An
433
+ operator is a `global` role with `create@any`. Creating a root needs no
434
+ `read` on it. A global `fullAccess` holder can still assign a global role
435
+ that grants it.
436
+
437
+ **A scope kind with `rootCreator`** needs (each is a compiler error):
438
+
439
+ - a membership catalog with `membership`, not an adopted membership source
440
+ (`rights.root-creator-membership`);
441
+ - `setFunction: "membership"` (`rights.root-creator-set-function`);
442
+ - the system role assignments catalog of its level
443
+ (`rights.root-creator-assignments`), and no required attribute without a
444
+ `defaultValue` on that catalog (`rights.root-creator-assignment-required`):
445
+ the creator's assignment is inserted with the key, scope, member and role
446
+ only;
447
+ - `rootCreator` on a scope role (`rights.root-creator-level`), on one role of
448
+ the scope kind (`rights.root-creator-duplicate`);
449
+ - no SQL subscription (`beforeWrite`, `onWrite`) that fires on `INSERT` of
450
+ its membership catalog or role assignments catalog
451
+ (`rights.root-creator-subscription`): the platform writes the creator's
452
+ rows as the table owner. Put that logic in a command hook of the catalog.
453
+
454
+ A `rootCreator` role without `fullAccess` and without `administerRights` on
455
+ the rights catalogs of its level gets the warning
456
+ `rights.root-creator-no-admin`: the creator could not assign roles in the new
457
+ tenant. A `rootCreator` role on a scope kind whose root no command creates
458
+ (the root is `Users`: provisioning creates its rows) gets the warning
459
+ `rights.root-creator-unreachable`: no tenant creation assigns the role, so
460
+ assign the first role with the operator tool.
461
+
462
+ **The operation** goes through `runtime.run` like any other:
463
+
464
+ ```jsonc
465
+ {
466
+ "action": "create",
467
+ "object": { "kind": "Catalog", "name": "<root>" },
468
+ "values": { … },
469
+ "creatorMember": { … }
470
+ }
471
+ ```
472
+
473
+ - Do not pass `id`: the runtime generates the root id (and the member row id)
474
+ once per `runtime.run`, and a retry reuses them. A `ctx.run` from a hook
475
+ generates new ids on each attempt, because the hook runs again. `id` or `tabularSections` on a root
476
+ `create` fails with `command.invalid`; fill tabular sections with a later
477
+ `update`.
478
+ - `creatorMember` holds attributes of the creator's member row that a command
479
+ may insert; the platform sets the key, the scope and the user. It defaults
480
+ to `{}`. It is allowed only on the root of a kind with `rootCreator`. A
481
+ missing required attribute, or a reference to a row that is missing or that
482
+ the creator cannot read, fails with `command.invalid` and the path
483
+ `creatorMember.<attribute>`.
484
+ - Hooks run in this order: `beforeWrite` of the root, `beforeWrite` of the
485
+ membership catalog (draft `{ values: creatorMember }`, `ctx.id` is the
486
+ member row id, `ctx.isNew`), `onWrite` of the root, `onWrite` of the
487
+ membership catalog. A membership `onWrite` may assign more roles with
488
+ `ctx.run`; `COMMIT` judges them as ordinary commands.
489
+ - `rows[0]` of the result is the root row. In the operator model the creator
490
+ cannot read the new root, so the row has only its key and version (`1`).
491
+ The member row goes only to the membership `onWrite`. If the
492
+ `rootCreator` role cannot read the membership catalog, that row also has
493
+ only its key and version (`1`).
494
+
495
+ The rights journal records the creator's assignment with the reason
496
+ `root-creator`. A later change of that assignment is an ordinary command.
497
+
498
+ ## Rights maintenance tool
499
+
500
+ `simetra rights-maintenance '<json>' [dir] --yes` writes one assignment
501
+ outside commands, in the database maintenance mode. It is a command line
502
+ tool only, not an MCP tool, and without `--yes` it does not connect. Connect
503
+ as the migrator that applied the plan (`SIMETRA_DATABASE_URL`): maintenance
504
+ mode works only for the login that owns the rights functions. The input has
505
+ one action:
506
+
507
+ - `{ "action": "firstGlobalAssignment", "user": "<uuid>", "role": "<role>" }`
508
+ — the first global assignment of a new database. Once any global
509
+ assignment exists, it fails with `maintenance.not-first`.
510
+ - `{ "action": "restoreGlobalFullAccess", "user": "<uuid>", "role": "<role>" }`
511
+ — a global `fullAccess` holder when no effective one is left. Omit `role`
512
+ when the project has exactly one assignable global `fullAccess` role.
513
+ - `{ "action": "tenantFullAccess", "scopeKind": "<scope kind>", "scope": "<uuid>", "user": "<uuid>", "role": "<role>", "member": { … } }`
514
+ — the `fullAccess` owner of one scope without an effective holder. Use it
515
+ for the first owner when an operator creates tenants (no `rootCreator`
516
+ role), and for a tenant whose only holder became invalid. If the user is
517
+ already a member, the member gets the role; do not pass `member` then.
518
+ Otherwise the tool inserts a member row with the `member` values,
519
+ attributes of your membership catalog that a command may insert. The tool
520
+ sets the key, the scope and the user itself, and checks the references in
521
+ `member` like a command does: the target must exist in the same scope.
522
+
523
+ The role must be `assignable`. For `tenantFullAccess` it is a `fullAccess`
524
+ role of exactly that scope kind. The tool refuses without writing and exits
525
+ with a non-zero code when:
526
+
527
+ - another `apply` or maintenance run holds the lock (`maintenance.busy`);
528
+ - the applied model is not the compiled one (`maintenance.model-mismatch`):
529
+ run `plan` and `apply` first;
530
+ - the user, the scope or the role is unknown, or the role does not fit the
531
+ action;
532
+ - the level already has an effective holder (`maintenance.holder-exists`);
533
+ - the user would not be an effective holder (`maintenance.not-effective`);
534
+ - a required member attribute has no value (`maintenance.member-required`);
535
+ - a reference in `member` (also an array `Ref` or a polymorphic pair) points
536
+ to a missing row or a row of another scope (`maintenance.invalid-member`,
537
+ with the `path` of the attribute).
538
+
539
+ `maintenance.refused` means that the database refused the write. Most often
540
+ the login is not the migrator. `maintenance.outcome-unknown` means that the
541
+ connection dropped after the write; run the tool again to see the state. The
542
+ rights journal records the write with no actor and the reason
543
+ `maintenance`. The tool is verified against the local Supabase stack,
544
+ directly and through its pooler; the hosted pooler is not verified yet.
545
+
546
+ ## Rights analysis
547
+
548
+ The database answers rights questions with the same rights functions the
549
+ policies use. `simetra.rights_mine()` returns the caller's own rights; any
550
+ user may call it. The other analysis functions disclose someone else's
551
+ rights, so they return rows only when the caller holds `administerRights` on
552
+ the role assignments catalog of the requested level (scope kind and scope,
553
+ or the global level with a zero uuid for both). Without that right they
554
+ return nothing, never an error:
555
+
556
+ - `simetra.rights_member(scope_kind, scope, member)` — the rights of a member
557
+ of that scope, with their origin (`via` is `archetype` or `delta`). The
558
+ member must belong to the scope; the global form takes a user id.
559
+ - `simetra.rights_who(action, object, scope_kind, scope)` — members of that
560
+ scope whose roles grant the action on the object. It answers per scope or
561
+ for the global level; it does not merge tenants.
562
+ - `simetra.rights_explain(object, row, user)` — one row per read policy of
563
+ the object with `has_right` and `carrier_match`. A row is visible to the
564
+ user when every `restrictive` row matches and at least one `permissive` row
565
+ has both flags. It explains only rows the caller can read, and only for a
566
+ user who belongs to the row's scope; an unknown row returns nothing. A
567
+ `publicRead` row is the exception: any user gets its single public-read
568
+ row, matching what row-level security shows.
569
+ `carrier_match` is null when the carrier set comes from a verbatim
570
+ function of yours and the user is not the caller. Register and constant
571
+ rows are not explained.
572
+ - `simetra.rights_journal_of(scope_kind, scope, limit)` — the rights journal
573
+ of that scope, newest first, at most 1000 rows.
574
+
575
+ The service role cannot execute these functions. They read claims, so they
576
+ return nothing in maintenance mode or without a session user. Build a client
577
+ rights snapshot from these functions and cache it by the rights cache key
578
+ above.
579
+
580
+ ## Supported limits
581
+
582
+ Measured on one developer machine (PostgreSQL 17.6, local Supabase stack;
583
+ reads and rights commands 2026-11-05, carrier rows 2026-10-31); treat them as
584
+ orders of magnitude, not guarantees.
585
+
586
+ | Scenario | Volume | Time |
587
+ | --- | --- | --- |
588
+ | Read a scoped table, dimension values per user | 20,000 values, 120,000 rows | list 0.57 s, point 18 ms |
589
+ | Read a scoped table, `fullAccess` holder in N scopes | 100 / 500 / 2,000 scopes, 100,000 rows | list 0.05 / 0.2 / 1.2 s |
590
+ | Owner carrier change, tabular section fan-out | 100,000 / 300,000 section rows | 2.5 / 8.0 s |
591
+ | Carrier backfill plan step | 1,000,000 section rows | 36 s |
592
+ | One rights command (assignment) in its own transaction | 11,000 assignments | 28 ms |
593
+ | Rights commands in one transaction | 1,000 commands | 7.1 s |
594
+ | Create a tenant with its creator, actor in N scopes | 1 / 2,000 scopes | core 29 / 237 ms, `COMMIT` 30 ms / 5.8 s |
595
+
596
+ - A `fullAccess` holder costs about 0.6 ms per scope on a list read: up to
597
+ about 1,500 scopes a read stays under a second. The scope count is data, so
598
+ no compiler warning covers it.
599
+ - Split batch rights changes into transactions: one command takes about
600
+ 30 ms, while a thousand commands in one transaction take about 7 s.
601
+
602
+ ## Who reads what
603
+
604
+ Rows are read through rights, not by default. In a project with at least one
605
+ role and a session user (a users catalog, or a membership source on a provider
606
+ whose user id is the `sub` claim):
607
+
608
+ - A table of a kind is read only through a role's `read` right on its object,
609
+ at the extent of the grant (`any`, `own`, a dimension, in a container); its
610
+ tabular sections and a register's movements and totals follow the object.
611
+ `publicRead` as a string opens every row instead and needs no right. The
612
+ conditional form `{ "role": "anon" | "authenticated", "published": true }`
613
+ opens only rows that are published and not marked for deletion (the header
614
+ and its tabular sections): it needs a catalog with commands, rights
615
+ functions and a rights contract with `read`, keeps the read policies and the
616
+ tenant boundary for everyone else, and adds the actions `publish` and
617
+ `unpublish`; marking a row for deletion unpublishes it. Example:
618
+ `"publicRead": { "role": "anon", "published": true }`. Any
619
+ `publicRead` is an error (`rights.public-read-forbidden`) on the users catalog, a membership catalog
620
+ and the rights system catalogs: for public profiles declare a separate
621
+ catalog with the public fields and a reference to the users catalog.
622
+ - A scoped object is read only inside the reader's scopes, and only through a
623
+ role assigned there: membership in a tenant without a role reads nothing.
624
+ - The users catalog shows only yourself and the users of members of your
625
+ scopes (when the project has a membership catalog or a membership source),
626
+ whatever the role grants
627
+ on it: a scope-level `read` on the users catalog reads only those.
628
+
629
+ Without any role (or without a session user: no users catalog and no
630
+ membership source on such a provider) no right opens a row: only
631
+ `publicRead` objects are readable. `rights.scope-kind-unread` (a warning on
632
+ the scope kind in `project.meta.json`) says that no role reads any object of
633
+ that scope kind, so nobody will see their rows: grant `read` to a role or
634
+ declare one with `fullAccess`.
635
+
636
+ ## Who writes what
637
+
638
+ Kind tables are written **only by commands**: the write policies grant the
639
+ command role and nobody else.
640
+
641
+ - The **root row** of a command is checked against the right of the command's
642
+ **own action** — the standard action (`create`, `update`, `delete`, `post`,
643
+ …) or the custom action itself, not the actions it `requires` — and only
644
+ through that action's DML (`create` inserts, `delete` deletes, the rest
645
+ update).
646
+ - **Every other row** is checked against the right of the **natural action of
647
+ its DML**, a fact of the kind (`create` for an insert, `update` for an
648
+ update, `delete` for a delete; `write` on an information register; `update`
649
+ for both on a constant); a tabular-section row is checked against `update`
650
+ of its owner. A DML with no natural action on that
651
+ table is refused.
652
+ - An action without `tabularSections` does not write tabular sections. The
653
+ transition columns (`posted`, the deletion mark) change only through `post`,
654
+ `unpost` and `markDeletion`; `post` only sets `posted` and `unpost` only
655
+ clears it, while `markDeletion` may set or clear the mark. A custom action is
656
+ not a transition action and cannot name a transition column in its header
657
+ effects (`rights.custom-action-effects`, reason `transitionColumn`).
658
+ - The ref key of a catalog, document or tabular-section row never changes —
659
+ not in a command, not in application SQL, not in maintenance mode, and also
660
+ in a project without rights (`42501` `command.forbidden`, detail `effect`,
661
+ the key column). The scope column of a row cannot be changed by any command,
662
+ and a tabular-section row cannot be moved to another owner;
663
+ a custom action that names the key in its header effects is refused
664
+ (`rights.custom-action-effects`, reason `immutableColumn`).
665
+ - A `beforeWrite` handler that, under a transition, changes another column makes
666
+ the command fail. Put a computation done at posting into the command hook or
667
+ into the effects of a custom action.
668
+ - Application SQL never writes a table of a kind and never changes the
669
+ platform's session settings: `SKILL.md`, section "The SQL module: closed
670
+ forms only", names the reference with those rules.
671
+
672
+ ## Generated privileges
673
+
674
+ Privileges on what the platform owns are generated: `EXECUTE` on a declared
675
+ scope set function and on a subscription handler, and every grant on a kind's
676
+ tables. In debt SQL (a `CustomTable` or `PgEnum` module, the shared
677
+ `metadata/sql/`) a verbatim `GRANT`/`REVOKE` on them fails with
678
+ `sql.generated-grant` (a kind's own module rejects any). `simetra fix` removes
679
+ the statement (and its file, if left empty) only when every target belongs to
680
+ the platform; one that also names other objects you split by hand. A grant
681
+ on another overload of the same name is not affected.
682
+
683
+ ## Platform roles
684
+
685
+ `simetra roles` creates the cluster roles the platform needs. It creates
686
+ `simetra_command` (`NOLOGIN NOINHERIT`, on the target and the shadow server)
687
+ and, when a project file is present, the runtime login role `simetra_runtime`
688
+ on the target only (`LOGIN NOINHERIT`, a member of `simetra_command` and, for
689
+ `supabase`, of `authenticated` and `anon`, each `WITH INHERIT FALSE, SET TRUE`). It reads
690
+ `database.provider` from the project file; without a project file it skips the
691
+ login role, and the output says why. The operator sets the login role's
692
+ password; the platform keeps no secrets.
693
+
694
+ The login role needs `ADMIN OPTION` on each of its parent roles in the role
695
+ that runs `roles`. Without it `roles` still creates the grant roles, but
696
+ refuses the login role with `roles.admin-option-missing` and does not create
697
+ it. An existing role is only checked, with one change: after upgrading
698
+ Simetra, run `roles` again on an existing database; it adds a missing
699
+ membership of the login role in a parent of its profile, or refuses with
700
+ `roles.membership-grant-denied`, which names the `GRANT` to run.
701
+
702
+ ### The `postgres` provider
703
+
704
+ On `database.provider: "postgres"` the same command prepares the cluster and
705
+ needs a superuser that logs in as itself. Give it through
706
+ `--database-url-env <VAR>` (a variable other than the owner's, so the
707
+ superuser DSN is not the one `plan` and `apply` use). It creates the roles of
708
+ the profile, the application database owned by `simetra_owner`,
709
+ `plpgsql_check` in that database, and the sealed template database
710
+ `simetra_template` that shadows and proof copies are built from. Running it
711
+ again converges the declared state and creates nothing.
712
+
713
+ The identity provider's own roles get their grants here too: the role of the
714
+ platform owner receives `USAGE` on the `better_auth` schema and `TRIGGER` and
715
+ `REFERENCES` on `better_auth."user"`, so the provision triggers and the foreign
716
+ keys of the model can sit on the account table. Before the identity provider's
717
+ migration has created that table, the table grants are skipped and the output
718
+ says so; run `roles` again after the migration. The spec of the
719
+ profile has the role set and the reasons:
720
+ `docs/superpowers/specs/2026-11-08-postgres-profile-design.md` §3.
721
+
722
+ Refusals, all raised before anything is written unless the hint says
723
+ otherwise:
724
+
725
+ - `roles.superuser-required` — the role is not a superuser, or its current
726
+ role differs from the login role; connect as the superuser.
727
+ - `roles.unsafe-schema` — a schema in the database (`extensions`,
728
+ `better_auth`) has an owner or content a superuser session must not trust;
729
+ the hint lists what to fix by hand.
730
+ - `roles.unsafe-template` — `simetra_template` is owned by a non-superuser,
731
+ accepts connections, or is closed without being marked as a template; drop
732
+ it as a superuser and run `roles` again.
733
+ - `roles.database-owner` — the database belongs to another role than
734
+ `simetra_owner`; fix the owner by hand or use a database `roles` creates.
735
+ - `roles.database-locale` — the database or `simetra_template` has another
736
+ collation than ICU `en-US`; `roles` never drops a database: dump, drop and
737
+ restore it by hand around a new `roles` run (the template is only dropped).
738
+ - `roles.shared-cluster` — a Simetra login role has an explicit `CONNECT` on
739
+ other databases; one cluster serves one application.
740
+ - `plan.owner-not-bypassrls` — the role of `plan`, `apply` or `rehearse` has
741
+ neither `BYPASSRLS` nor superuser; run `ALTER ROLE <role> BYPASSRLS` as a
742
+ superuser.
743
+ - `plan.shadow-base-unsupported` — a separate shadow server is not supported
744
+ on `postgres`; drop `--shadow-url-env`.
745
+
746
+ - `plan.identity-table-missing` — the model needs provision triggers on the
747
+ account table of the identity provider and the connected role cannot place
748
+ them: reason `table` means the table does not exist yet (run the provider's
749
+ migration first), reason `privilege` means the role lacks `USAGE` on its
750
+ schema or `TRIGGER` on the table (run `roles` again as the superuser).
751
+ - `plan.identity-trigger-locked` — on `postgres` only the owner of the account
752
+ table can remove or enable a provision trigger on it, and `plan` does not run
753
+ as that owner: reason `removed` means the plan drops a trigger, reason
754
+ `disabled` means it would enable a trigger that is disabled. Do the change by
755
+ hand as the table owner.
756
+
757
+ `plan.platform-role-shape` with the violation `request-role:<role>` means an
758
+ API request role (such as `authenticated`) and a platform role are members of
759
+ each other in some form, even `ADMIN` alone; revoke that membership.
760
+
761
+ ### Runtime login and anonymous sessions
762
+
763
+ The runtime refuses to start with `command.privileged-login` when its login
764
+ role reaches a power it must not hold, itself or through a membership; the
765
+ `reason` names the first fact found: `owner`, `superuser`, `bypassrls`,
766
+ `createrole`, `server-files`, `read-all-data`, `write-all-data`,
767
+ `database-owner` (the login owns the current database), `provider-login` or
768
+ `service`. Use the
769
+ dedicated runtime login role `simetra_runtime`, not an owner, a superuser or a
770
+ provider login.
771
+
772
+ An anonymous session is a guest and reads as one. On a provider whose
773
+ identity data marks anonymous sessions with a claim, a session that has a
774
+ subject but no anonymous claim is refused with `command.unauthenticated`
775
+ before any database work: the claim must be present, `true` or `false`.
776
+
777
+ ## Reading past row-level security
778
+
779
+ A `SECURITY DEFINER` function runs as its owner, the applying role, which
780
+ bypasses row-level security (`FORCE ROW LEVEL SECURITY` does not stop it).
781
+ One that a role of the API (or `PUBLIC`) may `EXECUTE` fails `compile` with
782
+ `sql.definer-caller-unchecked` in any `.sql` file, SQL debt included, whatever
783
+ it reads, until it names the check of its caller. Two ways out: link it to a
784
+ scope kind as its set function (or to an access dimension as its values
785
+ function), or declare its signature with the named check. After `introspect`
786
+ from scratch, set functions come back unlinked and fail this way until you
787
+ link them.
788
+
789
+ `sql.definer-reads-rls` (a warning) marks a view that reads a table under
790
+ row-level security as its owner, so the caller's policies do not apply, while
791
+ a role of the API (or `PUBLIC`) can read it:
792
+
793
+ - a view without `security_invoker` that someone may `SELECT`;
794
+ - a materialized view, which stores the rows its owner read at `REFRESH`.
795
+
796
+ The diagnostic lists the tables it found. Convert in this order of
797
+ preference:
798
+
799
+ 1. Read through a right and a policy: let the caller read the kind's table
800
+ itself, so the platform's policies decide, and make the unit
801
+ `SECURITY INVOKER` (a view: `WITH (security_invoker = true)` in
802
+ `CREATE VIEW`; a separate `ALTER VIEW` is not accepted in `.sql` files).
803
+ 2. Write the operation as a command of the object or a TypeScript hook; a
804
+ view may filter the rows with the rights functions.
805
+ 3. If no API caller needs it, `REVOKE EXECUTE` (function) or `REVOKE SELECT`
806
+ (view, materialized view) from `PUBLIC` and from each API role. A
807
+ materialized view that serves callers is replaced by a view with
808
+ `security_invoker`.
809
+
810
+ ## Carrier copies
811
+
812
+ A tabular section cannot be read by the carriers of its owner without a
813
+ copy, and neither can an object whose carrier is a path. So the platform
814
+ keeps copies: every tabular section of an object with carriers gets a column
815
+ per carrier (named like the owner's column), and a path carrier gets a column
816
+ in the object row. The copies are written only by the platform:
817
+
818
+ - A value the client writes into a copy is replaced by the value of the
819
+ source row; a request that changes only copies is a resave.
820
+ - When the source changes, the copies of dependent rows (and of their tabular
821
+ sections) follow. This propagation is not a change of the row: it does not
822
+ bump `version` or `updatedAt` and fires no subscription and no platform
823
+ `BEFORE UPDATE` guard.
824
+ - The names are taken: an attribute under a copy's name is
825
+ `rights.carrier-column-taken`; rename the attribute.
826
+ - A `beforeWrite` handler on such a table never assigns a copy or the column
827
+ of the first path step (`subscription.handler-assigns-carrier`: assign them
828
+ in the command hook) and never reads a copy as `NEW.<copy>`
829
+ (`subscription.handler-reads-carrier`: on `INSERT` it may still hold the
830
+ client's value); look the carrier up in the row the first step points to.
831
+ - On a table with copies the row mechanics are two triggers,
832
+ `<table>_simetra_touch` on `INSERT` and `<table>_simetra_touch_update` on an
833
+ `UPDATE` that changes the content, and a write subscription without
834
+ `whenChanged` gets the pair `<physicalName>` (`UPDATE`, content changed)
835
+ and `<physicalName>_insert` (`INSERT`), so propagation triggers neither.
836
+ - A new copy on a table that already has rows is filled by a plan step of
837
+ origin `carriers` (class `dataStep`, no `--allow` needed) that runs right
838
+ after the engine steps, in the same transaction: each row takes the value
839
+ from the row its composite foreign key points to, and a row without a link
840
+ gets `NULL`. The step holds `SHARE ROW EXCLUSIVE` on the table and on its
841
+ source until the apply ends. Triggers stay on, and a copy-only change does
842
+ not bump `version` or fire subscriptions.
843
+ - When a copy takes the place of a column that was not a copy (a removed
844
+ attribute that still holds data, or an adopted column the promotion
845
+ mapping left out), the step overwrites that data: it is class
846
+ `destructive` and needs `--allow <step id>` like any other step that loses
847
+ data. A copy column the plan itself creates is always filled, even if the
848
+ last applied snapshot says the copy already exists (for example, an
849
+ administrator dropped it by hand and the drift was accepted).