@niscorp/strata 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.
Files changed (48) hide show
  1. package/DESIGN.md +208 -0
  2. package/LICENSE +202 -0
  3. package/README.md +195 -0
  4. package/dist/check/index.cjs +223 -0
  5. package/dist/check/index.cjs.map +1 -0
  6. package/dist/check/index.d.cts +63 -0
  7. package/dist/check/index.d.ts +63 -0
  8. package/dist/check/index.js +4 -0
  9. package/dist/check/index.js.map +1 -0
  10. package/dist/chunk-EGFF63GA.js +16 -0
  11. package/dist/chunk-EGFF63GA.js.map +1 -0
  12. package/dist/chunk-HMT7HHFJ.js +156 -0
  13. package/dist/chunk-HMT7HHFJ.js.map +1 -0
  14. package/dist/chunk-ICWKTTKN.js +129 -0
  15. package/dist/chunk-ICWKTTKN.js.map +1 -0
  16. package/dist/chunk-MY3TGSV3.js +206 -0
  17. package/dist/chunk-MY3TGSV3.js.map +1 -0
  18. package/dist/chunk-U5CPF4LQ.js +175 -0
  19. package/dist/chunk-U5CPF4LQ.js.map +1 -0
  20. package/dist/documents-BjlM94Ea.d.cts +90 -0
  21. package/dist/documents-BjlM94Ea.d.ts +90 -0
  22. package/dist/index.cjs +370 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +16 -0
  25. package/dist/index.d.ts +16 -0
  26. package/dist/index.js +42 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/node/index.cjs +629 -0
  29. package/dist/node/index.cjs.map +1 -0
  30. package/dist/node/index.d.cts +19 -0
  31. package/dist/node/index.d.ts +19 -0
  32. package/dist/node/index.js +164 -0
  33. package/dist/node/index.js.map +1 -0
  34. package/dist/plan-BAewc8DG.d.ts +53 -0
  35. package/dist/plan-BEIlXVUt.d.cts +53 -0
  36. package/dist/postgres/index.cjs +333 -0
  37. package/dist/postgres/index.cjs.map +1 -0
  38. package/dist/postgres/index.d.cts +44 -0
  39. package/dist/postgres/index.d.ts +44 -0
  40. package/dist/postgres/index.js +145 -0
  41. package/dist/postgres/index.js.map +1 -0
  42. package/dist/upgrade/index.cjs +236 -0
  43. package/dist/upgrade/index.cjs.map +1 -0
  44. package/dist/upgrade/index.d.cts +54 -0
  45. package/dist/upgrade/index.d.ts +54 -0
  46. package/dist/upgrade/index.js +5 -0
  47. package/dist/upgrade/index.js.map +1 -0
  48. package/package.json +94 -0
