@simetrajs/designer 0.2.0 → 0.3.0-next.10

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,17 @@
1
+ # List-order indexes
2
+
3
+ `indexed: true` on an attribute and a composite `indexes` entry both give a
4
+ list-order index: the scope column first (on a scoped table), the attribute
5
+ columns in the declared order, the row key last. A keyset page then reads
6
+ from the index without sorting the visible set.
7
+
8
+ - A table without a one-column row key (a register movement or totals) gets no
9
+ key column.
10
+ - A `unique` attribute already has such an index, so no second one is made.
11
+ - An `indexed` `Ref` uses one index for both the foreign key and the order.
12
+ - Changing an existing index to this shape is a drop and a create in the
13
+ apply plan; it needs no permission, but the table is locked while the
14
+ index builds.
15
+ - A catalog's standard `description` is `NOT NULL DEFAULT ''` and indexed
16
+ whenever the catalog has it (`descriptionLength` above 0). A command may
17
+ omit it (the default `''` is stored) but must not send an explicit `null`.
@@ -26,6 +26,8 @@ export const client = defineObjectModule<Catalogs.Client>({
26
26
  the draft `{ values?, tabularSections? }` the phase writes. It never adds
27
27
  `id` or `mark`; the runtime checks the returned draft again.
28
28
  - `onWrite` (1C `ПриЗаписи`) sees the written row in the same transaction.
29
+ The row has the shape of a card read: the tabular sections that the phase
30
+ wrote are under `row.tabularSections.<name>`.
29
31
  - Both run on the operations `create`, `update` and `markDeletion`;
30
32
  `delete` raises no module event. On `markDeletion` the draft is empty and
31
33
  the mark is `ctx.mark`.
@@ -39,8 +41,24 @@ export const client = defineObjectModule<Catalogs.Client>({
39
41
  `ctx.isNew` is `create`; `ctx.user` is the current user.
40
42
  - `ctx.additionalProperties` is shared by the hooks of one phase only.
41
43
  - `ctx.run(operation)` runs a phase of another object in the same
42
- transaction, with its own rights check and hooks; `ctx.read(query)` reads in
43
- that transaction.
44
+ transaction, with its own rights check and hooks, and returns the written
45
+ row in the same shape as `onWrite` sees it; `ctx.read(query)` reads in
46
+ that transaction. It takes the query of `data-read` and returns `{ rows }`
47
+ or `{ count, capped? }`, e.g.
48
+ `ctx.read({ object, where: { attribute: "code", op: "eq", value }, limit: 1 })`.
49
+ - A tabular section array in an `update` passed to `ctx.run` replaces the
50
+ section: every existing row must be in the array or in `deleteIds`,
51
+ otherwise the command fails with `command.invalid`
52
+ `reason: "tabular-rows-missing"` — the same rule as `data-command`.
53
+ `ctx.run` always checks this. Build the array from a `ctx.read` of the
54
+ owner's lines.
55
+ - One command transaction may start at most `BATCH_MAX` phases through
56
+ `ctx.run`; past it the command fails with `command.depth`
57
+ `reason: "phases"`. Nesting deeper than the runtime's depth limit is
58
+ `command.depth` too.
59
+ - Hook time counts toward the command's time budget: a command past it
60
+ fails with `command.timeout`, and a lock wait past the lock timeout with
61
+ `command.busy`. Keep hooks short.
44
62
  - `ctx.reject(code, path?)` fails the command with `command.rejected`.
45
63
  - A `ctx` method works only while its hook runs. Never keep `ctx` for later:
46
64
  a late call fails the command (`command.internal`).
@@ -52,6 +52,38 @@ People are platform data, not tables you write yourself:
52
52
  its scope set function from that catalog. Use it instead of a hand-written
53
53
  member table and set function. One membership catalog per scope kind.
54
54
 
55
+ A scope kind needs its root (scoped by the kind itself) and, with
56
+ `"setFunction": "membership"`, a membership catalog; none of the three compiles
57
+ alone, so `add` creates them in one change with `objects`. Every existing
58
+ object that takes a scope must already declare one (`"scope": "none"` or a
59
+ kind), or the first kind fails with `scope.declaration-missing`:
60
+
61
+ ```json simetra:add
62
+ {
63
+ "target": { "kind": "Project" },
64
+ "collection": "scopeKinds",
65
+ "element": {
66
+ "name": "org",
67
+ "root": { "object": { "kind": "Catalog", "name": "Organization" } },
68
+ "setFunction": "membership"
69
+ },
70
+ "objects": [
71
+ { "kind": "Catalog", "name": "Organization", "data": { "scope": "org" } },
72
+ {
73
+ "kind": "Catalog",
74
+ "name": "OrgMember",
75
+ "data": {
76
+ "scope": "org",
77
+ "membership": { "user": "user" },
78
+ "attributes": [
79
+ { "name": "user", "type": "Ref", "ref": { "kind": "Catalog", "name": "Users" } }
80
+ ]
81
+ }
82
+ }
83
+ ]
84
+ }
85
+ ```
86
+
55
87
  The platform layer (identities, the current user, provisioning) lives in the
56
88
  PG schema `simetra`, generated when a users catalog exists, or when the
57
89
  project has a membership source and its provider's user id is the `sub` claim
@@ -97,8 +129,51 @@ with a trigger on the target table, see "Carrier copies").
97
129
  reference becomes a composite foreign key within the scope.
98
130
  - **`rightsContainer`** — the catalog is a rights container: roles can be
99
131
  assigned on its rows. `"rightsContainer": true`
100
- - **`containerBinding`** — the carrier that binds a row to its container.
101
- `"containerBinding": "<attribute>"` or `["<ref attribute>", "<attribute>"]`
132
+ - **`containerBinding`** — the `Ref` attribute that binds a row to its
133
+ container. `"containerBinding": "<attribute>"`; the path form
134
+ `["<ref attribute>", "<attribute>"]` is a schema error (it stays valid for
135
+ `ownership` and `access`). The target is a `rightsContainer` catalog (a
136
+ direct binding) or an object with its own `containerBinding` (a chain, of
137
+ any length: comment → task → project, where only the project is a container). The container of a row is the first
138
+ `rightsContainer` the chain reaches, so a container never continues the
139
+ chain. A hierarchy (a kind whose rows point at a parent row of the same
140
+ kind) is not a chain: bind every node directly to its container, never
141
+ through the parent attribute, because a binding to the kind itself is a
142
+ cycle. Any cycle in the kind graph, including a
143
+ reference to itself and two containers bound to each other, is
144
+ `rights.container-binding-cycle` on every kind of the cycle; a target that
145
+ is neither a container nor bound is `rights.container-target`.
146
+
147
+ A chained row carries a platform-owned copy of its binding, a standard
148
+ column named from the binding attribute and the end column of the direct
149
+ binding (`rights.carrier-column-taken` on a clash). The platform writes it;
150
+ a value in a request is ignored. A read policy compares only that column, so
151
+ the cost of a read does not grow with the chain. A container role reads the
152
+ chained row when the grant covers its kind.
153
+
154
+ **Rebinding.** Changing the binding attribute of a row whose kind has chained
155
+ descendants moves all of them to another container. Besides the right to
156
+ update the row itself, the actor needs `update` at extent `any` on every
157
+ descendant kind, on every level below, in the container before and in the
158
+ container after: through a role on that container or a scope-level role.
159
+ An empty binding on either side needs the scope-level right. Otherwise the
160
+ command fails with `command.forbidden` / `no-right`, and the database error
161
+ names the descendant kind; the check runs before any copy is rewritten. A
162
+ change made by a `beforeWrite` handler is judged the same way. Moving a row
163
+ between targets of the same container needs no extra right, and neither
164
+ does the copy update that a rebinding cascades. Outside a command
165
+ (maintenance, a plan data step) the check does not run.
166
+
167
+ **Limits.** Reading costs the same at any depth. Writing pays: a rebind
168
+ rewrites the copies of all descendants on every level below, in the same
169
+ transaction, one `UPDATE` per level through the foreign key index. Measured
170
+ on one developer machine (16 cores, Postgres 17 on the local stack, light
171
+ load), one task moved between two projects, 5 replies per
172
+ comment: 10 comments (60 copies) 6.5 ms median, 100 comments (600 copies)
173
+ 47 ms, 1 000 comments (6 000 copies) 489 ms (p90 528 ms), roughly 80 µs per
174
+ rewritten row. Keep the number of descendants of one row that can be
175
+ rebound in a single command in the low thousands, and give a deep or wide
176
+ subtree its own container instead of rebinding it.
102
177
  - **`access`** — the project access dimensions that narrow the rows, each with
103
178
  its carrier to the dimension's value catalog.
104
179
  `"access": [{ "attribute": "<attribute>", "dimension": "<dimension>" }]` or
@@ -115,7 +190,9 @@ with a trigger on the target table, see "Carrier copies").
115
190
  `rights.dimension-name-reserved`.
116
191
  The function is verbatim SQL of a closed form: no arguments,
117
192
  `RETURNS SETOF uuid LANGUAGE sql STABLE SECURITY DEFINER SET search_path = ''`
118
- with an `AS $$ … $$` body,
193
+ plus the pinned session settings of a head (the exact `SET` options are in
194
+ the hint of `sql.head-settings`; without them that error, the same for a
195
+ verbatim scope set function) with an `AS $$ … $$` body,
119
196
  every name schema-qualified (also in the views it reads and the `sql`
120
197
  functions it calls; a `plpgsql` function in that chain is refused), and no
121
198
  `simetra.*` object except `simetra.current_user_id()`
@@ -175,7 +252,11 @@ the role's key in an adopted assignment table of the same level).
175
252
  objects of that scope kind, only `read` on unscoped ones. The scope kind
176
253
  needs a membership.
177
254
  - `{ "container": <ref> }` — per row of a `rightsContainer` catalog: objects
178
- whose `containerBinding` leads to it.
255
+ whose `containerBinding` chain ends in it. Any such assignment also gives
256
+ implicit `read` of the container's own row, even for a role with no grants.
257
+ It covers that row only: not its tabular sections, no write, no
258
+ change-channel subscription, and a `rights_require` check without a target
259
+ row does not take it.
179
260
  - `"everyUser"` — every valid user without an assignment: unscoped objects,
180
261
  `own` or a dimension extent only, no `fullAccess`, no source keys.
181
262
 
@@ -360,7 +441,8 @@ catalogs through `runtime.run` (`simetra/server`). Every operation on them
360
441
  runs under `administerRights`:
361
442
 
362
443
  - custom role: `create`, `update` with `expectedVersion` (the `delta`
363
- tabular section is replaced whole), `markDeletion` on the roles catalog;
444
+ tabular section is replaced whole: name every existing line in the array
445
+ or in `deleteIds`), `markDeletion` on the roles catalog;
364
446
  - assignment: `create`, and `delete` with `expectedVersion`, on the role
365
447
  assignments catalog.
366
448
 
@@ -605,8 +687,15 @@ whose user id is the `sub` claim):
605
687
  - A table of a kind is read only through a role's `read` right on its object,
