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