package/DESIGN.md ADDED
@@ -0,0 +1,208 @@
1
+ # strata — design
2
+
3
+ Why it is shaped the way it is. The build plan lives in
4
+ [docs/plans/versioning.md](../../docs/plans/versioning.md); this is what was
5
+ decided and why, kept beside the code.
6
+
7
+ ## The problem it was built for
8
+
9
+ Every nisc artifact is JSON with a schema, and those artifacts are already
10
+ stored — `integration_actions.definition`, `vex_cache.dsl` and `prism_ir`,
11
+ atrium's bundles, lyra's theme layouts. Nothing recorded which grammar wrote
12
+ them. Underneath that, three packages created and altered their own tables on
13
+ every boot with `IF NOT EXISTS`, outside any ledger: moss added twelve columns
14
+ that way, tide dropped three. A deployment could not say what shape it was in,
15
+ and a later change had nowhere to go but another `IF NOT EXISTS`.
16
+
17
+ strata is one path for both: the documents stored in databases and written in
18
+ source files, and the tables a database holds.
19
+
20
+ ## Decisions
21
+
22
+ **Sequences per owner, versions by position.** tldraw's model: an append-only
23
+ list per owner, a version that is a count. A hand-bumped integer is a second
24
+ source of truth beside the list; a count cannot disagree with it. Owners are
25
+ namespaced so a package and an app never collide, and Kubernetes' lesson on
26
+ granularity applies — one sequence per *owner*, not per table and not one for
27
+ the world.
28
+
29
+ **One ledger for everyone.** Django's model: every package ships its own
30
+ migrations into the app's single ledger, ordered by the order given and bent by
31
+ explicit `dependsOn`. The order is deterministic — tldraw rebuilt its migration
32
+ system after ordering across sequences drifted between releases.
33
+
34
+ **Checksum the effect, not the prose.** The ledger stores a SHA-256 of each
35
+ migration's steps. Descriptions, `dependsOn` and full-line SQL comments are
36
+ excluded: rewording documentation is not editing history. Changing a step is —
37
+ the database already holds the old effect — and is refused (`EDITED`).
38
+
39
+ **Refuse, don't guess.** A database migrated by newer code (`TOO_NEW`), a hole
40
+ in the ledger, an unknown dependency, a cycle: each is a refusal with a
41
+ sentence, never a best effort. Verify mode refuses pending work, so a
42
+ production boot can require that a deploy step migrated first.
43
+
44
+ **One transaction, one lock.** A run takes `pg_advisory_xact_lock` on the
45
+ ledger's name, then creates the ledger if needed, reads it, plans and applies —
46
+ all in one transaction. Postgres DDL is transactional, so a failed step leaves
47
+ nothing behind. The lock comes first because two processes creating the ledger
48
+ at once race in the catalog before either reaches a row.
49
+
50
+ **Pure core, structural pool.** The plan is a pure function of sequences and
51
+ ledger rows; the runner is the only thing that touches a database, through the
52
+ `{ query, transaction }` shape nisc already passes everywhere. So the same code
53
+ runs in a server, a test and the showroom page (PGlite in the browser), and
54
+ checksums use WebCrypto rather than a Node module.
55
+
56
+ **Baselines converge.** Each package's first migration is exactly the
57
+ `IF NOT EXISTS` DDL its boot used to run. That makes adoption free: whatever
58
+ earlier shape a deployment is in, migration 1 lands the current one, keeps the
59
+ rows, and is recorded. No schema diffing, no "mark as applied" step that
60
+ assumes. Every package pins its baselines' checksums in a test, so an edit is
61
+ caught in CI rather than by a refusing production boot.
62
+
63
+ ## What moved when strata landed
64
+
65
+ moss's server now runs `nisc.moss` (integrations, their actions, the generation
66
+ pointer), `nisc.moss.sessions` (when the deployment uses moss's credential) and
67
+ the vex cache's sequence in one run, **before** introspection — as the tables
68
+ it replaced were. Two consequences, named rather than discovered later:
69
+
70
+ - The generation table used to be created *after* introspection; it is now
71
+ created before, and `strata_ledger` is a new table. Both enter the
72
+ introspected grant universe like every engine table (moss's stance: engine
73
+ tables are ordinary and grantable, and a grant is a charter's decision). A
74
+ charter selecting `*.read` reached them — and, it turned out, had always
75
+ reached moss's `integrations` (integration key hashes). relay's charter check
76
+ resolved against relay's tables only, so it never showed. Fixed in relay: the
77
+ check builds the universe the way boot does, and `*.read` roles deny the
78
+ engine's tables. Any app granting a data wildcard should do the same.
79
+ - `initIntegrations`, `initSessions`, `cache.init()` and the tide store's
80
+ `migrate` keep their names and now go through the ledger, so a host that is
81
+ not moss's server gets the same guarantees.
82
+
83
+ ## Documents (S2)
84
+
85
+ **Two kinds of owner.** Tables live in one database, so their version is the
86
+ database's — a ledger. Documents travel: an add-on built on older code submits
87
+ older documents, a row written by one replica is read by another, an artifact
88
+ sits in a repo for a year. Their version has to travel with them — a stamp per
89
+ document. A sequence owns one or the other; the same number cannot mean both.
90
+
91
+ **Version vector, not one number.** tldraw's answer to nested, pluggable
92
+ formats: the stamp names every grammar the writer spoke (`nisc.nova`,
93
+ `nisc.prism`, the app's `acme.kit`), so a kit's props and nova's layout evolve on
94
+ their own schedules and nothing composes by hand.
95
+
96
+ **The grammar owns the nesting; the migration owns one node.** Embedding paths
97
+ are the grammar's declaration of where documents sit inside documents. The
98
+ walker applies each step to every document of its kind, deepest first, re-reading
99
+ each node from the current document so a parent sees — and keeps — its children
100
+ already rewritten (the first implementation captured targets up front and wrote
101
+ stale parents over rewritten children; a test caught it). The consequence is
102
+ the useful one: a migration is flat. The relay rename that needed 22.5 KB of
103
+ unrolled Prism as a whole-tree transform is a dozen lines as a per-node one, and
104
+ Prism needs no recursion of its own for anything a grammar's embeddings describe.
105
+
106
+ **Two wildcards.** `*` crosses a record's values, `[]` an array's items. nova's
107
+ `children` is a single node or an array; one wildcard for both would treat a
108
+ lone child's `props` as a record of layouts.
109
+
110
+ **Injected transform.** strata knows nothing of Prism: a document step's
111
+ `transform` is opaque data run by the evaluator the host injects — nova's own
112
+ socket shape, `(config, source) => unknown`. moss injects Prism, so a
113
+ migration runs through the engine that runs endpoints, with the same guarantee
114
+ that no code executes. That is what makes a third party's migration safe to run.
115
+
116
+ **Refuse ahead, upgrade behind.** Strict grammars make every addition break
117
+ older readers, so a document ahead of the code on any grammar is `TOO_NEW` — at
118
+ boot a refusal to start, at intake "the host must be updated first", on a read
119
+ path the one action left out with a sentence. The reader upgrades first.
120
+
121
+ **Not every table of documents is a store.** `vex_cache` holds DSL and compiled
122
+ Prism IR, but its protected rows are re-seeded from source on every boot and its
123
+ generated rows are a cache invalidated by schema fingerprint and `irVersion`. It
124
+ is not stamped: there is nothing there to preserve across a grammar change.
125
+ `integration_actions` is — its rows are the only copy of what an add-on submitted.
126
+
127
+ ## Prism as the migration language (S3)
128
+
129
+ **Why Prism, not a second grammar.** Cambria proved migrations-as-data with a
130
+ closed lens vocabulary, but nisc already has one transform language (the
131
+ toolbox: Prism is "every transform"), and a second would be a second thing to
132
+ version. Prism gained what migrations need — `$has` (presence, not
133
+ non-null-ness), `$renameKeys` (order kept), `$update` (one deep path),
134
+ `$assert` (refuse with a sentence), `$walk` (rules over every node) — and a
135
+ config stays data: stored as a row, run in any host, safe when a third party
136
+ wrote it.
137
+
138
+ **The walker made `$walk` rarer than expected.** Embeddings already find every
139
+ document of a kind at any depth, so most migrations are a flat rule over one
140
+ node. `$walk` is for what a grammar's embeddings do not describe: reaching
141
+ inside a Prism config, or a free-form tree.
142
+
143
+ **A migration cannot migrate the language it is written in.** So the base case
144
+ is a rule, not a mechanism: a Prism op is never removed or reshaped; an old form
145
+ stays as sugar. `EVERY_OP_EVER` in Prism's tests fails on a removal.
146
+ `irVersion` stays 1 — it versions the IR's container; the op set is versioned by
147
+ `nisc.prism`.
148
+
149
+ ## The gate (S4)
150
+
151
+ **A snapshot only says something moved.** Each kind's JSON Schema, taken through
152
+ the schema's own Standard JSON Schema hook, recorded per version as the
153
+ validator wrote it. Same version, different schema: a migration is owed. No
154
+ JSON Schema compatibility classifier is trusted to judge — none is reliable
155
+ (2026).
156
+
157
+ **The comparison ignores prose and spelling, the record keeps both.** Before
158
+ comparing, both sides lose the `description` keyword (a reworded `.describe()`
159
+ is not a grammar change — but a field named `description` is) and are read in
160
+ one spelling: definitions inlined unless recursive, `allOf: [{ $ref }]` as
161
+ `$ref`, a union of bare types as a type list. zod 4.3 → 4.6 respelled both nisc
162
+ grammars without changing either; that must not be a migration. Keeping the
163
+ normalizing out of the record means strata can refine it without touching a
164
+ recorded file.
165
+
166
+ **A snapshot is a fingerprint, not history.** The grammar version is history —
167
+ its migrations and the documents captured at its stamp. The snapshot is what a
168
+ RECORDER (the validator, then strata) made of it, and a recorder can be wrong
169
+ or improve: zod 4.3 described Prism's tuples as open, and strata once dropped a
170
+ field named `description`. Then the current version is re-recorded —
171
+ `pnpm strata:snapshot --rebaseline`, refused unless the corpus passes, in a
172
+ commit that changes nothing else in the grammar. Not a marker migration: that
173
+ would bump every app's lock and every stored stamp to say nothing happened.
174
+
175
+ **The corpus judges.** Real documents from the lab apps, captured at their
176
+ stamp, must upgrade to the current grammars and parse the current strict
177
+ schemas. That is what caught a breaking rename in the rehearsal: 122 real
178
+ documents would have failed. An early-stamp corpus file is history.
179
+
180
+ **Arrays in schemas are sets.** A union's `anyOf` gains a branch and every index
181
+ shifts, so the gate's diff matches schema-array elements by what they describe
182
+ (for Prism's union, the op) — its first real catch, Prism's own grammar change,
183
+ read like a changelog because of it. Document diffs stay positional:
184
+ `layout.children[1]` is how a person finds the edit.
185
+
186
+ ## Source (S5)
187
+
188
+ **No codemods.** A codemod would have to understand every way a person writes
189
+ an object. strata instead fixes the TARGET: the exact JSON each artifact must
190
+ become, and a report of where (the file its id is in, and — found by searching
191
+ the source for the values that change — the file the edit actually lives in,
192
+ usually an imported layout).
193
+
194
+ **Verify is exact, and it is the only way the lock moves.** Every planned
195
+ artifact equals its expected JSON (key order aside — that is how a person
196
+ happened to write it), every untouched one is still one no migration would
197
+ change, nothing was added or removed since the plan. A person, an agent, a
198
+ script — anyone may edit; the check does not trust any of them. A migration
199
+ whose result fails the current schema stops the plan: no edit could pass.
200
+
201
+ **The lock is the truth, not a formality.** The lab apps' locks were written at
202
+ `nisc.prism 0` — their source predated the marker — and moved through the loop.
203
+ `init` exists only for a source that never had one.
204
+
205
+ ## Open
206
+
207
+ npm publishing (every package ships its first version with this in it);
208
+ lyceum and midas capture their own corpus and keep their own locks.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # @niscorp/strata
2
+
3
+ Versions for nisc. Every document an app writes — a screen, a query, a
4
+ transform — carries a **stamp**: how far along each grammar its writer was.
5
+ Read by newer code, it is upgraded through the migrations in between; read by
6
+ older code, it is refused (`TOO_NEW`), never guessed at. See
7
+ [Documents](#documents).
8
+
9
+ The tables those documents live in follow the same rules. A **sequence** is an
10
+ append-only list of migrations owned by one thing — a grammar's documents, a
11
+ package's tables, an app's tables. For tables, strata applies what is pending
12
+ **once**, records it in a **ledger**, and refuses a database whose history no
13
+ longer matches the code.
14
+
15
+ ```bash
16
+ pnpm add @niscorp/strata zod
17
+ ```
18
+
19
+ ```ts
20
+ import { defineSequence } from '@niscorp/strata';
21
+ import { migrate } from '@niscorp/strata/postgres';
22
+
23
+ export const appSequence = defineSequence({
24
+ id: 'acme.app',
25
+ migrations: [
26
+ { description: 'People', steps: [{ kind: 'sql', sql: 'CREATE TABLE people (id text PRIMARY KEY, name text NOT NULL)' }] },
27
+ { description: 'People can be archived', steps: [{ kind: 'sql', sql: 'ALTER TABLE people ADD COLUMN archived_at timestamptz' }] },
28
+ ],
29
+ });
30
+
31
+ await migrate(pool, [appSequence]); // applies what is pending, records it
32
+ await migrate(pool, [appSequence], { mode: 'verify' }); // refuses if anything is pending
33
+ ```
34
+
35
+ Under moss you rarely call it: the server runs every owner's sequence — moss's
36
+ own tables, the sessions table, the vex cache — in one ledgered run at boot.
37
+
38
+ ## The rules
39
+
40
+ - **A migration's number is its position.** A sequence's version is its length.
41
+ Nobody bumps a number; you append.
42
+ - **An applied migration is history.** Its steps are checksummed into the
43
+ ledger; change them and every database that ran it refuses to boot
44
+ (`EDITED`). Append a new migration instead. Descriptions, `dependsOn` and
45
+ full-line `--` comments are not part of the checksum — rewording is not
46
+ editing.
47
+ - **One statement per step.** A driver that prepares statements (PGlite, `pg`
48
+ with parameters) refuses a string carrying several. For a DDL file, use
49
+ `sqlSteps(ddl)` — never split on every `;`: a comment containing one is cut
50
+ in two and its tail becomes SQL (lyceum's schema would have failed at boot).
51
+ - **A run is one transaction** under an advisory lock. A step throws, nothing
52
+ from the run happened — Postgres DDL is transactional. Two processes booting
53
+ at once serialize; the second finds the work done.
54
+ - **A database migrated by newer code is refused** (`TOO_NEW`), never guessed at.
55
+ - **Sequence ids are namespaced**: `nisc.vex.cache`, `nisc.moss`, `acme.app`.
56
+ Order across sequences is the order you pass them, bent only by `dependsOn`
57
+ (`"nisc.moss/1"`) — deterministic, the same every time.
58
+
59
+ ## API
60
+
61
+ **`@niscorp/strata`** — pure, storage-blind.
62
+
63
+ | | |
64
+ |---|---|
65
+ | `defineSequence(seq)` | Type-checks a sequence where it is written. |
66
+ | `prepare(sequences)` | Parses (Zod, at the boundary), numbers and checksums. Throws `INVALID_SEQUENCE`. |
67
+ | `planMigrations(prepared, ledger)` | Pure: what is pending, in order, and every problem (`EDITED`, `TOO_NEW`, `UNKNOWN_DEPENDENCY`, `CYCLE`). |
68
+ | `checksumOf(migration)` | SHA-256 over the steps (WebCrypto — Node ≥ 22 and every browser). |
69
+ | `sqlSteps(ddl)` | A DDL file as one step per statement — splits only at a `;` that ends a line of SQL, never inside a comment. |
70
+ | `SequenceSchema`, `MigrationSchema`, `StepSchema` | The grammar, as Zod. |
71
+ | `StrataError` | `code` + a sentence + `details`. |
72
+
73
+ **`@niscorp/strata/postgres`**
74
+
75
+ | | |
76
+ |---|---|
77
+ | `migrate(pool, sequences, { mode, table, schema })` | The run. `mode: 'apply'` (default) or `'verify'`. Returns `{ applied, plan }`. |
78
+ | `status(pool, sequences, options)` | The plan, read-only — creates nothing, not even the ledger. |
79
+ | `readLedger(pool, options)` | The ledger's rows; empty for a database never migrated. |
80
+ | `ledgerDdl(options)` | The ledger table's DDL — the one statement strata runs outside a ledger. |
81
+
82
+ The pool is structural — `{ query, transaction }`, the shape vex's PGlite pool
83
+ and a wrapped `pg` pool already have. A pool without `transaction` is refused
84
+ (`NO_TRANSACTION`): a run must land whole or not at all.
85
+
86
+ The ledger defaults to `strata_ledger` in the connection's schema, beside the
87
+ app's tables; `table` and `schema` move it.
88
+
89
+ ## Adopting a database from before strata
90
+
91
+ Packages used to converge their tables on every boot with
92
+ `CREATE … IF NOT EXISTS` + `ADD COLUMN IF NOT EXISTS`. Each package's migration
93
+ 1 is that DDL, verbatim — so it **is** the adoption: run once over any earlier
94
+ shape of the tables it lands the current one, keeps the rows, and is recorded
95
+ so it never runs again. From then on changes are plain appended migrations.
96
+
97
+ ## Documents
98
+
99
+ A **grammar** sequence owns document kinds instead of tables. It declares its
100
+ kinds and where other documents nest inside them (its **embeddings**), and its
101
+ migrations are **document steps** — a transform over one document of one kind.
102
+
103
+ ```ts
104
+ export const NOVA_SEQUENCE = {
105
+ id: 'nisc.nova',
106
+ documents: {
107
+ action: { embeds: { layout: 'nisc.nova/layout', 'endpoints.*.request': 'nisc.prism/config' } },
108
+ layout: { embeds: { children: 'nisc.nova/layout', 'children[]': 'nisc.nova/layout', then: 'nisc.nova/layout' } },
109
+ },
110
+ migrations: [],
111
+ };
112
+
113
+ // An app's kit: Button's `label` prop is now `text` — one flat node at a time.
114
+ export const kit = {
115
+ id: 'acme.kit',
116
+ migrations: [{ description: 'Button: label → text', steps: [{ kind: 'document', at: 'nisc.nova/layout', transform: renameLabelPrismConfig }] }],
117
+ };
118
+
119
+ const upgrader = await createUpgrader([NOVA_SEQUENCE, PRISM_SEQUENCE, kit], { transform: prismEvaluate });
120
+ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nisc.nova/action', stamp: row.grammar });
121
+ ```
122
+
123
+ - **A document carries a stamp** — `{ "nisc.nova": 3, "acme.kit": 1 }`, how far
124
+ along each grammar its writer was — and is upgraded where it is read. Grammars
125
+ are never recorded in a ledger: documents travel (an add-on built on older
126
+ code submits older documents), so their version travels with them. One
127
+ sequence owns tables or documents, never both.
128
+ - **The walker does the recursion.** Embedding paths use `key`, `*` (every
129
+ value of a record) and `[]` (every item of an array) — kept apart because
130
+ nova's `children` is a lone node or an array. Every document of a step's kind
131
+ is found at any depth and rewritten on its own, deepest first; a transform
132
+ only ever sees one node.
133
+ - **The transform is injected** — `(config, source) => unknown`, nova's socket.
134
+ Under moss it is Prism's `evaluate`; a migration runs exactly like an endpoint.
135
+ The source is `{ document, path }`.
136
+ - **No stamp** (`{}`, `null`) reads as the start of every grammar. **Ahead of
137
+ the code** on any grammar is refused, `TOO_NEW`: the reader upgrades first.
138
+
139
+ | | |
140
+ |---|---|
141
+ | `createUpgrader(grammars, { transform })` | `{ stamp, upgrade, locate, behind }` — the stamp a document written now carries; upgrade one; every document inside one, by kind; is a stamp behind (throws if ahead). |
142
+ | `upgradeStore(pool, store, upgrader)` | `@niscorp/strata/postgres`. Rewrites every row of a table holding documents that is behind, in one transaction; a row from newer code refuses the pass. |
143
+
144
+ ## The check
145
+
146
+ **`@niscorp/strata/check`** — the gate a grammar change has to pass. Pure; the
147
+ host keeps the files.
148
+
149
+ | | |
150
+ |---|---|
151
+ | `snapshotOf(sequence, schemas)` | Each kind's JSON Schema, through the schema's own Standard JSON Schema hook (Zod ≥ 4.2, Valibot, ArkType), as the validator wrote it — keys sorted, nothing removed. `schemas` must cover exactly the grammar's kinds. |
152
+ | `compareSnapshot(recorded, current)` | `same`, `missing`, or `changed` with short diff lines (`+ properties.retry`, `~ required[0]: "id" → "key"`). Changed at the same version = a migration is owed. Both sides are compared without prose (the `description` keyword — a field named `description` is grammar) and in one spelling (definitions inlined unless recursive, `allOf: [{ $ref }]` as `$ref`, a union of bare types as a type list), so a reworded `.describe()` or a validator's respelling is not a change. |
153
+ | `snapshotText(snapshot)` | Stable file text: sorted keys. |
154
+ | `checkCorpus(upgrader, schemas, documents)` | Every captured document, upgraded from its stamp, must pass its kind's current schema. |
155
+
156
+ A snapshot only says *something moved*; the corpus of real documents is the
157
+ judge of whether old ones survive. nisc runs both on its own grammars in CI
158
+ (`pnpm check:grammars`; records in the repo's `strata/` directory).
159
+
160
+ ## Source — `strata upgrade`
161
+
162
+ Artifacts written in an app's TypeScript are not rewritten by machine — a
163
+ codemod would have to understand every way a person writes an object. strata
164
+ works out EXACTLY what each must become, and holds the edit to it.
165
+
166
+ ```ts
167
+ // the app's src/dev/strata.ts — it lists its artifacts; strata does the rest
168
+ import { runSourceUpgrade } from '@niscorp/strata/node';
169
+ process.exit(await runSourceUpgrade({ root, grammars, transform: prismTransform, schemas, documents }, process.argv.slice(2)));
170
+ ```
171
+
172
+ ```bash
173
+ pnpm strata status --check # the source against the installed grammars (CI)
174
+ pnpm strata upgrade # .strata/upgrade/: expected JSON + REPORT.md (file, "look in", migrations, diff)
175
+ pnpm strata verify # the edited source must equal it; then strata.lock.json moves
176
+ ```
177
+
178
+ `strata.lock.json` (committed) is the source's stamp. `upgrade` plans from it:
179
+ artifacts a migration changes get their expected JSON and a positional diff;
180
+ the rest are recorded as untouched. `verify` passes only when every planned
181
+ artifact equals its expected JSON (key order aside), every untouched one is
182
+ still one no migration would change, and nothing was added or removed since
183
+ the plan — then the lock moves and the work files go. A migration whose result
184
+ fails the current schema stops the plan: no edit could pass. `init` records a
185
+ lock for a source that has never had one.
186
+
187
+ | | |
188
+ |---|---|
189
+ | `@niscorp/strata/upgrade` | Pure: `planSourceUpgrade`, `verifySourceUpgrade`, `renderReport`, `changedStrings`. |
190
+ | `@niscorp/strata/node` | `runSourceUpgrade(options, argv)` — the lock, the work directory, the report, "look in" hints from the source. |
191
+ See [DESIGN.md](./DESIGN.md) and [the plan](../../docs/plans/versioning.md).
192
+
193
+ ## License
194
+
195
+ Apache-2.0