606
688
  at the extent of the grant (`any`, `own`, a dimension, in a container); its
607
689
  tabular sections and a register's movements and totals follow the object.
608
- `publicRead` opens every row instead and needs no right. It is an error
609
- (`rights.public-read-forbidden`) on the users catalog, a membership catalog
690
+ `publicRead` as a string opens every row instead and needs no right. The
691
+ conditional form `{ "role": "anon" | "authenticated", "published": true }`
692
+ opens only rows that are published and not marked for deletion (the header
693
+ and its tabular sections): it needs a catalog with commands, rights
694
+ functions and a rights contract with `read`, keeps the read policies and the
695
+ tenant boundary for everyone else, and adds the actions `publish` and
696
+ `unpublish`; marking a row for deletion unpublishes it. Example:
697
+ `"publicRead": { "role": "anon", "published": true }`. Any
698
+ `publicRead` is an error (`rights.public-read-forbidden`) on the users catalog, a membership catalog
610
699
  and the rights system catalogs: for public profiles declare a separate
611
700
  catalog with the public fields and a reference to the users catalog.
612
701
  - A scoped object is read only inside the reader's scopes, and only through a
@@ -623,6 +712,34 @@ the scope kind in `project.meta.json`) says that no role reads any object of
623
712
  that scope kind, so nobody will see their rows: grant `read` to a role or
