@rulvar/store-conformance 1.0.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.
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.
@@ -0,0 +1,75 @@
1
+ import { JournalEntry, JournalStore, LeasableStore } from "@rulvar/core";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Conformance kit surface (M2-T11, DEF-4): an executable suite
6
+ * parameterized by a store factory. A store implementation passes or it
7
+ * is not a rulvar store (docs/11, section "Conformance tier"; docs/03,
8
+ * section "Conformance obligations").
9
+ */
10
+ /** One mandatory check; `run` rejects with a descriptive Error on violation. */
11
+ interface ConformanceCheck {
12
+ id: string;
13
+ title: string;
14
+ run(): Promise<void>;
15
+ }
16
+ interface ConformanceSuite {
17
+ name: string;
18
+ checks: readonly ConformanceCheck[];
19
+ /** Runs every check sequentially; throws on the first violation. */
20
+ run(): Promise<void>;
21
+ }
22
+ /**
23
+ * The factory contract: every call MUST return a fresh, isolated store
24
+ * (checks run against independent instances; a JsonlFileStore factory
25
+ * uses a fresh temp directory per call).
26
+ */
27
+ type StoreFactory<S> = () => Promise<S> | S;
28
+ /** Structural subset of the Vitest/Jest registration API. */
29
+ interface TestRegistrar {
30
+ describe(name: string, factory: () => void): void;
31
+ it(name: string, fn: () => Promise<void>): void;
32
+ }
33
+ /** Registers the suite as one `describe` block with one `it` per check. */
34
+ declare function registerConformance(suite: ConformanceSuite, api: TestRegistrar): void;
35
+ declare function makeSuite(name: string, checks: readonly ConformanceCheck[]): ConformanceSuite;
36
+ /** Canonical JSON with recursively sorted keys (fold-state hashing). */
37
+ declare function stableStringify(value: unknown): string;
38
+ //#endregion
39
+ //#region src/journal.d.ts
40
+ declare function journalStoreConformance(mk: StoreFactory<JournalStore>): ConformanceSuite;
41
+ //#endregion
42
+ //#region src/leasable.d.ts
43
+ declare function leasableStoreConformance(mk: StoreFactory<LeasableStore>, options?: {
44
+ /**
45
+ * The store's configured lease TTL, when known: enables the
46
+ * wall-clock expiry and renew-keeps-held checks.
47
+ */
48
+ ttlMs?: number;
49
+ }): ConformanceSuite;
50
+ //#endregion
51
+ //#region src/fixtures/golden-fold.d.ts
52
+ /**
53
+ * seq 0 agent spawn (running; abandoned by seq 6)
54
+ * seq 1 suspended external gate-a under the spawn's child scope
55
+ * seq 2 suspended external gate-b at the root
56
+ * seq 3 resolution of gate-a: schema-INVALID (never closes)
57
+ * seq 4 resolution of gate-a: applied
58
+ * seq 5 resolution of gate-a: noop (already_resolved)
59
+ * seq 6 abandon of the spawn: applied (covers the agent:0 subtree)
60
+ * seq 7 resolution of gate-b: applied (root scope, not covered)
61
+ * seq 8 abandon of gate-b: noop (already_resolved; first-closing-wins)
62
+ * seq 9 abandon of the spawn again: noop (target_abandoned)
63
+ */
64
+ declare const GOLDEN_FOLD_JOURNAL: readonly JournalEntry[];
65
+ /**
66
+ * Materializes the observable fold state of a journal: ref-entry
67
+ * classifications (invalid details excluded: validator message wording is
68
+ * not contractual), suspension states, and per-seq abandon coverage.
69
+ */
70
+ declare function materializeFoldState(entries: readonly JournalEntry[]): Record<string, unknown>;
71
+ declare function foldStateSha256(entries: readonly JournalEntry[]): string;
72
+ /** The reference hash; computed once from the kernel fold and frozen. */
73
+ declare const GOLDEN_FOLD_STATE_SHA256 = "81e6ccff549fb3e6c1de4d34ba65b912162eba6f66403b5d5f23a3e1ec69243c";
74
+ //#endregion
75
+ export { type ConformanceCheck, type ConformanceSuite, GOLDEN_FOLD_JOURNAL, GOLDEN_FOLD_STATE_SHA256, type StoreFactory, type TestRegistrar, foldStateSha256, journalStoreConformance, leasableStoreConformance, makeSuite, materializeFoldState, registerConformance, stableStringify };
package/dist/index.js ADDED
@@ -0,0 +1,588 @@
1
+ import { LeaseHeldError, Replayer, ResolutionFold, agentScope, buildDeriverRegistry, deriveContentKey, dispositionHook } from "@rulvar/core";
2
+ import { createHash } from "node:crypto";
3
+ //#region src/types.ts
4
+ /** Registers the suite as one `describe` block with one `it` per check. */
5
+ function registerConformance(suite, api) {
6
+ api.describe(suite.name, () => {
7
+ for (const check of suite.checks) api.it(`${check.id}: ${check.title}`, () => check.run());
8
+ });
9
+ }
10
+ function makeSuite(name, checks) {
11
+ return {
12
+ name,
13
+ checks,
14
+ async run() {
15
+ for (const check of checks) await check.run();
16
+ }
17
+ };
18
+ }
19
+ /** Assertion helper: conformance failures are plain Errors naming the check. */
20
+ function ensure(condition, checkId, message) {
21
+ if (!condition) throw new Error(`store-conformance ${checkId}: ${message}`);
22
+ }
23
+ /** Canonical JSON with recursively sorted keys (fold-state hashing). */
24
+ function stableStringify(value) {
25
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
26
+ if (typeof value === "object" && value !== null) {
27
+ const record = value;
28
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
29
+ }
30
+ return JSON.stringify(value) ?? "null";
31
+ }
32
+ //#endregion
33
+ //#region src/fixtures/golden-fold.ts
34
+ /**
35
+ * Golden fold-state fixture (M2-T11; docs/03, section "Conformance
36
+ * obligations"): a hand-authored journal with applied, noop, and invalid
37
+ * resolutions plus applied and noop abandons. Folding it through the
38
+ * kernel MUST produce a fold state whose canonical hash equals
39
+ * GOLDEN_FOLD_STATE_SHA256 on every store implementation: a store cannot
40
+ * influence replay semantics.
41
+ *
42
+ * FROZEN fixture (docs/11, section "Frozen journal fixtures"): any edit
43
+ * requires an explicit hashVersion-bump changeset
44
+ * (scripts/check-frozen-fixtures.mjs).
45
+ */
46
+ function entry(partial) {
47
+ return {
48
+ hashVersion: 2,
49
+ scope: "",
50
+ key: `golden-${partial.seq}`,
51
+ ordinal: 0,
52
+ kind: "external",
53
+ status: "suspended",
54
+ spanId: "golden-span",
55
+ startedAt: (/* @__PURE__ */ new Date(17e11 + partial.seq * 1e3)).toISOString(),
56
+ ...partial
57
+ };
58
+ }
59
+ /**
60
+ * seq 0 agent spawn (running; abandoned by seq 6)
61
+ * seq 1 suspended external gate-a under the spawn's child scope
62
+ * seq 2 suspended external gate-b at the root
63
+ * seq 3 resolution of gate-a: schema-INVALID (never closes)
64
+ * seq 4 resolution of gate-a: applied
65
+ * seq 5 resolution of gate-a: noop (already_resolved)
66
+ * seq 6 abandon of the spawn: applied (covers the agent:0 subtree)
67
+ * seq 7 resolution of gate-b: applied (root scope, not covered)
68
+ * seq 8 abandon of gate-b: noop (already_resolved; first-closing-wins)
69
+ * seq 9 abandon of the spawn again: noop (target_abandoned)
70
+ */
71
+ const GOLDEN_FOLD_JOURNAL = [
72
+ entry({
73
+ seq: 0,
74
+ kind: "agent",
75
+ status: "running"
76
+ }),
77
+ entry({
78
+ seq: 1,
79
+ scope: "agent:0",
80
+ value: {
81
+ key: "gate-a",
82
+ schema: {
83
+ type: "object",
84
+ additionalProperties: false,
85
+ required: ["ok"],
86
+ properties: { ok: { type: "boolean" } }
87
+ }
88
+ }
89
+ }),
90
+ entry({
91
+ seq: 2,
92
+ value: { key: "gate-b" }
93
+ }),
94
+ entry({
95
+ seq: 3,
96
+ kind: "resolution",
97
+ status: "ok",
98
+ ref: 1,
99
+ scope: "agent:0",
100
+ resolution: {
101
+ target: 1,
102
+ by: "external",
103
+ value: { ok: "yes" }
104
+ }
105
+ }),
106
+ entry({
107
+ seq: 4,
108
+ kind: "resolution",
109
+ status: "ok",
110
+ ref: 1,
111
+ scope: "agent:0",
112
+ resolution: {
113
+ target: 1,
114
+ by: "operator",
115
+ value: { ok: true }
116
+ }
117
+ }),
118
+ entry({
119
+ seq: 5,
120
+ kind: "resolution",
121
+ status: "ok",
122
+ ref: 1,
123
+ scope: "agent:0",
124
+ resolution: {
125
+ target: 1,
126
+ by: "timeout",
127
+ value: { ok: false }
128
+ }
129
+ }),
130
+ entry({
131
+ seq: 6,
132
+ kind: "abandon",
133
+ status: "ok",
134
+ ref: 0,
135
+ abandon: {
136
+ target: 0,
137
+ authorizedBy: 0,
138
+ reason: "golden abandon"
139
+ }
140
+ }),
141
+ entry({
142
+ seq: 7,
143
+ kind: "resolution",
144
+ status: "ok",
145
+ ref: 2,
146
+ resolution: {
147
+ target: 2,
148
+ by: "external",
149
+ value: { go: 1 }
150
+ }
151
+ }),
152
+ entry({
153
+ seq: 8,
154
+ kind: "abandon",
155
+ status: "ok",
156
+ ref: 2,
157
+ abandon: {
158
+ target: 2,
159
+ authorizedBy: 6,
160
+ reason: "late abandon over a resolved gate"
161
+ }
162
+ }),
163
+ entry({
164
+ seq: 9,
165
+ kind: "abandon",
166
+ status: "ok",
167
+ ref: 0,
168
+ abandon: {
169
+ target: 0,
170
+ authorizedBy: 6,
171
+ reason: "repeat abandon"
172
+ }
173
+ })
174
+ ];
175
+ /**
176
+ * Materializes the observable fold state of a journal: ref-entry
177
+ * classifications (invalid details excluded: validator message wording is
178
+ * not contractual), suspension states, and per-seq abandon coverage.
179
+ */
180
+ function materializeFoldState(entries) {
181
+ const fold = new ResolutionFold(entries);
182
+ const abandonFold = fold.abandonFold;
183
+ const classifications = {};
184
+ const suspensions = {};
185
+ const abandoned = {};
186
+ for (const item of entries) {
187
+ abandoned[String(item.seq)] = abandonFold.isAbandoned(item.seq);
188
+ const classification = fold.classificationOf(item.seq);
189
+ if (classification !== void 0) classifications[String(item.seq)] = classification.classification === "invalid" ? { classification: "invalid" } : classification;
190
+ if (item.status === "suspended") suspensions[String(item.seq)] = fold.suspensionState(item.seq);
191
+ }
192
+ return {
193
+ classifications,
194
+ suspensions,
195
+ abandoned
196
+ };
197
+ }
198
+ function foldStateSha256(entries) {
199
+ return createHash("sha256").update(stableStringify(materializeFoldState(entries)), "utf8").digest("hex");
200
+ }
201
+ /** The reference hash; computed once from the kernel fold and frozen. */
202
+ const GOLDEN_FOLD_STATE_SHA256 = "81e6ccff549fb3e6c1de4d34ba65b912162eba6f66403b5d5f23a3e1ec69243c";
203
+ //#endregion
204
+ //#region src/journal.ts
205
+ /**
206
+ * journalStoreConformance (M2-T11, DEF-4): the executable definition of
207
+ * the JournalStore seam. Mandatory checks per docs/03, section
208
+ * "Conformance obligations" and docs/11, section "Conformance tier":
209
+ * A1 append atomicity, A2 total per-run order, A3 read-your-writes,
210
+ * A4 opaque payload, meta separation, the golden fold-state fixture, the
211
+ * end-to-end decide-once oracle, and the abandon fixture (zero live
212
+ * classes inside a skipped subtree, zero ledger increment).
213
+ *
214
+ * The oracle and the abandon fixture drive the kernel (Replayer,
215
+ * ResolutionFold, the DEF-1 predicate) directly over the store under
216
+ * test, in strict mode, so "zero live calls" holds by construction: no
217
+ * dispatch surface exists below the kernel. The engine-level variants
218
+ * (FakeAdapter call counters) live in the M2 cassette suite
219
+ * (@rulvar/testing).
220
+ */
221
+ const RUN$1 = "conformance-run";
222
+ function baseEntry(seq, overrides) {
223
+ return {
224
+ hashVersion: 2,
225
+ seq,
226
+ scope: "",
227
+ key: `conf-key-${seq}`,
228
+ ordinal: 0,
229
+ kind: "step",
230
+ status: "ok",
231
+ value: { seq },
232
+ spanId: "conf-span",
233
+ startedAt: (/* @__PURE__ */ new Date(17e11 + seq * 1e3)).toISOString(),
234
+ ...overrides
235
+ };
236
+ }
237
+ function sameEntry(a, b) {
238
+ return stableStringify(a) === stableStringify(b);
239
+ }
240
+ function meta(runId, overrides) {
241
+ return {
242
+ runId,
243
+ status: "running",
244
+ updatedAt: (/* @__PURE__ */ new Date(17e11)).toISOString(),
245
+ ...overrides
246
+ };
247
+ }
248
+ function journalStoreConformance(mk) {
249
+ return makeSuite("journalStoreConformance", [
250
+ {
251
+ id: "a1-append-atomicity",
252
+ title: "an append is all-or-nothing; a torn write is never observable",
253
+ async run() {
254
+ const store = await mk();
255
+ const big = "x".repeat(8192);
256
+ const submitted = Array.from({ length: 12 }, (_, i) => baseEntry(i, { value: {
257
+ seq: i,
258
+ blob: `${big}-${i}`,
259
+ sentinel: "END-OF-ENTRY"
260
+ } }));
261
+ const appends = submitted.map((item) => store.append(RUN$1, item));
262
+ const midLoads = [store.load(RUN$1), store.load(RUN$1)];
263
+ await Promise.all([...appends, ...midLoads]);
264
+ for (const seen of await Promise.all(midLoads)) for (const item of seen) {
265
+ const original = submitted.find((candidate) => candidate.seq === item.seq);
266
+ ensure(original !== void 0 && sameEntry(item, original), "a1-append-atomicity", `a load observed a torn or foreign entry at seq ${item.seq}`);
267
+ }
268
+ const loaded = await store.load(RUN$1);
269
+ ensure(loaded.length === submitted.length, "a1-append-atomicity", `expected ${submitted.length} whole entries, loaded ${loaded.length}`);
270
+ for (const item of loaded) {
271
+ const original = submitted.find((candidate) => candidate.seq === item.seq);
272
+ ensure(original !== void 0 && sameEntry(item, original), "a1-append-atomicity", `loaded entry seq ${item.seq} does not equal the appended entry`);
273
+ }
274
+ }
275
+ },
276
+ {
277
+ id: "a2-total-order",
278
+ title: "load returns the order of successful appends, stable across loads",
279
+ async run() {
280
+ const store = await mk();
281
+ const entries = Array.from({ length: 10 }, (_, i) => baseEntry(i));
282
+ for (const item of entries) await store.append(RUN$1, item);
283
+ const first = await store.load(RUN$1);
284
+ ensure(first.map((item) => item.seq).join(",") === entries.map((item) => item.seq).join(","), "a2-total-order", `sequential appends loaded out of order: ${first.map((item) => item.seq).join(",")}`);
285
+ await Promise.all(Array.from({ length: 8 }, (_, i) => store.append(RUN$1, baseEntry(10 + i))));
286
+ const second = await store.load(RUN$1);
287
+ const third = await store.load(RUN$1);
288
+ ensure(second.map((item) => item.seq).join(",") === third.map((item) => item.seq).join(","), "a2-total-order", "two loads of the same run disagree on entry order");
289
+ ensure(second.length === 18 && new Set(second.map((item) => item.seq)).size === 18, "a2-total-order", "concurrent appends were lost or duplicated");
290
+ ensure(second.slice(0, 10).map((item) => item.seq).join(",") === entries.map((item) => item.seq).join(","), "a2-total-order", "later appends reordered the existing prefix");
291
+ }
292
+ },
293
+ {
294
+ id: "a3-read-your-writes",
295
+ title: "an acknowledged append is visible to an immediately following load",
296
+ async run() {
297
+ const store = await mk();
298
+ for (let i = 0; i < 5; i += 1) {
299
+ const item = baseEntry(i);
300
+ await store.append(RUN$1, item);
301
+ const loaded = await store.load(RUN$1);
302
+ const last = loaded[loaded.length - 1];
303
+ ensure(loaded.length === i + 1 && last !== void 0 && sameEntry(last, item), "a3-read-your-writes", `append of seq ${i} was acknowledged but not visible to load`);
304
+ }
305
+ }
306
+ },
307
+ {
308
+ id: "a4-opaque-payload",
309
+ title: "unknown kinds and unknown fields round-trip byte-exactly, never normalized",
310
+ async run() {
311
+ const store = await mk();
312
+ const exotic = {
313
+ v: 1,
314
+ seq: 0,
315
+ scope: "par:0:1/wormhole",
316
+ key: "k-exotic",
317
+ ordinal: 3,
318
+ kind: "wormhole.v9",
319
+ status: "ok",
320
+ value: {
321
+ unicode: "δοκιμή ☃ 🚀".normalize("NFC"),
322
+ float: .30000000000000004,
323
+ nested: { deep: [
324
+ 1,
325
+ 2,
326
+ { three: null }
327
+ ] }
328
+ },
329
+ futureField: { shape: "unknown" },
330
+ spanId: "s",
331
+ startedAt: "2026-01-01T00:00:00.000Z"
332
+ };
333
+ await store.append(RUN$1, exotic);
334
+ const [loaded] = await store.load(RUN$1);
335
+ ensure(loaded !== void 0 && sameEntry(loaded, exotic), "a4-opaque-payload", "the exotic entry did not round-trip byte-exactly (normalized, stripped, or rewritten)");
336
+ ensure(loaded.hashVersion === void 0, "a4-opaque-payload", "the store injected hashVersion into a legacy entry (normalization is read-side only)");
337
+ }
338
+ },
339
+ {
340
+ id: "meta-separation",
341
+ title: "putMeta replaces the run record; listRuns filters without payload parsing; delete removes both",
342
+ async run() {
343
+ const store = await mk();
344
+ ensure((await store.load("never-written")).length === 0, "meta-separation", "load of an unknown run must return an empty journal");
345
+ await store.append(RUN$1, baseEntry(0));
346
+ await store.putMeta(meta(RUN$1, {
347
+ name: "wf-a",
348
+ tags: ["team:core"]
349
+ }));
350
+ await store.putMeta(meta("other-run", {
351
+ status: "suspended",
352
+ name: "wf-b"
353
+ }));
354
+ ensure((await store.listRuns()).filter((candidate) => candidate.runId === RUN$1).length === 1, "meta-separation", "putMeta must upsert one record per run");
355
+ await store.putMeta(meta(RUN$1, {
356
+ status: "suspended",
357
+ name: "wf-a",
358
+ tags: ["team:core"]
359
+ }));
360
+ const suspended = await store.listRuns({ status: "suspended" });
361
+ ensure(suspended.some((candidate) => candidate.runId === RUN$1) && suspended.every((candidate) => candidate.status === "suspended"), "meta-separation", "listRuns must reflect the replaced meta and honor the status filter");
362
+ const byName = await store.listRuns({ name: "wf-b" });
363
+ ensure(byName.length === 1 && byName[0]?.runId === "other-run", "meta-separation", "listRuns must honor the name filter");
364
+ const byTag = await store.listRuns({ tags: ["team:core"] });
365
+ ensure(byTag.length === 1 && byTag[0]?.runId === RUN$1, "meta-separation", "listRuns must honor the tags filter");
366
+ await store.delete(RUN$1);
367
+ ensure((await store.load(RUN$1)).length === 0 && !(await store.listRuns()).some((candidate) => candidate.runId === RUN$1), "meta-separation", "delete must remove the journal and the meta record");
368
+ }
369
+ },
370
+ {
371
+ id: "golden-fold-state",
372
+ title: "the kernel fold over the stored golden journal hashes to the reference",
373
+ async run() {
374
+ const store = await mk();
375
+ for (const item of GOLDEN_FOLD_JOURNAL) await store.append(RUN$1, item);
376
+ const hash = foldStateSha256(await store.load(RUN$1));
377
+ ensure(hash === GOLDEN_FOLD_STATE_SHA256, "golden-fold-state", `fold state hash ${hash} differs from the reference ${GOLDEN_FOLD_STATE_SHA256}: the store influenced replay semantics`);
378
+ }
379
+ },
380
+ {
381
+ id: "decide-once-oracle",
382
+ title: "a scripted race yields exactly one applied classification, then replays with the same winner",
383
+ async run() {
384
+ const store = await mk();
385
+ const writer = new Replayer({
386
+ runId: RUN$1,
387
+ store
388
+ });
389
+ const suspended = await writer.appendSuspended({
390
+ scope: "",
391
+ key: deriveContentKey({
392
+ kind: "external",
393
+ key: "decide-once"
394
+ }),
395
+ kind: "external",
396
+ spanId: "conf-span",
397
+ value: { key: "decide-once" }
398
+ });
399
+ const [first, second] = await Promise.all([writer.resolveSuspended(suspended.seq, {
400
+ by: "external",
401
+ value: { decision: "primary" }
402
+ }), writer.resolveSuspended(suspended.seq, {
403
+ by: "timeout",
404
+ value: { decision: "fallback" }
405
+ })]);
406
+ const outcomes = [first, second];
407
+ ensure(outcomes.filter((outcome) => outcome.applied).length === 1, "decide-once-oracle", "a race of two resolution attempts must settle exactly one applied");
408
+ const journaled = await store.load(RUN$1);
409
+ ensure(journaled.filter((item) => item.kind === "resolution").length === 2, "decide-once-oracle", "both attempts must be journaled (the loser is a journaled noop)");
410
+ const state = new Replayer({
411
+ runId: RUN$1,
412
+ store,
413
+ priorEntries: journaled,
414
+ strict: true
415
+ }).suspensionState(suspended.seq);
416
+ const winnerSeq = outcomes.find((outcome) => outcome.applied)?.seq;
417
+ ensure(state.state === "resolved" && state.by === winnerSeq, "decide-once-oracle", "the replayed fold disagrees with the live winner");
418
+ const reload = await store.load(RUN$1);
419
+ ensure(foldStateSha256(journaled) === foldStateSha256(reload), "decide-once-oracle", "two loads of the raced journal fold to different states");
420
+ }
421
+ },
422
+ {
423
+ id: "abandon-derived-skip",
424
+ title: "a journal with an abandoned branch replays with zero live classes inside the subtree",
425
+ async run() {
426
+ const store = await mk();
427
+ const writer = new Replayer({
428
+ runId: RUN$1,
429
+ store
430
+ });
431
+ const branchIdentity = {
432
+ kind: "step",
433
+ key: "abandoned-branch",
434
+ deps: []
435
+ };
436
+ const spawn = await writer.appendRunning({
437
+ scope: "",
438
+ key: deriveContentKey(branchIdentity),
439
+ kind: "agent",
440
+ spanId: "conf-span"
441
+ });
442
+ const child = await writer.appendRunning({
443
+ scope: agentScope("", spawn.seq),
444
+ key: "child-key",
445
+ kind: "agent",
446
+ spanId: "conf-span"
447
+ });
448
+ await writer.appendTerminal(child.seq, {
449
+ status: "ok",
450
+ value: "paid work",
451
+ usage: {
452
+ inputTokens: 500,
453
+ outputTokens: 100,
454
+ cacheReadTokens: 0,
455
+ cacheWriteTokens: 0
456
+ }
457
+ });
458
+ ensure((await writer.abandonBranch({
459
+ target: spawn.seq,
460
+ authorizedBy: spawn.seq,
461
+ reason: "conformance abandon"
462
+ })).applied, "abandon-derived-skip", "the covering abandon must apply");
463
+ const replayed = new Replayer({
464
+ runId: RUN$1,
465
+ store,
466
+ priorEntries: await store.load(RUN$1),
467
+ strict: true
468
+ });
469
+ replayed.setDisposition(dispositionHook(replayed.fold.abandonFold, buildDeriverRegistry()));
470
+ const matched = replayed.match("", branchIdentity, "scoped");
471
+ ensure(matched.kind === "skip", "abandon-derived-skip", `the abandoned dispatch must derive skipped, got '${matched.kind}'`);
472
+ const ledger = replayed.ledger();
473
+ ensure(ledger.usage.inputTokens === 0 && ledger.usage.outputTokens === 0 && ledger.agentsSpawned === 0, "abandon-derived-skip", "derived-skipped entries must contribute a zero ledger increment (docs/03, section 13.3)");
474
+ ensure(replayed.resumeReport().orphaned.length === 0, "abandon-derived-skip", "covered entries must be reported skipped, never orphaned");
475
+ }
476
+ }
477
+ ]);
478
+ }
479
+ //#endregion
480
+ //#region src/leasable.ts
481
+ /**
482
+ * leasableStoreConformance (M2-T11, DEF-4): the executable definition of
483
+ * the lease capability (docs/03, section "LeasableStore and leases").
484
+ * Mandatory: acquire on a held lease rejects with the typed
485
+ * LeaseHeldError; the fencing epoch is monotonic per run; an append
486
+ * carrying a stale epoch is rejected AND invisible to subsequent loads;
487
+ * a released lease can neither renew nor append.
488
+ *
489
+ * The renew-cadence rule (at most ttl/3) is a HOLDER obligation; the
490
+ * store-side counterpart checked here (when `ttlMs` is provided) is that
491
+ * a lease renewed at that cadence stays held past the original ttl and
492
+ * that an unrenewed lease becomes reclaimable. The first LeasableStore
493
+ * ships in M5 (@rulvar/store-sqlite); the multi-process soak re-runs
494
+ * these sections under real concurrency in M8.
495
+ */
496
+ const RUN = "lease-run";
497
+ function leaseEntry(seq) {
498
+ return {
499
+ hashVersion: 2,
500
+ seq,
501
+ scope: "",
502
+ key: `lease-key-${seq}`,
503
+ ordinal: 0,
504
+ kind: "step",
505
+ status: "ok",
506
+ value: { seq },
507
+ spanId: "lease-span",
508
+ startedAt: (/* @__PURE__ */ new Date(17e11 + seq * 1e3)).toISOString()
509
+ };
510
+ }
511
+ function sleep(ms) {
512
+ return new Promise((resolve) => setTimeout(resolve, ms));
513
+ }
514
+ async function mustReject(operation) {
515
+ try {
516
+ await operation();
517
+ } catch (thrown) {
518
+ return thrown;
519
+ }
520
+ }
521
+ function leasableStoreConformance(mk, options) {
522
+ const checks = [
523
+ {
524
+ id: "lease-exclusive-acquire",
525
+ title: "acquire on a held lease rejects with the typed LeaseHeldError",
526
+ async run() {
527
+ const store = await mk();
528
+ const held = await store.acquire(RUN, "owner-a");
529
+ ensure(held.runId === RUN && held.owner === "owner-a" && typeof held.epoch === "number", "lease-exclusive-acquire", "acquire must return a Lease with runId, owner, and a numeric fencing epoch");
530
+ ensure(await mustReject(() => store.acquire(RUN, "owner-b")) instanceof LeaseHeldError, "lease-exclusive-acquire", "a second acquire while held must reject with LeaseHeldError (typed, code lease_held)");
531
+ await store.release(held);
532
+ ensure((await store.acquire(RUN, "owner-b")).owner === "owner-b", "lease-exclusive-acquire", "after release, acquire must succeed for a new owner");
533
+ }
534
+ },
535
+ {
536
+ id: "fencing-stale-epoch",
537
+ title: "the epoch is monotonic; a stale-epoch append is rejected and invisible",
538
+ async run() {
539
+ const store = await mk();
540
+ const first = await store.acquire(RUN, "owner-a");
541
+ await store.append(RUN, leaseEntry(0), first);
542
+ await store.release(first);
543
+ const second = await store.acquire(RUN, "owner-b");
544
+ ensure(second.epoch > first.epoch, "fencing-stale-epoch", `the fencing epoch must be monotonic per run (got ${second.epoch} after ${first.epoch})`);
545
+ await store.append(RUN, leaseEntry(1), second);
546
+ ensure(await mustReject(() => store.append(RUN, leaseEntry(2), first)) !== void 0, "fencing-stale-epoch", "an append carrying a stale epoch must be rejected");
547
+ const loaded = await store.load(RUN);
548
+ ensure(loaded.length === 2 && !loaded.some((item) => item.seq === 2), "fencing-stale-epoch", "a rejected stale-epoch append must never appear in load");
549
+ }
550
+ },
551
+ {
552
+ id: "lease-release-fences",
553
+ title: "a released lease can neither renew nor append",
554
+ async run() {
555
+ const store = await mk();
556
+ const lease = await store.acquire(RUN, "owner-a");
557
+ await store.renew(lease);
558
+ await store.release(lease);
559
+ ensure(await mustReject(() => store.renew(lease)) !== void 0, "lease-release-fences", "renew of a released lease must reject");
560
+ ensure(await mustReject(() => store.append(RUN, leaseEntry(0), lease)) !== void 0, "lease-release-fences", "append under a released lease must reject");
561
+ ensure((await store.load(RUN)).length === 0, "lease-release-fences", "nothing may be visible after only-rejected appends");
562
+ }
563
+ }
564
+ ];
565
+ const ttlMs = options?.ttlMs;
566
+ if (ttlMs !== void 0) checks.push({
567
+ id: "lease-ttl-and-renew-cadence",
568
+ title: "renew at ttl/3 keeps the lease held past ttl; an unrenewed lease expires",
569
+ async run() {
570
+ const store = await mk();
571
+ const held = await store.acquire(RUN, "owner-a");
572
+ const cadence = Math.floor(ttlMs / 3);
573
+ const deadline = Date.now() + Math.ceil(ttlMs * 1.5);
574
+ while (Date.now() < deadline) {
575
+ await sleep(cadence);
576
+ await store.renew(held);
577
+ ensure(await mustReject(() => store.acquire(RUN, "owner-b")) instanceof LeaseHeldError, "lease-ttl-and-renew-cadence", "a lease renewed at ttl/3 must stay held past the original ttl");
578
+ }
579
+ await store.release(held);
580
+ const abandoned = await store.acquire("expiring-run", "owner-a");
581
+ await sleep(Math.ceil(ttlMs * 1.2));
582
+ ensure((await store.acquire("expiring-run", "owner-b")).epoch > abandoned.epoch, "lease-ttl-and-renew-cadence", "reclaiming an expired lease must advance the fencing epoch");
583
+ }
584
+ });
585
+ return makeSuite("leasableStoreConformance", checks);
586
+ }
587
+ //#endregion
588
+ export { GOLDEN_FOLD_JOURNAL, GOLDEN_FOLD_STATE_SHA256, foldStateSha256, journalStoreConformance, leasableStoreConformance, makeSuite, materializeFoldState, registerConformance, stableStringify };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@rulvar/store-conformance",
3
+ "version": "1.0.0",
4
+ "description": "rulvar executable store conformance kit (DEF-4).",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=22.12.0"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "sideEffects": false,
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "@rulvar/core": "1.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^22.20.0",
29
+ "tsdown": "^0.22.3",
30
+ "typescript": "~6.0.3"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/o-stepper/rulvar.git",
35
+ "directory": "packages/store-conformance"
36
+ },
37
+ "homepage": "https://rulvar.com",
38
+ "bugs": {
39
+ "url": "https://github.com/o-stepper/rulvar/issues"
40
+ },
41
+ "scripts": {
42
+ "build": "tsdown",
43
+ "typecheck": "tsc --noEmit",
44
+ "lint": "eslint .",
45
+ "pack-check": "publint --pack pnpm && attw --pack . --profile esm-only"
46
+ }
47
+ }