@simetrajs/designer 0.0.0-stage → 0.1.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.
@@ -0,0 +1,491 @@
1
+ ---
2
+ name: simetra-metadata
3
+ description: Use when you need to create, change, validate or explain Simetra metadata (a `metadata/` directory) with the `simetra` tools — compile it, read a compiler diagnostic (`file:line:col`, `--format json`, `--locale`), explain the compiled picture of an object, fix missing ids and `physicalName`, create, add, rename or delete elements, or promote an adopted table, through checked operations, compare a database with the metadata (`diff`), plan and apply the metadata to a database (`plan`, `apply`), or expose the tools to an agent with `simetra mcp` (`--read-only` to refuse writes). Also use when a pre-commit or CI metadata check fails. For bringing an existing database under metadata (`introspect`), use `simetra-adoption`.
4
+ ---
5
+
6
+ # Simetra metadata — compile, explain, fix, create, add, rename, delete, promote, introspect, diff, plan, apply
7
+
8
+ The tools are one catalog served by the command line and by the MCP server,
9
+ with the same tool names and the same input in both. Run the CLI
10
+ from the project root as `pnpm exec simetra …` (or `node_modules/.bin/simetra …`).
11
+ Every command defaults to `./metadata`.
12
+
13
+ This skill covers how to use the tools. What the metadata model means is
14
+ described by the schemas in `node_modules/simetra/schemas/` and by the
15
+ diagnostics themselves.
16
+
17
+ ## Which tool when
18
+
19
+ | Task | Tool | CLI | MCP call |
20
+ | --------------------------------------------------------------------------------- | ------------ | ---------------------------------------- | ------------------------------------------- |
21
+ | Is the metadata accepted by the compiler? | `compile` | `simetra compile [dirs...]` | `compile` with `{}` |
22
+ | What does the compiler derive for one object (tables, columns, keys, queries)? | `explain` | `simetra explain <Kind>.<Name> [dir]` | `explain` with `{kind, name}` |
23
+ | New elements miss `id` / `physicalName` / `kindLabel`, or files are not canonical | `fix` | `simetra fix [dir]` | `fix` with `{}` |
24
+ | New object | `create` | `simetra create '<json>' [dir]` | `create` with `{kind, name, data?}` |
25
+ | New element in a collection of an object or of the project root | `add` | `simetra add '<json>' [dir]` | `add` with `{target, collection, element}` |
26
+ | Rename an object or a nested element | `rename` | `simetra rename '<json>' [dir]` | `rename` with `{target, newName}` |
27
+ | Remove an object or a nested element | `delete` | `simetra delete '<json>' [dir] --yes` | `delete` with `{target, confirm}` |
28
+ | Turn an adopted `CustomTable` into a Catalog, Document or InformationRegister | `promote` | `simetra promote <json\|-> [dir]` | `promote` with `{target, into, columns, …}` |
29
+ | Read a live database into metadata | `introspect` | `simetra introspect [dir] --schemas a,b` | `introspect` with `{schemas?, project?}` |
30
+ | Does the database match the metadata? | `diff` | `simetra diff [dir] --tables a,b` | `diff` with `{tables?}` |
31
+ | Plan bringing the database to the metadata (writes `plans/…plan.json`) | `plan` | `simetra plan [dir]` | `plan` with `{}` |
32
+ | Apply a reviewed plan to the database | `apply` | `simetra apply <plan> [dir] --plan-hash <hex> --yes` | `apply` with `{plan, planHash, allow?, confirm}` |
33
+
34
+ `compile`, `explain`, `diff`, `apply` only read files. `fix`, `create`, `add`,
35
+ `rename`, `delete`, `promote`, `introspect` change files; `plan` writes only its
36
+ plan file. `introspect`, `diff` and `plan` read the database; only `apply`
37
+ writes to it.
38
+
39
+ ## Examples
40
+
41
+ Create an object (ids and physical names are assigned for you):
42
+
43
+ ```json simetra:create
44
+ { "kind": "Catalog", "name": "Currency" }
45
+ ```
46
+
47
+ Add an attribute to it:
48
+
49
+ ```json simetra:add
50
+ {
51
+ "target": { "kind": "Catalog", "name": "Currency" },
52
+ "collection": "attributes",
53
+ "element": { "name": "symbol", "type": "String", "length": 5 }
54
+ }
55
+ ```
56
+
57
+ Rename it; references are rewritten, `physicalName` stays:
58
+
59
+ ```json simetra:rename
60
+ {
61
+ "target": { "kind": "Catalog", "name": "Currency", "element": ["symbol"] },
62
+ "newName": "sign"
63
+ }
64
+ ```
65
+
66
+ Preview a deletion without writing and without confirmation:
67
+
68
+ ```json simetra:delete
69
+ {
70
+ "target": { "kind": "Catalog", "name": "Currency", "element": ["sign"] },
71
+ "dryRun": true
72
+ }
73
+ ```
74
+
75
+ Promote an adopted `CustomTable` into a Catalog from a complete one-off
76
+ mapping (every column of the table is named; the call is dry-runnable like any
77
+ mutation, and its response carries the promotion record). `promote` also
78
+ writes the record to `plans/<objectId>.promotion.json`: commit it with the
79
+ metadata, since `plan` refuses a promotion without it
80
+ (`plan.promotion-record-missing`).
81
+
82
+ ```json simetra:promote
83
+ {
84
+ "target": { "name": "Tag" },
85
+ "into": { "kind": "Catalog", "name": "Tag", "data": { "codeLength": 0 } },
86
+ "columns": {
87
+ "id": { "to": "standard", "name": "ref" },
88
+ "name": { "to": "standard", "name": "description" }
89
+ }
90
+ }
91
+ ```
92
+
93
+ Filling a `promote` mapping (the schema says what the fields are; a refusal
94
+ says why a mapping is wrong, so read its diagnostics):
95
+
96
+ - `columns` names every column of the adopted table by its logical name, with
97
+ one fate: `{to: "standard", name}` (canonical camelCase name of a standard
98
+ attribute: `ref`, `description`, `deletionMark`, `parent`, `owner`, `number`,
99
+ `date`, ... whatever the project's attribute case), `{to: "scope"}` (the
100
+ scope carrier), `{to: "attribute", element: {name, ...}}` (an own attribute;
101
+ `collection` is `dimensions` or `resources` only in registers) or
102
+ `{to: "retire"}`. An element carries no `id` or `physicalName`.
103
+ - `into.data` holds the kind's settings (for example `codeLength`); name, kind,
104
+ schema, scope, ids and physical names come from the table and the operation
105
+ and are refused in the input. `tabularSections` lists further adopted tables
106
+ with their own `columns`.
107
+ - `fill` computes a target column: one that no column carries, or a mapped
108
+ target whose source allows NULL while the target is NOT NULL. On a mapped
109
+ target, `coalesce(<its source column>, <value>)` keeps the existing values
110
+ and fills only the NULLs (transaction time such as `now()` is allowed in
111
+ `<value>`); any other expression rewrites the existing values (step kind
112
+ `repair`), which must be deterministic. A `fill` step addresses a tabular
113
+ section table through `table`. Its `expression` is written in the old
114
+ physical names and runs before the renames; a model function is called
115
+ schema-qualified.
116
+ - `conversions` gives a class (`platform`, `property`, `rowRule`, `metadata`,
117
+ `applicationCode`, `removed`) to each adopted element the kind does not take
118
+ over: the identity of every SQL unit of the adopted tables' modules except a
119
+ function in the closed shell, and of every unit elsewhere whose target is a
120
+ promoted table; `<CustomTable>#uniques|checks|indexes/<name or index>`;
121
+ `<CustomTable>#default/<column>` (the default of a column mapped to an own
122
+ attribute without `defaultValue`); `<CustomTable>#comment` and
123
+ `<CustomTable>#comment/<column>` (a comment the kind has no place for; only
124
+ `removed`). A refusal names each element still missing a class.
125
+ - A class must be true of the desired state: `property` is accepted only when
126
+ the kind recreates the element equivalently
127
+ (`promote.property-not-equivalent`; a DEFERRABLE attribute, for one, cannot be
128
+ `property`), and `platform` only when the desired state holds the replacement
129
+ mechanism (`plan.platform-replacement-missing`, raised by `plan`, which then
130
+ writes no plan). `plan` checks `property` again against the desired state:
131
+ a record, a later metadata change or a hand edit whose element the kind no
132
+ longer recreates equivalently is refused (`plan.property-not-reproduced`).
133
+ When refused, classify the element `removed` (the plan then needs the
134
+ `remove:` permission) or keep the table a `CustomTable`; for
135
+ `plan.property-not-reproduced`, alternatively make the kind recreate the
136
+ element equivalently.
137
+ - Before promoting, check whether server code reads or writes the table with
138
+ the service key. If it does, do not promote the table: the kind gives the
139
+ service role no privileges, so that code loses access
140
+ (`plan.service-role-access-lost`); keep the table a `CustomTable` until
141
+ platform commands exist. An explicit adopted grant to the service role takes
142
+ the class `removed`.
143
+ - Functions in the closed shell move to the kind's module, and functions that
144
+ read the promoted tables are rewritten in place. Other verbatim SQL that
145
+ reads them is refused: rewrite or drop it first.
146
+ - `sharedFunctions` lists identities of those module functions that move to
147
+ `sql/<schema>/<function>.sql` instead; `consumerLabels` the values by which
148
+ the consumer's data encodes the object (the record's `labelTranslation`
149
+ maps them to the kind label and lists the polymorphic `_type` columns that
150
+ hold them).
151
+
152
+ The same calls from a shell. A mutation takes its JSON as an argument, as
153
+ `--input`, or as `-` for stdin:
154
+
155
+ ```sh
156
+ pnpm exec simetra compile
157
+ pnpm exec simetra explain Catalog.Currency
158
+ pnpm exec simetra create '{"kind":"Catalog","name":"Currency"}' --dry-run
159
+ pnpm exec simetra delete --input '{"target":{"kind":"Catalog","name":"Currency"}}' --yes
160
+ pnpm exec simetra diff
161
+ pnpm exec simetra plan
162
+ pnpm exec simetra apply plans/initial-3f2a9c1b7d4e.plan.json --plan-hash <hex> --allow s2 --yes
163
+ ```
164
+
165
+ An input that does not match the tool's schema is refused with the path of the
166
+ offending field (for example `target.kind`); nothing is written.
167
+
168
+ ## Reading the result
169
+
170
+ - Exit code: `0` ok (warnings allowed), `1` the result has error diagnostics
171
+ (this includes refused operations such as `operation.delete-referenced`)
172
+ or, for `diff`, differences or errors — `0` from `diff` means the database
173
+ matches the metadata,
174
+ `2` the call itself was refused: input that does not match the tool's schema
175
+ (bad JSON, unknown field), a missing `--yes`, a usage or I/O error (bad flag,
176
+ missing directory) or an unknown `explain` target. In MCP the same cases are
177
+ `isError`, with diagnostics for the exit-1 ones.
178
+ - Text diagnostics look like `path/File.meta.json:LINE:COL severity code message`.
179
+ A diagnostic without a position (the input as a whole, a missing file) has no
180
+ `LINE:COL`. The code (`file.kind-mismatch`, …) is the stable handle; do not
181
+ match on message text.
182
+ - `--format json` carries the same diagnostics as data; use it when a program,
183
+ not a human, reads the output.
184
+ - `--locale en|uk` picks the message language (default `en`); code and
185
+ location are identical in both.
186
+ - Start from the first error: one root cause often produces several follow-ups.
187
+ - Artifacts (`snapshot.json`, `desired-state.sql`, `entities.d.ts`) are written
188
+ only with `compile --out <dir>`, and `--out` takes one metadata directory per run.
189
+
190
+ ## Mutations are checked, never raw
191
+
192
+ - Every mutation writes files **only when the result compiles without errors**;
193
+ otherwise nothing is written and the diagnostics are returned.
194
+ - `create`, `add`, `rename`, `delete` also need the current metadata to compile
195
+ cleanly (`operation.input-invalid` otherwise): run `fix` or repair the file by
196
+ hand first.
197
+ - `--dry-run` (MCP: `dryRun: true`) reports the changes without writing. Use it
198
+ before the real run.
199
+ - `delete` is destructive: it needs `--yes` (MCP: `confirm: true`) and is refused
200
+ while anything references the target: the result then carries
201
+ `operation.delete-referenced` listing every reference (exit 1, nothing
202
+ written). A dry run needs no confirmation; it reports `would write <file>` for
203
+ a file that changes and `would delete <file>` only for a file that is removed.
204
+ - Rename never changes `physicalName` or `kindLabel` (no DDL). Do not edit ids,
205
+ `physicalName` or `kindLabel` of existing elements by hand: they are assigned
206
+ once (by `fix`, `create`, `add`), and in a Git repository `compile` checks
207
+ them, together with an object's PG schema, against `HEAD`
208
+ (`identity.assigned-once-changed`). Outside Git that check is skipped with a
209
+ warning.
210
+ - Never pass an `id` to `create` or `add`: ids are assigned by the operation, and
211
+ an input carrying one gets `operation.input-invalid` (exit 1, nothing written).
212
+
213
+ ## Declare, don't write SQL
214
+
215
+ A rule the platform can derive is a property in the metadata, not a statement
216
+ in a `.sql` file. The schemas in `node_modules/simetra/schemas/` describe each
217
+ property; some that replace hand-written SQL are listed below.
218
+
219
+ Attribute properties (an element of `attributes`):
220
+
221
+ - `defaultValue`: `{ "fill": "now" | "today" | "newUuid" }` on a scalar of the
222
+ matching type, `{ "empty": true }` on an array (`"array": true`), or
223
+ `{ "empty": "object" | "array" }` on a scalar `Json`.
224
+ - `unique`: `true`, or `"ignoreCase"` on a scalar String or Text. `uniqueWithin`: `"owner"` or `"parent"`,
225
+ only on a catalog's own attributes and only when the catalog has owners or a
226
+ hierarchy.
227
+ - Numbers (scalar only): `nonNegative`, `positive`, `minValue`, `maxValue`.
228
+ - Strings and text (scalar only): `minLength`, `pattern`. The pattern must
229
+ mean the same in JavaScript and Postgres: no named groups, `\p{}`, `\k<>`,
230
+ `\b`, `\B`, `\x`, `\u{}` or inline flag groups such as `(?i:…)`. Write a
231
+ character as itself or as `\uXXXX`.
232
+ - `personalData: true` marks personal data (a name, a phone, an address):
233
+ anonymization sets it to `NULL`, so it cannot also be `required`.
234
+
235
+ Object properties:
236
+
237
+ - `indexes` on a Catalog, a Document and their tabular sections: a list of
238
+ composite indexes, each `{ "attributes": [name | { "name": …, "order": "desc" }] }`.
239
+ - `publicRead`: `"authenticated"` or `"anon"` on kinds with row-level security.
240
+ - Project file: `storageBuckets`, a list of `{ "bucket": …, "scopeKind": … }`.
241
+
242
+ An attribute with properties, added through the tool:
243
+
244
+ ```json simetra:add
245
+ {
246
+ "target": { "kind": "Catalog", "name": "Currency" },
247
+ "collection": "attributes",
248
+ "element": {
249
+ "name": "isoCode",
250
+ "type": "String",
251
+ "length": 3,
252
+ "unique": "ignoreCase",
253
+ "minLength": 3
254
+ }
255
+ }
256
+ ```
257
+
258
+ An event subscription is a file in `event-subscriptions/`, created with `create`
259
+ (kind `EventSubscription`): `sources` (refs `{ kind, name }` or
260
+ `{ "providerTable": "<schema>.<table>" }`), `event` (`beforeWrite`, `onWrite`,
261
+ `beforeDelete`, `onDelete`), optional `whenChanged` (attribute names, write
262
+ events only) and `handler` (`{ schema?, name }`, a no-argument function that
263
+ `RETURNS trigger`, in the closed shell below). The platform generates its
264
+ `FOR EACH ROW` triggers, named after `physicalName`, on every source: `before*`
265
+ is `BEFORE`, `on*` is `AFTER`, `*Write` is `INSERT OR UPDATE`, `*Delete` is
266
+ `DELETE`. With `whenChanged`, `<physicalName>` fires on an `UPDATE` that changes
267
+ a listed column (`IS DISTINCT FROM`), `<physicalName>_insert` on every `INSERT`.
268
+ No event is insert-only; `TG_OP` tells insert from update. A handler on a
269
+ provider table (`auth.users`) that writes app tables must be `SECURITY DEFINER`
270
+ with `SET search_path = ''`: the provider role has no rights on your schemas.
271
+
272
+ Catalogs and Documents get the row mechanics trigger `<table>_simetra_touch`
273
+ (the single platform function `simetra.touch()`): an insert sets `version` to 1,
274
+ an update adds 1, both set `updatedAt` to `now()` whatever the client writes.
275
+ Never maintain them (`moddatetime`) or list them in `whenChanged`. A
276
+ `beforeWrite` handler never assigns `NEW.updated_at` or `NEW.version` and never
277
+ replaces the row (`NEW := …`, `SELECT … INTO NEW`): it returns `NEW`, or `NULL`
278
+ to skip the write, never `OLD` or a copy of the row.
279
+
280
+ ## Users, membership and rights
281
+
282
+ People are platform data, not tables you write yourself: a users catalog
283
+ (`"role": "users"`), authorship (`trackAuthor`) and a membership catalog
284
+ (`membership`) instead of hand-written tables and set functions. Rights are
285
+ declarations too: `customActions`, `ownership`, `rightsContainer`,
286
+ `containerBinding` and `access` on objects; `accessDimensions`,
287
+ `membershipSources` and `assignmentSources` on the project; rights sets
288
+ (`rights-sets/`) and roles (`roles/`) are objects of their own. Every name in
289
+ them is a reference, so `rename` rewrites it and `delete` refuses while it is
290
+ used; the compiler checks them (rules `users.*`, `rights.*`) and `explain`
291
+ shows the derived rights contract, a role's contract and the rows of the
292
+ rights projection. Forms of each field:
293
+ `references/people-and-rights.md`.
294
+
295
+ ```json simetra:add
296
+ {
297
+ "target": { "kind": "Catalog", "name": "Currency" },
298
+ "collection": "customActions",
299
+ "element": { "name": "revalue", "requires": ["update"] }
300
+ }
301
+ ```
302
+
303
+ The platform layer (identities, the current user, provisioning) lives in the
304
+ PG schema `simetra`, generated when a users catalog exists. The schema is
305
+ reserved: no object, `defaultSchema`, set function, external reference,
306
+ event handler or SQL unit may use it, and there is no `metadata/sql/simetra/`
307
+ folder (`schema.reserved`). In SQL, the
308
+ current user is `(select simetra.current_user_id())`, written exactly so in a
309
+ policy (`sql.bare-current-user` rejects a bare call there); it is `NULL` for
310
+ an anonymous session or an anonymous sign-in of the provider, a service
311
+ session and an invalid user.
312
+
313
+ ## The SQL module: closed forms only
314
+
315
+ The `.sql` module of an object of a 1C kind accepts only:
316
+
317
+ - Functions in the closed shell: `LANGUAGE sql` or `plpgsql`, an explicit
318
+ volatility, and `SET search_path = ''` for every `SECURITY DEFINER`. No
319
+ overloads.
320
+ - Row rules: `ALTER TABLE <own table> ADD CONSTRAINT <name> CHECK (<rule>)`
321
+ within a small grammar. The constraint needs a name and must target the
322
+ object's own table or one of its own tabular-section tables.
323
+ - Movement query blocks in a document module.
324
+
325
+ Any other statement is rejected (`sql.statement-not-allowed`, `sql.closed-shell`,
326
+ `sql.row-rule-grammar`, …) with a hint that names the property that replaces it.
327
+ Follow the hint instead of rewording the statement. `CustomTable` and `PgEnum`
328
+ modules and the shared `metadata/sql/` folder are not closed: their content is
329
+ debt (below).
330
+
331
+ Privileges on what the platform owns are generated: `EXECUTE` on a declared
332
+ scope set function and on a subscription handler, and every grant on a kind's
333
+ tables. In debt SQL (a `CustomTable` or `PgEnum` module, the shared
334
+ `metadata/sql/`) a verbatim `GRANT`/`REVOKE` on them fails with
335
+ `sql.generated-grant` (a kind's own module rejects any). `simetra fix` removes
336
+ the statement (and its file, if left empty) only when every target belongs to
337
+ the platform; one that also names other objects you split by hand. A grant on another overload of the same name is not affected.
338
+
339
+ A row rule shape:
340
+
341
+ ```sql
342
+ ALTER TABLE <schema>.<own_table> ADD CONSTRAINT <rule_name> CHECK (<rule>);
343
+ ```
344
+
345
+ ## SQL debt
346
+
347
+ `metadata/sql-debt.json` lists the verbatim SQL units that the compiler still
348
+ tolerates. It only shrinks:
349
+
350
+ - Only `introspect` writes it, from the database. Never add an entry by hand.
351
+ - An entry that is no longer debt (its unit is gone or now has a closed form)
352
+ fails `compile` with `sql.debt-stale`; `fix` removes exactly such entries
353
+ and never adds one. A removed entry comes back only through `introspect`.
354
+ - A debt unit that is not in the list fails `compile` with `sql.debt-grows`.
355
+ Express the statement as a property, an `EventSubscription` or a closed-shell
356
+ function; moving it to another file does not make it acceptable.
357
+ - A project with an existing `sql/` folder and no list is seeded by running
358
+ `introspect` again (see `simetra-adoption`).
359
+
360
+ ## The database: introspect and diff
361
+
362
+ `introspect` and `diff` read a live database and never write to it. The
363
+ connection comes only from the environment (`SIMETRA_DATABASE_URL`, or the
364
+ variable named with `--database-url-env`); never paste a connection string.
365
+ Scope, the shadow database, exit codes and how to judge a result are in the
366
+ `simetra-adoption` skill. `diff` output carries `applyState`: `absent` while
367
+ the database holds none of the platform's apply state, which the first `apply`
368
+ creates and `diff` does not count as a difference; `present` otherwise.
369
+
370
+ ## The database: plan and apply
371
+
372
+ `plan` compares the live database with the metadata and writes
373
+ `plans/<from>-<to>.plan.json` next to the metadata directory (the directory
374
+ that holds `metadata/`); the database is only read. Its output shows drift
375
+ first, then each step with its class and lock level, then the `planHash`.
376
+ Show the plan to the owner before applying it.
377
+
378
+ `apply` applies exactly that file in one transaction. It needs the `planHash`
379
+ of the reviewed plan, confirmation (`--yes`, MCP `confirm: true`), and in
380
+ `allow` the id of every step that drops data or relaxes a guarantee and
381
+ `drift` when the plan carries drift; the plan output says which items need
382
+ it. `rehearse` runs the plan and rolls it back, but still takes the same
383
+ locks as `apply`. It also builds the desired shadow database and proves on the
384
+ same connection that the catalog equals the desired state, so it holds the
385
+ plan's locks a little longer. A successful `rehearse` writes its report to
386
+ `plans/<from>-<to>.rehearsal.json` next to the plan.
387
+
388
+ Before the end of the transaction, `apply` and `rehearse` re-validate function
389
+ bodies and fire deferred constraints; an invalid constraint or index that the
390
+ desired state does not have is refused. An `apply.function-check-blind` warning lists
391
+ functions the check cannot see (another language, no `EXECUTE` for the role, a
392
+ trigger function without a trigger): nothing proved their bodies, so review
393
+ them by hand.
394
+
395
+ When the role has global default privileges, a plan also ends with environment
396
+ steps: explicit GRANT/REVOKE that cancel them on the objects the plan creates.
397
+ The output shows them as their own group, `environment rights: the global
398
+ default privileges of role <role>`; review them with the rest of the plan.
399
+ If the environment changes before the apply, it is refused
400
+ (`apply.target-changed`); plan again. A plan file from an older tool version is
401
+ refused too: rebuild it with `plan`.
402
+
403
+ A promotion plan's `allow` also takes the `access:<table>`,
404
+ `delete:<table>.<constraint>`, `remove:<table>` and `repair:<table>` items its
405
+ output lists; a repair rewrites existing values with the fill expression shown.
406
+ A promotion is applied only with a valid rehearsal report: rehearse the plan on
407
+ a copy of the target with data first. Point the rehearsal at the copy through
408
+ the connection variable: `simetra apply --rehearse --database-url-env <VAR>`
409
+ on the command line, or an MCP server launched with
410
+ `simetra mcp --database-url-env <VAR>` (an MCP server's database is fixed at
411
+ launch). Make the copy from the target after the plan, restore it as the plan's
412
+ role with `pg_restore --no-owner`, on a server with the same PostgreSQL major
413
+ version, encoding and collation; otherwise the rehearsal is refused as not a
414
+ copy of the plan's target (`apply.target-changed`). Rehearsing on the target
415
+ itself is allowed, but it holds the target's locks for the whole run: make it
416
+ a deliberate choice of the owner, not a default. `apply` refuses without a
417
+ report (`apply.rehearsal-required`), with a stale one (`apply.rehearsal-stale`:
418
+ another plan, report format, server, ledger head, or not one row count per
419
+ promoted table), and when a table has rows on the target but none on the copy
420
+ (`apply.rehearsal-copy-empty`); it warns when the copy has fewer rows
421
+ (`apply.rehearsal-fewer-rows`) or when the statement timeout computed from the
422
+ report exceeds what Postgres accepts (`apply.rehearsal-timeout-unbounded`).
423
+
424
+ Which connection to use:
425
+
426
+ - Reads of the target (`introspect`, `diff`, `plan`) run in short read-only
427
+ transactions and work through a transaction-mode pooler.
428
+ - The shadow database of `diff` and `plan` needs a direct or session-mode
429
+ connection: it is created, reached by name and loaded with session settings
430
+ that a transaction-mode pooler is not guaranteed to keep. With a pooled target
431
+ connection, point `--shadow-url-env` at a direct one.
432
+ - A long `apply` wants a direct or session-mode connection too: a pooler may
433
+ cut the transaction with its own timeouts.
434
+
435
+ ```json simetra:apply
436
+ {
437
+ "plan": "plans/initial-3f2a9c1b7d4e.plan.json",
438
+ "planHash": "9b1d6e0c4f3a2b8d7e6f5a4c3b2a1908f7e6d5c4b3a29180f7e6d5c4b3a2918f",
439
+ "allow": ["drift", "s2"],
440
+ "confirm": true
441
+ }
442
+ ```
443
+
444
+ A changed plan file, changed metadata or a changed database refuses the
445
+ apply; plan again.
446
+
447
+ If `apply` reports `outcome unknown`, the connection was lost and the apply may
448
+ or may not have been committed. Never apply again blindly: look up the printed
449
+ apply id in the `apply_id` column of `simetra.ledger` first — a row means it was
450
+ committed.
451
+
452
+ ## Agents over MCP
453
+
454
+ ```sh
455
+ pnpm exec simetra mcp
456
+ pnpm exec simetra mcp --read-only
457
+ pnpm exec simetra mcp --database-url-env STAGING_DATABASE_URL
458
+ pnpm exec simetra mcp --allow-database-write
459
+ ```
460
+
461
+ - By default the write tools change files in the served directory, under the
462
+ same rules as the CLI: the metadata is in git, and nothing is written unless
463
+ the result compiles. `--read-only` is a flag of `simetra mcp` only; the CLI
464
+ has none (preview with `--dry-run`).
465
+ - With `--read-only` every tool is still listed, but a write tool is refused
466
+ with a hint to remove `--read-only` from the server's args. Ask the owner
467
+ before restarting the server without it.
468
+ - `apply` writes to the database only when the server runs with
469
+ `--allow-database-write`; without it `apply` is refused with a hint to add
470
+ the flag. Ask the owner; never add it yourself. `--read-only` refuses
471
+ `plan` and `apply` too: they write their files under `plans/`.
472
+ - `plan` and `apply` have no `dryRun`: review with `plan`, and check on the
473
+ database with `rehearse`.
474
+ - The server reads the disk on every call, so edits made by hand between calls
475
+ are seen.
476
+
477
+ ## Pre-commit and CI
478
+
479
+ Check every metadata directory under the current directory with
480
+ `simetra compile --all`; add `--staged` to compile the Git **index** instead of
481
+ the working tree (what a pre-commit hook wants). Fields assigned once are
482
+ compared with `HEAD` in both modes:
483
+
484
+ ```sh
485
+ pnpm exec simetra compile --all
486
+ pnpm exec simetra compile --all --staged
487
+ ```
488
+
489
+ A rejected commit means the staged content does not compile: run
490
+ `simetra compile --all` for the working tree, fix, `git add`, commit again. Do
491
+ not bypass the hook with `--no-verify`.
@@ -0,0 +1,156 @@
1
+ # Users, membership and rights
2
+
3
+ Forms of the people and rights declarations; the router is `SKILL.md`.
4
+
5
+ Contents:
6
+
7
+ - Users, authorship and membership
8
+ - Rights declarations
9
+ - Rights sets and roles
10
+
11
+ ## Users, authorship and membership
12
+
13
+ People are platform data, not tables you write yourself:
14
+
15
+ - **Users catalog.** A Catalog with `"role": "users"` is the project's users
16
+ catalog: at most one per project, `scope: "none"`, a description (the
17
+ display name filled from the account). The compiler adds the standard
18
+ `userKind` and `invalid` attributes. Every non-anonymous account of the
19
+ identity provider gets a row through the platform's provisioning; an
20
+ anonymous sign-in gets one when it is converted to a permanent account.
21
+ Provisioning inserts only the key
22
+ and the description, so the catalog's own attributes must accept that
23
+ insert: a `required` attribute needs a `defaultValue` that passes the
24
+ attribute's own checks, a unique attribute takes no default other than
25
+ `{ "fill": "newUuid" }`, and its module has no row rule
26
+ (`users.provision-unsafe` names the reason).
27
+ - **Scope root.** The users catalog may be the `root` of a scope kind
28
+ (`{ "object": { "kind": "Catalog", "name": "<users catalog>" } }`) while
29
+ staying `scope: "none"`; references to it from any scope kind are plain
30
+ references, without `crossScope`. Do not point a root or a foreign key at
31
+ the provider's account table.
32
+ - **Authorship.** `trackAuthor: true` on a Catalog or a Document adds the
33
+ standard `createdBy` and `updatedBy` references to the users catalog;
34
+ without a users catalog it is an error (`users.catalog-missing`).
35
+ - **Membership.** A scoped catalog with `membership: { "user": "<attribute>" }`
36
+ is the membership of its scope kind: the attribute is a scalar `Ref` to the
37
+ users catalog, nullable for an invited member without an account. The
38
+ compiler derives one member per user and scope value and generates a
39
+ "my member" function; a scope kind with `"setFunction": "membership"` gets
40
+ its scope set function from that catalog. Use it instead of a hand-written
41
+ member table and set function. One membership catalog per scope kind.
42
+
43
+ ## Rights declarations
44
+
45
+ A **carrier** is an attribute of the object, or a two-step path
46
+ `["<ref attribute>", "<attribute of its target>"]`; every step stays inside
47
+ the tenant (`rights.carrier-cross-tenant`).
48
+
49
+ - **`customActions`** — actions beyond the standard ones of the kind; each
50
+ gets an id, `requires` names standard action words or other custom actions
51
+ of the object, `effects` says what it writes. The name is unique among the
52
+ object's attributes, tabular sections and custom actions.
53
+ `{ "name": "<action>", "requires": ["update"], "effects": { "header": ["<attribute>"] } }`
54
+ 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`).
58
+ - **`ownership`** — carriers whose `Ref` names the owner of a row (a member
59
+ or a user). `"ownership": ["<attribute>", ["<ref attribute>", "<attribute>"]]`
60
+ The target is the users catalog, the membership catalog of the object's own
61
+ scope kind, or the adopted table of that scope kind's membership source
62
+ (`rights.ownership-target`); `"ref"` (the key) owns only rows of the users
63
+ catalog. An adopted target needs a `UNIQUE (<scope column>, <key>)`, so the
64
+ reference becomes a composite foreign key within the scope.
65
+ - **`rightsContainer`** — the catalog is a rights container: roles can be
66
+ assigned on its rows. `"rightsContainer": true`
67
+ - **`containerBinding`** — the carrier that binds a row to its container.
68
+ `"containerBinding": "<attribute>"` or `["<ref attribute>", "<attribute>"]`
69
+ - **`access`** — the project access dimensions that narrow the rows, each with
70
+ its carrier to the dimension's value catalog.
71
+ `"access": [{ "attribute": "<attribute>", "dimension": "<dimension>" }]` or
72
+ `{ "ref": ["<ref attribute>", "<attribute>"], "dimension": "<dimension>" }`
73
+ - **`accessDimensions`** (project) — a value catalog plus where the current
74
+ user's values come from: a relation object or a verbatim SQL function.
75
+ `{ "name": "<dimension>", "target": <catalog ref>, "values": { "relation": { "object": <ref>, "subject": "<field>", "value": "<field>" } } }`
76
+ or `"values": { "function": { "name": "<function>" } }`.
77
+ The function is verbatim SQL of a closed form: no arguments,
78
+ `RETURNS SETOF uuid LANGUAGE sql STABLE SECURITY DEFINER SET search_path = ''`
79
+ with an `AS $$ … $$` body,
80
+ every name schema-qualified (also in the views it reads and the `sql`
81
+ functions it calls; a `plpgsql` function in that chain is refused), and no
82
+ `simetra.*` object except `simetra.current_user_id()`
83
+ (`rights.dimension-function-*`).
84
+ - **`membershipSources`** (project) — an adopted table that holds the
85
+ membership of a scope kind instead of a membership catalog.
86
+ `{ "name": "<source>", "scopeKind": "<scope kind>", "table": <CustomTable ref>, "columns": { "scope": "<column>", "user": "<column>" } }`
87
+ - **`assignmentSources`** (project) — an adopted table that holds role
88
+ assignments of one level: `"global"`, `{ "scopeKind": "<scope kind>" }` or
89
+ `{ "container": <ref> }`.
90
+ `{ "name": "<source>", "assignedOn": "global", "table": <CustomTable ref>, "columns": { "member": "<column>", "role": "<column>" } }`
91
+
92
+ Dimensions and sources are project elements: add them to the project root
93
+ (`"target": { "kind": "Project" }`) and rename or delete them by
94
+ `{ "kind": "Project", "element": ["<name>"] }`; their names are unique among
95
+ all named elements of the project.
96
+
97
+ ## Rights sets and roles
98
+
99
+ A **rights set** (`rights-sets/<Name>/<Name>.meta.json`) is a named group of
100
+ grants; a **role** (`roles/<Name>/<Name>.meta.json`) is what an assignment
101
+ gives a member. Both get an id from `fix` and have no physical name.
102
+
103
+ ```jsonc
104
+ {
105
+ "kind": "Role",
106
+ "name": "<role>",
107
+ "assignedOn": "global" | "everyUser" | { "scopeKind": "<scope kind>" } | { "container": <catalog ref> },
108
+ "include": [{ "kind": "RightsSet", "name": "<set>" }],
109
+ "grants": [
110
+ { "grantAll": { "extent": "<extent>" } },
111
+ { "grant": { "objects": [<object ref>], "actions": ["<action>"], "extent": "<extent>" } },
112
+ { "deny": { "objects": { "withAction": "<standard action>" }, "actions": ["<action>"] } }
113
+ ]
114
+ }
115
+ ```
116
+
117
+ A set has the same `include` and `grants`, without `assignedOn` and without
118
+ `deny`. A role also takes `fullAccess`, `order`, `assignable`, `maxHolders`,
119
+ `rootCreator` and `sourceKeys` (`[{ "source": "<assignment source>", "key": "<key>" }]`,
120
+ the role's key in an adopted assignment table of the same level).
121
+
122
+ **Levels** (`assignedOn`) decide which objects a role's grants may touch:
123
+
124
+ - `"global"` — per user; in a project with scope kinds, unscoped objects only.
125
+ - `{ "scopeKind": "<scope kind>" }` — per member of a tenant: every action on
126
+ objects of that scope kind, only `read` on unscoped ones. The scope kind
127
+ needs a membership.
128
+ - `{ "container": <ref> }` — per row of a `rightsContainer` catalog: objects
129
+ whose `containerBinding` leads to it.
130
+ - `"everyUser"` — every valid user without an assignment: unscoped objects,
131
+ `own` or a dimension extent only, no `fullAccess`, no source keys.
132
+
133
+ **Grants:**
134
+
135
+ - `include` — the sets' grants become the role's; includes are transitive,
136
+ a cycle is an error.
137
+ - `grantAll` — every action the level allows on every object of the level
138
+ that supports the extent; an object without it is skipped.
139
+ - `grant` — the listed actions on the objects. `objects` is a list of
140
+ references or `{ "withAction": "<standard action>" }` (every object of the
141
+ level that has it). A custom action is granted on exactly one listed object.
142
+ - `deny` — only in a role: removes rows after the includes are expanded, with
143
+ the given extent or, without one, every extent of the actions.
144
+
145
+ **Extents:** `"any"`, `"own"` (the object needs `ownership`) or
146
+ `{ "dimension": "<dimension>" }` (the object maps it in `access`). `any`
147
+ covers `own` and every dimension, so `X@any` also yields `X@own` and
148
+ `X@<dimension>`; `own` and dimensions do not cover each other. An action's
149
+ `requires` is met at the same extent or at `any`.
150
+
151
+ The compiler reports these as `rights.*` (for example `rights.grant-level`,
152
+ `rights.extent-unsupported`, `rights.requires-missing`,
153
+ `rights.custom-action-multi-object`, `rights.include-cycle`); the full set is
154
+ the compiler's rule catalog. Changing a role's level is an
155
+ `identity.assigned-once-changed` error; renaming its scope kind or container
156
+ is not.