624
713
  declare one with `fullAccess`.
625
714
 
715
+ **Open self sign-up.** `"selfSignUp": true` in `project.meta.json` declares
716
+ that anyone may register, so whatever every signed-in user sees is open to
717
+ anyone. The warning `project.self-sign-up` then lists the objects with
718
+ `publicRead` `authenticated` and the grants of `everyUser` roles. List what you
719
+ open on purpose in `selfSignUpAccepted`, and the warning names only the rest;
720
+ a new object, action or wider form warns again:
721
+
722
+ ```json
723
+ "selfSignUpAccepted": {
724
+ "objects": [{ "object": { "kind": "Catalog", "name": "Country" } }],
725
+ "grants": [
726
+ {
727
+ "role": { "kind": "Role", "name": "ClientOwner" },
728
+ "object": { "kind": "Catalog", "name": "Client" },
729
+ "actions": ["read", "update"],
730
+ "extent": "own"
731
+ }
732
+ ]
733
+ }
734
+ ```
735
+
736
+ `"published": true` on an object entry accepts only the published rows of the
737
+ conditional `publicRead`. The names are references: `rename` rewrites them, and
738
+ `delete` of an accepted object, role, custom action or dimension is refused
739
+ until the entry is removed. An entry that matches nothing open any more warns
740
+ with `project.self-sign-up-stale`: remove it, and accept the openness again
741
+ when it comes back.
742
+
626
743
  ## Who writes what
627
744
 
628
745
  Kind tables are written **only by commands**: the write policies grant the
@@ -676,40 +793,142 @@ on another overload of the same name is not affected.
676
793
  `simetra_command` (`NOLOGIN NOINHERIT`, on the target and the shadow server)
677
794
  and, when a project file is present, the runtime login role `simetra_runtime`
678
795
  on the target only (`LOGIN NOINHERIT`, a member of `simetra_command` and, for
679
- `supabase`, of `authenticated`, each `WITH INHERIT FALSE, SET TRUE`). It reads
796
+ `supabase`, of `authenticated` and `anon`, each `WITH INHERIT FALSE, SET TRUE`). It reads
680
797
  `database.provider` from the project file; without a project file it skips the
681
798
  login role, and the output says why. The operator sets the login role's
682
- password; the platform keeps no secrets.
799
+ password; the platform keeps no secrets (the one exception, a database on your
800
+ machine, is `--dev-passwords` below).
683
801
 
684
802
  The login role needs `ADMIN OPTION` on each of its parent roles in the role
685
803
  that runs `roles`. Without it `roles` still creates the grant roles, but
686
804
  refuses the login role with `roles.admin-option-missing` and does not create
687
- it. An existing role is only checked, never changed.
805
+ it. An existing role is only checked, with one change: after upgrading
806
+ Simetra, run `roles` again on an existing database; it adds a missing
807
+ membership of the login role in a parent of its profile, or refuses with
808
+ `roles.membership-grant-denied`, which names the `GRANT` to run.
809
+
810
+ ### The `postgres` provider
811
+
812
+ On `database.provider: "postgres"` the same command prepares the cluster and
813
+ needs a superuser that logs in as itself. Give it through
814
+ `--database-url-env <VAR>` (a variable other than the owner's, so the
815
+ superuser DSN is not the one `plan` and `apply` use). It creates the roles of
816
+ the profile, the application database owned by `simetra_owner`,
817
+ `plpgsql_check` in that database, and the sealed template database
818
+ `simetra_template` that shadows and proof copies are built from. Running it
819
+ again converges the declared state and creates nothing.
820
+
821
+ For a database on your machine, `simetra roles --dev-passwords` (MCP input
822
+ `devPasswords: true`) also sets the password of each login role this run
823
+ creates (`simetra_owner`, `simetra_auth`, `simetra_runtime`,
824
+ `simetra_signals`) from `SIMETRA_OWNER_DEV_PASSWORD`,
825
+ `SIMETRA_AUTH_DEV_PASSWORD`, `SIMETRA_RUNTIME_DEV_PASSWORD` and
826
+ `SIMETRA_SIGNALS_DEV_PASSWORD` in the environment. A role that already exists
827
+ keeps its password. It refuses before anything is written when a variable is
828
+ missing or empty (`roles.dev-password-missing`), when the database host is not
829
+ this machine — `localhost`, `127.0.0.0/8`, `::1` or a unix socket
830
+ (`roles.dev-passwords-remote`), or when the provider is not `postgres`
831
+ (`roles.dev-passwords-unsupported`). On any other server set the passwords
832
+ yourself.
833
+
834
+ The identity provider's own roles get their grants here too: the role of the
835
+ platform owner receives `USAGE` on the `better_auth` schema and `TRIGGER` and
836
+ `REFERENCES` on `better_auth."user"`, so the provision triggers and the foreign
837
+ keys of the model can sit on the account table. Before the identity provider's
838
+ migration has created that table, the table grants are skipped and the output
839
+ says so; run `roles` again after the migration. The spec of the
840
+ profile has the role set and the reasons:
841
+ `docs/superpowers/specs/2026-11-08-postgres-profile-design.md` §3.
842
+
843
+ Refusals, all raised before anything is written unless the hint says
844
+ otherwise:
845
+
846
+ - `roles.superuser-required` — the role is not a superuser, or its current
847
+ role differs from the login role; connect as the superuser.
848
+ - `roles.unsafe-schema` — a schema in the database (`extensions`,
849
+ `better_auth`) has an owner or content a superuser session must not trust;
850
+ the hint lists what to fix by hand.
851
+ - `roles.unsafe-template` — `simetra_template` is owned by a non-superuser,
852
+ accepts connections, or is closed without being marked as a template; drop
853
+ it as a superuser and run `roles` again.
854
+ - `roles.database-owner` — the database belongs to another role than
855
+ `simetra_owner`; fix the owner by hand or use a database `roles` creates.
856
+ - `roles.database-locale` — the database or `simetra_template` has another
857
+ collation than ICU `en-US`; `roles` never drops a database: dump, drop and
858
+ restore it by hand around a new `roles` run (the template is only dropped).
859
+ - `roles.shared-cluster` — a Simetra login role has an explicit `CONNECT` on
860
+ other databases; one cluster serves one application.
861
+ - `roles.extension-unavailable` — the server does not offer `plpgsql_check`
862
+ in `pg_available_extensions`; install the extension's package on the
863
+ database server (`postgresql-<major>-plpgsql-check` from PGDG) and run
864
+ `roles` again. `apply` refuses the same way with
865
+ `apply.extension-unavailable` before it locks any table when its plan checks
866
+ function bodies with the extension and the server no longer offers it.
867
+ - `plan.owner-not-bypassrls` — the role of `plan`, `apply` or `rehearse` has
868
+ neither `BYPASSRLS` nor superuser; run `ALTER ROLE <role> BYPASSRLS` as a
869
+ superuser.
870
+ - `plan.shadow-base-unsupported` — a separate shadow server is not supported
871
+ on `postgres`; drop `--shadow-url-env`.
872
+
873
+ - `plan.identity-table-missing` — the model needs provision triggers on the
874
+ account table of the identity provider and the connected role cannot place
875
+ them: reason `table` means the table does not exist yet (run the provider's
876
+ migration first), reason `privilege` means the role lacks `USAGE` on its
877
+ schema or `TRIGGER` on the table (run `roles` again as the superuser).
878
+ - `plan.identity-trigger-locked` — on `postgres` only the owner of the account
879
+ table can remove or enable a provision trigger on it, and `plan` does not run
880
+ as that owner: reason `removed` means the plan drops a trigger, reason
881
+ `disabled` means it would enable a trigger that is disabled. Do the change by
882
+ hand as the table owner.
688
883
 
689
884
  `plan.platform-role-shape` with the violation `request-role:<role>` means an
690
885
  API request role (such as `authenticated`) and a platform role are members of
691
886
  each other in some form, even `ADMIN` alone; revoke that membership.
692
887
 
888
+ ### Runtime login and anonymous sessions
889
+
890
+ The runtime refuses to start with `command.privileged-login` when its login
891
+ role reaches a power it must not hold, itself or through a membership; the
892
+ `reason` names the first fact found: `owner`, `superuser`, `bypassrls`,
893
+ `createrole`, `server-files`, `read-all-data`, `write-all-data`,
894
+ `database-owner` (the login owns the current database), `provider-login` or
895
+ `service`. Use the
896
+ dedicated runtime login role `simetra_runtime`, not an owner, a superuser or a
897
+ provider login.
898
+
899
+ An anonymous session is a guest and reads as one. On a provider whose
900
+ identity data marks anonymous sessions with a claim, a session that has a
901
+ subject but no anonymous claim is refused with `command.unauthenticated`
902
+ before any database work: the claim must be present, `true` or `false`.
903
+
693
904
  ## Reading past row-level security
694
905
 
695
- `sql.definer-reads-rls` (a warning) marks a unit that reads a table under
906
+ A `SECURITY DEFINER` function runs as its owner, the applying role, which
907
+ bypasses row-level security (`FORCE ROW LEVEL SECURITY` does not stop it).
908
+ One that a role of the API (or `PUBLIC`) may `EXECUTE` fails `compile` with
909
+ `sql.definer-caller-unchecked` in any `.sql` file, SQL debt included, whatever
910
+ it reads, until it names the check of its caller. Two ways out: link it to a
911
+ scope kind as its set function (or to an access dimension as its values
912
+ function), or declare its signature with the named check. After `introspect`
913
+ from scratch, set functions come back unlinked and fail this way until you
914
+ link them.
915
+
916
+ `sql.definer-reads-rls` (a warning) marks a view that reads a table under
696
917
  row-level security as its owner, so the caller's policies do not apply, while
697
- a role of the API (or `PUBLIC`) can run or read it:
918
+ a role of the API (or `PUBLIC`) can read it:
698
919
 
699
- - a `SECURITY DEFINER` function that someone may `EXECUTE`;
700
920
  - a view without `security_invoker` that someone may `SELECT`;
701
921
  - a materialized view, which stores the rows its owner read at `REFRESH`.
702
922
 
703
- The diagnostic lists the tables it found. The compiler does not see the owner of a function,
704
- so one whose owner is itself subject to row-level security is flagged too.
705
- Convert in this order of preference:
923
+ The diagnostic lists the tables it found. Convert in this order of
924
+ preference:
706
925
 
707
926
  1. Read through a right and a policy: let the caller read the kind's table
708
927
  itself, so the platform's policies decide, and make the unit
709
928
  `SECURITY INVOKER` (a view: `WITH (security_invoker = true)` in
710
929
  `CREATE VIEW`; a separate `ALTER VIEW` is not accepted in `.sql` files).
711
- 2. If the unit must run as its owner, check the caller's membership or rights
712
- inside it, or filter the rows with the rights functions in a view.
930
+ 2. Write the operation as a command of the object or a TypeScript hook; a
931
+ view may filter the rows with the rights functions.
713
932
  3. If no API caller needs it, `REVOKE EXECUTE` (function) or `REVOKE SELECT`
714
933
  (view, materialized view) from `PUBLIC` and from each API role. A
715
934
  materialized view that serves callers is replaced by a view with
@@ -0,0 +1,81 @@
1
+ # The database: plan and apply
2
+
3
+ `plan` compares the live database with the metadata and writes
4
+ `plans/<from>-<to>.plan.json` next to the metadata directory (the directory
5
+ that holds `metadata/`); the database is only read. Its output shows drift
6
+ first, then each step with its class and lock level, then the `planHash`.
7
+ Show the plan to the owner before applying it.
8
+
9
+ The generated SQL grants to platform roles (`simetra_command`) that live in the
10
+ cluster, not in the database, so `plan` does not create them. Without one on
11
+ the target or the shadow server, `plan`, `diff` and `rehearse` refuse with
12
+ `plan.platform-role-missing`: run `simetra roles` once with a role that has
13
+ `CREATEROLE` ("Platform roles" in the people-and-rights reference; `postgres`
14
+ needs a superuser and no separate shadow server). It only checks an existing role; an unsafe
15
+ shape (`plan.platform-role-shape`) is fixed by hand, not by `roles`.
16
+
17
+ `apply` applies exactly that file in one transaction. It needs the `planHash`
18
+ of the reviewed plan, confirmation (`--yes`, MCP `confirm: true`), and in
19
+ `allow` the id of every step that drops data or relaxes a guarantee and
20
+ `drift` when the plan carries drift; the plan output says which items need
21
+ it. `rehearse` runs the plan and rolls it back, but still takes the same
22
+ locks as `apply`. It also builds the desired shadow database and proves on the
23
+ same connection that the catalog equals the desired state, so it holds the
24
+ plan's locks a little longer. A successful `rehearse` writes its report to
25
+ `plans/<from>-<to>.rehearsal.json` next to the plan.
26
+
27
+ Before the end of the transaction, `apply` and `rehearse` re-validate function
28
+ bodies and fire deferred constraints; an invalid constraint or index that the
29
+ desired state does not have is refused. An `apply.function-check-blind` warning lists
30
+ functions the check cannot see (another language, no `EXECUTE` for the role, a
31
+ trigger function without a trigger): nothing proved their bodies, so review
32
+ them by hand.
33
+
34
+ When the role has global default privileges, a plan also ends with environment
35
+ steps: explicit GRANT/REVOKE that cancel them on the objects the plan creates.
36
+ The output shows them as their own group, `environment rights: the global
37
+ default privileges of role <role>`; review them with the rest of the plan.
38
+ If the environment changes before the apply, it is refused
39
+ (`apply.target-changed`); plan again. A plan file from an older tool version is
40
+ refused too: rebuild it with `plan`. After a data-only restore or a
41
+ logical-replication move, reset the row version epoch (the row-version-epoch reference).
42
+
43
+ A promotion plan's `allow` also takes its listed `access:<table>`, `remove:<t>`,
44
+ `repair:<t>`, `delete:<t>.<constraint>` and `update:<t>.<constraint>` items; a
45
+ repair rewrites existing values with the fill expression shown.
46
+ A promotion is applied only with a valid rehearsal report: rehearse the plan on
47
+ a copy of the target with data first. Point the rehearsal at the copy through
48
+ the connection variable: `simetra apply --rehearse --database-url-env <VAR>`
49
+ on the command line, or an MCP server launched with
50
+ `simetra mcp --database-url-env <VAR>` (an MCP server's database is fixed at
51
+ launch). Make the copy from the target after the plan, restore it as the plan's
52
+ role with `pg_restore --no-owner`, on a server with the same PostgreSQL major
53
+ version, encoding and collation; otherwise the rehearsal is refused as not a
54
+ copy of the plan's target (`apply.target-changed`). Rehearsing on the target
55
+ itself is allowed, but it holds the target's locks for the whole run: make it
56
+ a deliberate choice of the owner, not a default. `apply` refuses without a
57
+ report (`apply.rehearsal-required`), with a stale one (`apply.rehearsal-stale`:
58
+ another plan, report format, server, ledger head, or not one row count per
59
+ promoted table), and when a table has rows on the target but none on the copy
60
+ (`apply.rehearsal-copy-empty`); it warns when the copy has fewer rows
61
+ (`apply.rehearsal-fewer-rows`) or when the statement timeout computed from the
62
+ report exceeds what Postgres accepts (`apply.rehearsal-timeout-unbounded`).
63
+
64
+ Which connection to use:
65
+
66
+ - Reads of the target (`introspect`, `diff`, `plan`) run in short read-only
67
+ transactions and work through a transaction-mode pooler.
68
+ - The shadow database of `diff` and `plan` needs a direct or session-mode
69
+ connection: it is created, reached by name and loaded with session settings
70
+ that a transaction-mode pooler is not guaranteed to keep. With a pooled target
71
+ connection, point `--shadow-url-env` at a direct one.
72
+ - A long `apply` wants a direct or session-mode connection too: a pooler may
73
+ cut the transaction with its own timeouts.
74
+
75
+ A changed plan file, changed metadata or a changed database refuses the
76
+ apply; plan again.
77
+
78
+ If `apply` reports `outcome unknown`, the connection was lost and the apply may
79
+ or may not have been committed. Never apply again blindly: look up the printed
80
+ apply id in the `apply_id` column of `simetra.ledger` first — a row means it was
81
+ committed.
@@ -5,8 +5,18 @@ package skills into `.agents/skills/` and `.claude/skills/` and writes the MCP
5
5
  server entry for the chosen agents. Run it from the project root — the
6
6
  directory the agent starts in, where `metadata/` lives.
7
7
 
8
+ When the agent starts in another directory (a monorepo root above the app),
9
+ name it with `--root`, or run `init` from there with the metadata directory as
10
+ the argument. The package is looked up from the metadata directory; the links
11
+ and configs go into the root, and the MCP entry names the metadata directory
12
+ relative to the root. A directory an own entry already names is kept. A
13
+ named metadata directory must exist, and on Windows it must be on the same
14
+ drive as the root.
15
+
8
16
  ```sh
9
17
  pnpm exec simetra init
18
+ pnpm exec simetra init --root ..
19
+ pnpm exec simetra init apps/app/metadata
10
20
  pnpm exec simetra init --agents claude,codex,cursor,vscode
11
21
  pnpm exec simetra init --dry-run
12
22
  pnpm exec simetra init --check --agents claude,codex
@@ -15,7 +25,7 @@ pnpm exec simetra init --check --agents claude,codex
15
25
  - Without `--agents` only Claude Code's `.mcp.json` is written. The skill
16
26
  links are made in both skill directories for every agent.
17
27
  - The links and configs belong in git. In CI run `init --check` with the same
18
- `--agents`: it exits 1 when a link or an MCP entry is missing or stale, and
28
+ `--agents`, `--root` and metadata directory: it exits 1 when a link or an MCP entry is missing or stale, and
19
29
  changes nothing.
20
30
  - `init` never overwrites what it does not own: a skill directory with the
21
31
  same name, or a `simetra` MCP entry with another command, is left alone and
@@ -0,0 +1,39 @@
1
+ # Row version epoch
2
+
3
+ Every row of a table with the mechanics trigger carries a `version` from one
4
+ database-wide sequence, `simetra.row_version`. A client keeps a row by its
5
+ version, so a version must never repeat for a key. The database gives the
6
+ client an epoch, `simetra.row_version_epoch()`; when it changes, the client drops
7
+ the versions it holds.
8
+
9
+ The epoch changes on its own when the server restarts, a volume snapshot or a
10
+ point in the past is restored, a failover moves the timeline, or the database
11
+ moves to a new cluster or a new database. It is `NULL` on a replica.
12
+
13
+ Two cases the database cannot see:
14
+
15
+ - **A data-only restore into the same database** (`pg_restore --data-only`,
16
+ `psql` from a dump). The dump brings back old sequence values and the old
17
+ epoch row.
18
+ - **A move by logical replication.** Sequences do not travel, so the new
19
+ sequence may sit below the versions in the rows.
20
+
21
+ After either, the schema owner runs the call below with the application stopped
22
+ and before its first read:
23
+
24
+ ```sql
25
+ SELECT simetra.reset_row_version_epoch();
26
+ ```
27
+
28
+ It seeds the sequence above every version in the mechanics tables and issues a
29
+ new epoch. Versions issued between the restore and the call may repeat: the
30
+ database does not guard that window.
31
+
32
+ Rules for your own SQL:
33
+
34
+ - Never set `synchronous_commit = off` after a row write in a debt unit. The
35
+ mechanics trigger raises the commit to synchronous; `off` makes it
36
+ asynchronous again, and a crash then loses issued versions without an epoch
37
+ change.
38
+ - Never write the `simetra.row_version_*` settings (`sql.debt-session-write`
39
+ warns).
@@ -0,0 +1,28 @@
1
+ # Search fields and mode
2
+
3
+ The object property `search` on a Catalog, a Document or a `CustomTable`
4
+ names what a search of the object looks at (a reference picker, a `contains`
5
+ or `startsWith` filter of a list read).
6
+
7
+ ```json
8
+ { "search": { "fields": ["description", "code"], "mode": "startsWith" } }
9
+ ```
10
+
11
+ - `fields`: logical names of header attributes, standard or custom. Omitted:
12
+ the default fields of the kind — a Catalog's presentation field
13
+ (`description`, or `code` with `mainPresentation: "Code"`; none when its
14
+ length is 0), a Document's `number`, a `CustomTable` none. An object with no
15
+ fields has no search.
16
+ - `mode`: `startsWith` or `contains`; `contains` when omitted.
17
+ - A field of type `String` or `Text` gets a stored derived column and an index
18
+ built by the platform (`<column>_search`); it is not an attribute, so leave
19
+ it out of metadata files and out of `fields`.
20
+ - `startsWith` is read through an index on a bounded prefix of the lowercased
21
+ value, with the exact condition on the full value beside it, so the result
22
+ is the same with or without the index. It is the mode to choose for a large
23
+ table.
24
+ - `contains` has no index: it scans the rows of the scope, so it stays fast
25
+ only for a scope up to about a hundred thousand rows, and a request needs a
26
+ scope equality. Without one the scan covers the whole table.
27
+ - Adding `search` to an adopted `CustomTable` adds the derived column in the
28
+ apply plan; it rewrites the table, so the plan marks it as a heavy step.