@godspeedai/cognate-store-sqlite 0.0.0-stage → 0.1.1

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-store-sqlite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Authoritative `DurableStore` on `bun:sqlite` (spec §13).
4
+
5
+ ## Tables (spec §13.2)
6
+
7
+ `schema_versions` (migrations), `event_streams` (per-stream version), `events` (envelope only —
8
+ position, event_id, stream_id/sequence, type, timing, causality, semantic ref, metadata),
9
+ `payloads` (event_id → JSON payload, separate from the envelope so `erasePayload` can delete
10
+ content without touching causality), `idempotency` (scope+key → fingerprint/result/event_ids),
11
+ `records` (collection+id → version/JSON value, CAS), `outbox` (id, topic, payload, status,
12
+ attempts, `claimed_until` lease), `projection_checkpoints`, `projection_state`, `blobs`
13
+ (sha256-addressed bytes).
14
+
15
+ ## Transaction boundary
16
+
17
+ `commit()` runs the entire decision — envelope validation, idempotency lookup, stream/record CAS,
18
+ event/record/outbox writes, idempotency recording — inside one `BEGIN IMMEDIATE` transaction.
19
+ Any failure throws and rolls back everything; `onCommitted` listeners fire only after `COMMIT`
20
+ returns. `commitProjection` and `erasePayload` are each their own single transaction. bun:sqlite
21
+ is synchronous and the store performs no `await` before entering a transaction, so concurrent
22
+ `commit()` calls in one process serialize naturally through the JS event loop — exactly one wins
23
+ a stream-version race, the rest see `ConcurrencyError`.
24
+
25
+ ## Durability settings
26
+
27
+ `journal_mode=WAL`, `synchronous=FULL` (fsync on every commit — durability over speed, per spec
28
+ §31.2 "fail closed": a decision must never be reported committed before SQLite confirms it),
29
+ `foreign_keys=ON`, `busy_timeout=5000`. `secure_delete=ON` so `erasePayload` overwrites freed
30
+ pages instead of merely unlinking them; it also runs `PRAGMA wal_checkpoint(TRUNCATE)` so no
31
+ plaintext lingers in the WAL either.
32
+
33
+ ## Limits
34
+
35
+ Single-process writer: correctness relies on one Node/Bun process holding the connection and on
36
+ bun:sqlite's synchronous API for in-process serialization, not on SQLite's file locking for
37
+ cross-process write concurrency. Multiple processes writing the same file concurrently will hit
38
+ `SQLITE_BUSY` after `busy_timeout` rather than being serialized by this store. Back up by copying
39
+ the `.sqlite` file plus its `-wal`/`-shm` siblings only after a checkpoint (or use the SQLite
40
+ backup API); a bare copy of the main file while WAL is active can miss committed data.
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-store-sqlite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Authoritative DurableStore on bun:sqlite (spec §13).",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GodSpeedAI/Cognate.git",
10
+ "directory": "packages/store-sqlite"
11
+ },
12
+ "engines": {
13
+ "bun": ">=1.4.0"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts"
23
+ },
24
+ "dependencies": {
25
+ "@godspeedai/cognate-events": "^0.1.1"
26
+ }
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,519 @@
1
+ // Authoritative DurableStore on bun:sqlite (spec §13). Single-process writer; see README.md.
2
+ import { Database } from "bun:sqlite";
3
+ import { createHash } from "node:crypto";
4
+ import { ConcurrencyError, RecordConflictError, IdempotencyMismatchError, CheckpointConflictError, NotFoundError, validateNewEvent } from "@godspeedai/cognate-events";
5
+ import type {
6
+ DurableStore,
7
+ NewEvent,
8
+ StoredEvent,
9
+ RecordWrite,
10
+ StoredRecord,
11
+ CommitRequest,
12
+ CommitOutcome,
13
+ OutboxItem,
14
+ OutboxStatus,
15
+ OutboxSettlement,
16
+ ProjectionCheckpoint,
17
+ ProjectionCommit,
18
+ Json,
19
+ } from "@godspeedai/cognate-events";
20
+ import { migrate } from "./schema.ts";
21
+
22
+ export interface SqliteStoreOptions {
23
+ /** Database file path, or ":memory:". */
24
+ readonly path: string;
25
+ }
26
+
27
+ // A row shape as returned by bun:sqlite; kept loosely typed at the boundary and mapped
28
+ // into the exact DurableStore shapes below.
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ type Row = any;
31
+
32
+ const EVENT_SELECT = "SELECT e.*, p.payload AS payload FROM events e LEFT JOIN payloads p ON p.event_id = e.event_id";
33
+
34
+ function mapEventRow(row: Row): StoredEvent {
35
+ const event: Row = {
36
+ eventId: row.event_id,
37
+ streamId: row.stream_id,
38
+ streamSequence: row.stream_sequence,
39
+ position: row.position,
40
+ eventType: row.event_type,
41
+ schemaVersion: row.schema_version,
42
+ occurredAt: row.occurred_at,
43
+ recordedAt: row.recorded_at,
44
+ tenant: row.tenant,
45
+ correlationId: row.correlation_id,
46
+ causationId: row.causation_id,
47
+ runId: row.run_id,
48
+ scopeId: row.scope_id,
49
+ payload: row.payload != null ? JSON.parse(row.payload as string) : null,
50
+ };
51
+ if (row.component_id != null) event.componentId = row.component_id;
52
+ if (row.fiber_id != null) event.fiberId = row.fiber_id;
53
+ if (row.semantic_ref != null) event.semanticRef = JSON.parse(row.semantic_ref as string);
54
+ if (row.metadata != null) event.metadata = JSON.parse(row.metadata as string);
55
+ if (row.erasure_reason != null) event.erasure = { reason: row.erasure_reason, erasedAt: row.erasure_at };
56
+ return event as StoredEvent;
57
+ }
58
+
59
+ function mapRecordRow(row: Row): StoredRecord {
60
+ return { collection: row.collection, id: row.id, version: row.version, value: JSON.parse(row.value as string) };
61
+ }
62
+
63
+ // Priority order, most to least selective: a correlationId (one thread/session) or agent narrows to a small
64
+ // slice of the tenant's runs; tenant alone is the least selective (every run of that tenant), so it is only
65
+ // picked when nothing more selective was asked for. Field iteration order in `where` must not decide this —
66
+ // runtime-bun always builds `{ tenant, correlationId?, agent? }` with tenant first.
67
+ const RUNS_INDEX_PRIORITY: readonly (readonly [string, string])[] = [
68
+ ["correlationId", "records_runs_correlation_idx"],
69
+ ["agent", "records_runs_agent_idx"],
70
+ ["tenant", "records_runs_tenant_idx"],
71
+ ];
72
+
73
+ /**
74
+ * Builds the exact SQL `listRecords` executes (exported so tests can prove, via `EXPLAIN QUERY PLAN` on this
75
+ * same text, which index the real code path chooses — not a hand-written approximation of it).
76
+ *
77
+ * Equality filters push down as `json_extract(value, '$.<field>')` so a matching field can be served by an
78
+ * expression index (schema.ts migration 3) instead of loading every row in the collection and filtering in
79
+ * JS. The partial indexes are conditioned on a literal `collection = 'runs'`, which SQLite only matches
80
+ * against a literal in the query (a bound `?` parameter defeats partial-index selection even when its value
81
+ * happens to be "runs"), so a collection name safe to embed literally is inlined. Without an `INDEXED BY`
82
+ * hint, SQLite's planner may still favor the always-present `(collection, id)` primary key over a selective
83
+ * partial index on a small table (no `ANALYZE` statistics); the hint keeps the lookup scoped to the matching
84
+ * slice of runs regardless of table size, which is the DEBT-019 concern.
85
+ */
86
+ export function buildListRecordsQuery(collection: string, where?: { readonly [field: string]: string | number | boolean | null }): { readonly sql: string; readonly params: readonly unknown[] } {
87
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(collection)) throw new Error(`listRecords: invalid collection name "${collection}"`);
88
+ const indexHint = collection === "runs" && where ? RUNS_INDEX_PRIORITY.find(([f]) => f in where)?.[1] : undefined;
89
+ let sql = `SELECT * FROM records${indexHint ? ` INDEXED BY ${indexHint}` : ""} WHERE collection = '${collection}'`;
90
+ const params: unknown[] = [];
91
+ for (const [field, value] of Object.entries(where ?? {})) {
92
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(field)) throw new Error(`listRecords: invalid field name "${field}"`);
93
+ sql += value === null ? ` AND json_extract(value, '$.${field}') IS NULL` : ` AND json_extract(value, '$.${field}') = ?`;
94
+ if (value !== null) params.push(value);
95
+ }
96
+ sql += " ORDER BY id";
97
+ return { sql, params };
98
+ }
99
+
100
+ function mapOutboxRow(row: Row): OutboxItem {
101
+ return {
102
+ id: row.id,
103
+ topic: row.topic,
104
+ payload: JSON.parse(row.payload as string),
105
+ status: row.status as OutboxStatus,
106
+ attempts: row.attempts,
107
+ availableAt: row.claimed_until,
108
+ lastError: row.last_error ?? null,
109
+ receipt: row.receipt != null ? JSON.parse(row.receipt as string) : null,
110
+ createdAt: row.created_at,
111
+ };
112
+ }
113
+
114
+ function mapCheckpointRow(row: Row): ProjectionCheckpoint {
115
+ return {
116
+ name: row.name,
117
+ version: row.version,
118
+ position: row.position,
119
+ status: row.status,
120
+ error: row.error_event_id != null ? { position: row.error_position, eventId: row.error_event_id, message: row.error_message } : null,
121
+ };
122
+ }
123
+
124
+ export function openSqliteStore(options: SqliteStoreOptions): DurableStore {
125
+ const db = new Database(options.path, { create: true });
126
+ db.exec("PRAGMA journal_mode = WAL");
127
+ // Durability over speed: fsync on every commit (spec §31.2 "fail closed" — a decision must
128
+ // never be reported committed before SQLite has actually persisted it). WAL + synchronous=FULL
129
+ // fsyncs the WAL on every transaction commit, so a crash cannot lose or reorder a committed decision.
130
+ db.exec("PRAGMA synchronous = FULL");
131
+ db.exec("PRAGMA foreign_keys = ON");
132
+ db.exec("PRAGMA busy_timeout = 5000");
133
+ // Erased payload bytes are overwritten in place rather than merely unlinked, so `erasePayload`
134
+ // (spec §32) leaves nothing recoverable from freed pages once the WAL is checkpointed.
135
+ db.exec("PRAGMA secure_delete = ON");
136
+ migrate(db);
137
+
138
+ let closed = false;
139
+ const listeners = new Set<(events: readonly StoredEvent[]) => void>();
140
+
141
+ function assertOpen(): void {
142
+ if (closed) throw new Error("store-sqlite: store is closed");
143
+ }
144
+
145
+ function ensureStream(streamId: string): void {
146
+ db.query("INSERT OR IGNORE INTO event_streams (stream_id, version) VALUES (?, 0)").run(streamId);
147
+ }
148
+
149
+ function streamVersionRow(streamId: string): number {
150
+ const row = db.query("SELECT version FROM event_streams WHERE stream_id = ?").get(streamId) as { version: number } | null;
151
+ return row?.version ?? 0;
152
+ }
153
+
154
+ function insertEventRow(streamId: string, sequence: number, event: NewEvent, recordedAt: string): StoredEvent {
155
+ const eventId = event.eventId ?? crypto.randomUUID();
156
+ db.query(
157
+ `INSERT INTO events (event_id, stream_id, stream_sequence, event_type, schema_version, occurred_at, recorded_at, tenant, correlation_id, causation_id, run_id, scope_id, component_id, fiber_id, semantic_ref, metadata)
158
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
159
+ ).run(
160
+ eventId,
161
+ streamId,
162
+ sequence,
163
+ event.eventType,
164
+ event.schemaVersion,
165
+ event.occurredAt,
166
+ recordedAt,
167
+ event.tenant,
168
+ event.correlationId,
169
+ event.causationId,
170
+ event.runId,
171
+ event.scopeId,
172
+ event.componentId ?? null,
173
+ event.fiberId ?? null,
174
+ event.semanticRef ? JSON.stringify(event.semanticRef) : null,
175
+ event.metadata ? JSON.stringify(event.metadata) : null,
176
+ );
177
+ db.query("INSERT INTO payloads (event_id, payload) VALUES (?, ?)").run(eventId, JSON.stringify(event.payload));
178
+ const row = db.query(`${EVENT_SELECT} WHERE e.event_id = ?`).get(eventId) as Row;
179
+ return mapEventRow(row);
180
+ }
181
+
182
+ function applyRecordWrite(write: RecordWrite): StoredRecord {
183
+ const row = db.query("SELECT version FROM records WHERE collection = ? AND id = ?").get(write.collection, write.id) as { version: number } | null;
184
+ const current = row?.version ?? 0;
185
+ if (current !== write.expectedVersion) throw new RecordConflictError(write.collection, write.id, write.expectedVersion, current);
186
+ const version = current + 1;
187
+ db.query(
188
+ `INSERT INTO records (collection, id, version, value) VALUES (?, ?, ?, ?)
189
+ ON CONFLICT (collection, id) DO UPDATE SET version = excluded.version, value = excluded.value`,
190
+ ).run(write.collection, write.id, version, JSON.stringify(write.value));
191
+ return { collection: write.collection, id: write.id, version, value: write.value };
192
+ }
193
+
194
+ const commitTxn = db.transaction((request: CommitRequest): CommitOutcome => {
195
+ // Phase A — validate every envelope before anything is written (spec §10).
196
+ for (const append of request.appends) for (const event of append.events) validateNewEvent(event);
197
+
198
+ // Phase B — idempotency: duplicate replays the recorded result; a fingerprint mismatch is an error.
199
+ if (request.idempotency) {
200
+ const existing = db
201
+ .query("SELECT fingerprint, result, event_ids FROM idempotency WHERE scope = ? AND key = ?")
202
+ .get(request.idempotency.scope, request.idempotency.key) as { fingerprint: string; result: string; event_ids: string } | null;
203
+ if (existing) {
204
+ if (existing.fingerprint !== request.idempotency.fingerprint) {
205
+ throw new IdempotencyMismatchError(request.idempotency.scope, request.idempotency.key);
206
+ }
207
+ const ids = JSON.parse(existing.event_ids) as string[];
208
+ const events = ids.map((id) => mapEventRow(db.query(`${EVENT_SELECT} WHERE e.event_id = ?`).get(id) as Row));
209
+ return { kind: "duplicate", events, result: JSON.parse(existing.result) as Json };
210
+ }
211
+ }
212
+
213
+ // Phase C — CAS every stream's expected version before writing any event.
214
+ const streamVersions = new Map<string, number>();
215
+ for (const append of request.appends) {
216
+ ensureStream(append.streamId);
217
+ const current = streamVersionRow(append.streamId);
218
+ if (current !== append.expectedVersion) throw new ConcurrencyError(append.streamId, append.expectedVersion, current);
219
+ streamVersions.set(append.streamId, current);
220
+ }
221
+
222
+ // Phase D — CAS every record write before applying any of them.
223
+ for (const write of request.records ?? []) {
224
+ const row = db.query("SELECT version FROM records WHERE collection = ? AND id = ?").get(write.collection, write.id) as { version: number } | null;
225
+ const current = row?.version ?? 0;
226
+ if (current !== write.expectedVersion) throw new RecordConflictError(write.collection, write.id, write.expectedVersion, current);
227
+ }
228
+
229
+ // Phase E — insert events; the store assigns sequence/position/id/recordedAt.
230
+ const recordedAt = new Date().toISOString();
231
+ const storedEvents: StoredEvent[] = [];
232
+ for (const append of request.appends) {
233
+ let sequence = streamVersions.get(append.streamId) ?? 0;
234
+ for (const event of append.events) {
235
+ sequence += 1;
236
+ storedEvents.push(insertEventRow(append.streamId, sequence, event, recordedAt));
237
+ }
238
+ db.query("UPDATE event_streams SET version = ? WHERE stream_id = ?").run(sequence, append.streamId);
239
+ }
240
+
241
+ // Phase F — apply record writes (already validated above).
242
+ const storedRecords = (request.records ?? []).map((write) => applyRecordWrite(write));
243
+
244
+ // Phase G — outbox intents; a reused id fails the whole decision (unique constraint).
245
+ for (const item of request.outbox ?? []) {
246
+ db.query("INSERT INTO outbox (id, topic, payload, created_at) VALUES (?, ?, ?, ?)").run(item.id, item.topic, JSON.stringify(item.payload), recordedAt);
247
+ }
248
+
249
+ // Phase H — record the idempotency key against the result and the events it produced.
250
+ const result: Json = request.result ?? null;
251
+ if (request.idempotency) {
252
+ db.query("INSERT INTO idempotency (scope, key, fingerprint, result, event_ids, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(
253
+ request.idempotency.scope,
254
+ request.idempotency.key,
255
+ request.idempotency.fingerprint,
256
+ JSON.stringify(result),
257
+ JSON.stringify(storedEvents.map((e) => e.eventId)),
258
+ recordedAt,
259
+ );
260
+ }
261
+
262
+ return { kind: "committed", events: storedEvents, records: storedRecords, result };
263
+ });
264
+
265
+ const claimOutboxTxn = db.transaction((topic: string, now: number, limit: number, leaseMs: number): OutboxItem[] => {
266
+ const rows = db.query("SELECT * FROM outbox WHERE topic = ? AND status = 'pending' AND claimed_until <= ? ORDER BY rowid LIMIT ?").all(topic, now, limit) as Row[];
267
+ const claimedUntil = now + leaseMs;
268
+ const items: OutboxItem[] = [];
269
+ for (const row of rows) {
270
+ db.query("UPDATE outbox SET attempts = attempts + 1, claimed_until = ? WHERE id = ?").run(claimedUntil, row.id);
271
+ items.push(mapOutboxRow({ ...row, attempts: row.attempts + 1, claimed_until: claimedUntil }));
272
+ }
273
+ return items;
274
+ });
275
+
276
+ const settleOutboxTxn = db.transaction((id: string, settlement: OutboxSettlement): void => {
277
+ if (settlement.kind === "delivered") {
278
+ db.query("UPDATE outbox SET status = 'delivered', receipt = ? WHERE id = ?").run(JSON.stringify(settlement.receipt), id);
279
+ } else if (settlement.kind === "retry") {
280
+ db.query("UPDATE outbox SET last_error = ?, claimed_until = ? WHERE id = ?").run(settlement.error, settlement.retryAt, id);
281
+ } else {
282
+ db.query("UPDATE outbox SET status = 'poisoned', last_error = ? WHERE id = ?").run(settlement.error, id);
283
+ }
284
+ });
285
+
286
+ const commitProjectionTxn = db.transaction((commitReq: ProjectionCommit): void => {
287
+ const row = db.query("SELECT position FROM projection_checkpoints WHERE name = ?").get(commitReq.name) as { position: number } | null;
288
+ const current = row?.position ?? 0;
289
+ if (current !== commitReq.fromPosition) {
290
+ throw new CheckpointConflictError(`Projection ${commitReq.name} checkpoint is at ${current}, expected ${commitReq.fromPosition}`);
291
+ }
292
+ for (const write of commitReq.writes) {
293
+ if (write.value === null) {
294
+ db.query("DELETE FROM projection_state WHERE name = ? AND key = ?").run(commitReq.name, write.key);
295
+ } else {
296
+ db.query(
297
+ `INSERT INTO projection_state (name, key, value) VALUES (?, ?, ?)
298
+ ON CONFLICT (name, key) DO UPDATE SET value = excluded.value`,
299
+ ).run(commitReq.name, write.key, JSON.stringify(write.value));
300
+ }
301
+ }
302
+ db.query(
303
+ `INSERT INTO projection_checkpoints (name, version, position, status, error_position, error_event_id, error_message)
304
+ VALUES (?, ?, ?, 'ok', NULL, NULL, NULL)
305
+ ON CONFLICT (name) DO UPDATE SET version = excluded.version, position = excluded.position, status = 'ok', error_position = NULL, error_event_id = NULL, error_message = NULL`,
306
+ ).run(commitReq.name, commitReq.version, commitReq.toPosition);
307
+ });
308
+
309
+ const erasePayloadTxn = db.transaction((eventId: string, reason: string, actorId: string): StoredEvent => {
310
+ const original = db.query(`${EVENT_SELECT} WHERE e.event_id = ?`).get(eventId) as Row;
311
+ if (!original) throw new NotFoundError(`event ${eventId} not found`);
312
+ const erasedAt = new Date().toISOString();
313
+ db.query("DELETE FROM payloads WHERE event_id = ?").run(eventId);
314
+ db.query("UPDATE events SET erasure_reason = ?, erasure_at = ? WHERE event_id = ?").run(reason, erasedAt, eventId);
315
+
316
+ ensureStream("$erasures");
317
+ const sequence = streamVersionRow("$erasures") + 1;
318
+ const tombstone = insertEventRow(
319
+ "$erasures",
320
+ sequence,
321
+ {
322
+ eventType: "erasure.recorded",
323
+ schemaVersion: 1,
324
+ occurredAt: erasedAt,
325
+ tenant: original.tenant,
326
+ correlationId: original.correlation_id,
327
+ causationId: original.event_id,
328
+ runId: original.run_id,
329
+ scopeId: original.scope_id,
330
+ payload: { eventId, reason, actorId },
331
+ },
332
+ erasedAt,
333
+ );
334
+ db.query("UPDATE event_streams SET version = ? WHERE stream_id = ?").run(sequence, "$erasures");
335
+ return tombstone;
336
+ });
337
+
338
+ const store: DurableStore = {
339
+ async commit(request: CommitRequest): Promise<CommitOutcome> {
340
+ assertOpen();
341
+ const outcome = commitTxn.immediate(request);
342
+ if (outcome.kind === "committed" && outcome.events.length > 0) {
343
+ for (const listener of listeners) listener(outcome.events);
344
+ }
345
+ return outcome;
346
+ },
347
+
348
+ async streamVersion(streamId: string): Promise<number> {
349
+ assertOpen();
350
+ return streamVersionRow(streamId);
351
+ },
352
+
353
+ async readStream(streamId: string, options?: { readonly afterSequence?: number; readonly limit?: number }): Promise<StoredEvent[]> {
354
+ assertOpen();
355
+ let sql = `${EVENT_SELECT} WHERE e.stream_id = ?`;
356
+ const params: unknown[] = [streamId];
357
+ if (options?.afterSequence != null) {
358
+ sql += " AND e.stream_sequence > ?";
359
+ params.push(options.afterSequence);
360
+ }
361
+ sql += " ORDER BY e.stream_sequence";
362
+ if (options?.limit != null) {
363
+ sql += " LIMIT ?";
364
+ params.push(options.limit);
365
+ }
366
+ const rows = db.query(sql).all(...(params as [])) as Row[];
367
+ return rows.map(mapEventRow);
368
+ },
369
+
370
+ async readAll(options?: { readonly afterPosition?: number; readonly limit?: number }): Promise<StoredEvent[]> {
371
+ assertOpen();
372
+ let sql = `${EVENT_SELECT} WHERE 1 = 1`;
373
+ const params: unknown[] = [];
374
+ if (options?.afterPosition != null) {
375
+ sql += " AND e.position > ?";
376
+ params.push(options.afterPosition);
377
+ }
378
+ sql += " ORDER BY e.position";
379
+ if (options?.limit != null) {
380
+ sql += " LIMIT ?";
381
+ params.push(options.limit);
382
+ }
383
+ const rows = db.query(sql).all(...(params as [])) as Row[];
384
+ return rows.map(mapEventRow);
385
+ },
386
+
387
+ async getEvent(eventId: string): Promise<StoredEvent | undefined> {
388
+ assertOpen();
389
+ const row = db.query(`${EVENT_SELECT} WHERE e.event_id = ?`).get(eventId) as Row;
390
+ return row ? mapEventRow(row) : undefined;
391
+ },
392
+
393
+ onCommitted(listener: (events: readonly StoredEvent[]) => void): () => void {
394
+ listeners.add(listener);
395
+ return () => listeners.delete(listener);
396
+ },
397
+
398
+ async getRecord(collection: string, id: string): Promise<StoredRecord | undefined> {
399
+ assertOpen();
400
+ const row = db.query("SELECT * FROM records WHERE collection = ? AND id = ?").get(collection, id) as Row;
401
+ return row ? mapRecordRow(row) : undefined;
402
+ },
403
+
404
+ async listRecords(collection: string, where?: { readonly [field: string]: string | number | boolean | null }): Promise<StoredRecord[]> {
405
+ assertOpen();
406
+ const { sql, params } = buildListRecordsQuery(collection, where);
407
+ const rows = db.query(sql).all(...(params as [])) as Row[];
408
+ return rows.map(mapRecordRow);
409
+ },
410
+
411
+ async claimOutbox(options: { readonly topic: string; readonly now: number; readonly limit: number; readonly leaseMs: number }): Promise<OutboxItem[]> {
412
+ assertOpen();
413
+ return claimOutboxTxn.immediate(options.topic, options.now, options.limit, options.leaseMs);
414
+ },
415
+
416
+ async settleOutbox(id: string, settlement: OutboxSettlement): Promise<void> {
417
+ assertOpen();
418
+ settleOutboxTxn.immediate(id, settlement);
419
+ },
420
+
421
+ async requeueOutbox(id: string, now: number): Promise<void> {
422
+ assertOpen();
423
+ db.query("UPDATE outbox SET status = 'pending', claimed_until = ? WHERE id = ?").run(now, id);
424
+ },
425
+
426
+ async listOutbox(options?: { readonly topic?: string; readonly status?: OutboxStatus }): Promise<OutboxItem[]> {
427
+ assertOpen();
428
+ let sql = "SELECT * FROM outbox WHERE 1 = 1";
429
+ const params: unknown[] = [];
430
+ if (options?.topic != null) {
431
+ sql += " AND topic = ?";
432
+ params.push(options.topic);
433
+ }
434
+ if (options?.status != null) {
435
+ sql += " AND status = ?";
436
+ params.push(options.status);
437
+ }
438
+ sql += " ORDER BY rowid";
439
+ const rows = db.query(sql).all(...(params as [])) as Row[];
440
+ return rows.map(mapOutboxRow);
441
+ },
442
+
443
+ async getProjection(name: string): Promise<ProjectionCheckpoint | undefined> {
444
+ assertOpen();
445
+ const row = db.query("SELECT * FROM projection_checkpoints WHERE name = ?").get(name) as Row;
446
+ return row ? mapCheckpointRow(row) : undefined;
447
+ },
448
+
449
+ async commitProjection(commitReq: ProjectionCommit): Promise<void> {
450
+ assertOpen();
451
+ commitProjectionTxn.immediate(commitReq);
452
+ },
453
+
454
+ async failProjection(name: string, error: { readonly position: number; readonly eventId: string; readonly message: string }): Promise<void> {
455
+ assertOpen();
456
+ db.query(
457
+ `INSERT INTO projection_checkpoints (name, version, position, status, error_position, error_event_id, error_message)
458
+ VALUES (?, '', 0, 'error', ?, ?, ?)
459
+ ON CONFLICT (name) DO UPDATE SET status = 'error', error_position = excluded.error_position, error_event_id = excluded.error_event_id, error_message = excluded.error_message`,
460
+ ).run(name, error.position, error.eventId, error.message);
461
+ },
462
+
463
+ async readProjection(name: string, key: string): Promise<Json | undefined> {
464
+ assertOpen();
465
+ const row = db.query("SELECT value FROM projection_state WHERE name = ? AND key = ?").get(name, key) as { value: string } | null;
466
+ return row ? (JSON.parse(row.value) as Json) : undefined;
467
+ },
468
+
469
+ async listProjection(name: string): Promise<{ readonly key: string; readonly value: Json }[]> {
470
+ assertOpen();
471
+ const rows = db.query("SELECT key, value FROM projection_state WHERE name = ? ORDER BY key").all(name) as Row[];
472
+ return rows.map((row) => ({ key: row.key, value: JSON.parse(row.value) as Json }));
473
+ },
474
+
475
+ async resetProjection(name: string): Promise<void> {
476
+ assertOpen();
477
+ const txn = db.transaction((n: string): void => {
478
+ db.query("DELETE FROM projection_state WHERE name = ?").run(n);
479
+ db.query("DELETE FROM projection_checkpoints WHERE name = ?").run(n);
480
+ });
481
+ txn.immediate(name);
482
+ },
483
+
484
+ async putBlob(bytes: Uint8Array): Promise<string> {
485
+ assertOpen();
486
+ const hash = `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
487
+ db.query("INSERT OR IGNORE INTO blobs (hash, bytes) VALUES (?, ?)").run(hash, bytes);
488
+ return hash;
489
+ },
490
+
491
+ async getBlob(hash: string): Promise<Uint8Array | undefined> {
492
+ assertOpen();
493
+ const row = db.query("SELECT bytes FROM blobs WHERE hash = ?").get(hash) as { bytes: Uint8Array } | null;
494
+ return row ? new Uint8Array(row.bytes) : undefined;
495
+ },
496
+
497
+ async deleteBlob(hash: string): Promise<void> {
498
+ assertOpen();
499
+ db.query("DELETE FROM blobs WHERE hash = ?").run(hash);
500
+ },
501
+
502
+ async erasePayload(eventId: string, reason: string, actorId: string): Promise<void> {
503
+ assertOpen();
504
+ const tombstone = erasePayloadTxn.immediate(eventId, reason, actorId);
505
+ // Flush and truncate the WAL so the secure-delete-zeroed pages (and the tombstone) are the
506
+ // only trace left on disk; the erased plaintext must not linger in either file (spec §32).
507
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
508
+ for (const listener of listeners) listener([tombstone]);
509
+ },
510
+
511
+ async close(): Promise<void> {
512
+ if (closed) return;
513
+ closed = true;
514
+ db.close();
515
+ },
516
+ };
517
+
518
+ return store;
519
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,142 @@
1
+ // Numbered migrations recorded in `schema_versions`. Tables mirror spec §13.2 logical names.
2
+ // Payloads are kept in a table separate from event envelopes so erasure (spec §32) can delete
3
+ // content while the envelope (causality, ids, timing) survives untouched.
4
+ import type { Database } from "bun:sqlite";
5
+
6
+ export interface Migration {
7
+ readonly version: number;
8
+ readonly sql: string;
9
+ }
10
+
11
+ export const MIGRATIONS: readonly Migration[] = [
12
+ {
13
+ version: 1,
14
+ sql: `
15
+ CREATE TABLE event_streams (
16
+ stream_id TEXT PRIMARY KEY,
17
+ version INTEGER NOT NULL
18
+ );
19
+
20
+ CREATE TABLE events (
21
+ position INTEGER PRIMARY KEY,
22
+ event_id TEXT NOT NULL UNIQUE,
23
+ stream_id TEXT NOT NULL REFERENCES event_streams(stream_id),
24
+ stream_sequence INTEGER NOT NULL,
25
+ event_type TEXT NOT NULL,
26
+ schema_version INTEGER NOT NULL,
27
+ occurred_at TEXT NOT NULL,
28
+ recorded_at TEXT NOT NULL,
29
+ tenant TEXT NOT NULL,
30
+ correlation_id TEXT NOT NULL,
31
+ causation_id TEXT,
32
+ run_id TEXT,
33
+ scope_id TEXT NOT NULL,
34
+ component_id TEXT,
35
+ fiber_id TEXT,
36
+ semantic_ref TEXT,
37
+ metadata TEXT,
38
+ erasure_reason TEXT,
39
+ erasure_at TEXT,
40
+ UNIQUE (stream_id, stream_sequence)
41
+ );
42
+
43
+ -- Payload bytes live apart from the envelope so erasePayload can delete content
44
+ -- without touching causality-bearing columns above (spec sec32).
45
+ CREATE TABLE payloads (
46
+ event_id TEXT PRIMARY KEY REFERENCES events(event_id),
47
+ payload TEXT NOT NULL
48
+ );
49
+
50
+ CREATE TABLE idempotency (
51
+ scope TEXT NOT NULL,
52
+ key TEXT NOT NULL,
53
+ fingerprint TEXT NOT NULL,
54
+ result TEXT NOT NULL,
55
+ event_ids TEXT NOT NULL,
56
+ created_at TEXT NOT NULL,
57
+ PRIMARY KEY (scope, key)
58
+ );
59
+
60
+ CREATE TABLE records (
61
+ collection TEXT NOT NULL,
62
+ id TEXT NOT NULL,
63
+ version INTEGER NOT NULL,
64
+ value TEXT NOT NULL,
65
+ PRIMARY KEY (collection, id)
66
+ );
67
+
68
+ CREATE TABLE outbox (
69
+ id TEXT PRIMARY KEY,
70
+ topic TEXT NOT NULL,
71
+ payload TEXT NOT NULL,
72
+ status TEXT NOT NULL DEFAULT 'pending',
73
+ attempts INTEGER NOT NULL DEFAULT 0,
74
+ claimed_until INTEGER NOT NULL DEFAULT 0,
75
+ last_error TEXT,
76
+ receipt TEXT,
77
+ created_at TEXT NOT NULL
78
+ );
79
+ CREATE INDEX outbox_topic_idx ON outbox (topic, status, claimed_until);
80
+
81
+ CREATE TABLE projection_checkpoints (
82
+ name TEXT PRIMARY KEY,
83
+ version TEXT NOT NULL,
84
+ position INTEGER NOT NULL,
85
+ status TEXT NOT NULL,
86
+ error_position INTEGER,
87
+ error_event_id TEXT,
88
+ error_message TEXT
89
+ );
90
+
91
+ CREATE TABLE projection_state (
92
+ name TEXT NOT NULL,
93
+ key TEXT NOT NULL,
94
+ value TEXT NOT NULL,
95
+ PRIMARY KEY (name, key)
96
+ );
97
+
98
+ CREATE TABLE blobs (
99
+ hash TEXT PRIMARY KEY,
100
+ bytes BLOB NOT NULL
101
+ );
102
+ `,
103
+ },
104
+ {
105
+ // Spec §9.2: durable facts are never undone by deleting or rewriting history. Enforced in the file itself,
106
+ // so raw SQL cannot bypass the store API. Only a single erasure (§32) may set the erasure columns.
107
+ version: 2,
108
+ sql: `
109
+ CREATE TRIGGER events_append_only_delete BEFORE DELETE ON events
110
+ BEGIN SELECT RAISE(ABORT, 'events are append-only (spec §9.2)'); END;
111
+
112
+ CREATE TRIGGER events_append_only_update BEFORE UPDATE ON events
113
+ WHEN NEW.position IS NOT OLD.position OR NEW.event_id IS NOT OLD.event_id OR NEW.stream_id IS NOT OLD.stream_id OR NEW.stream_sequence IS NOT OLD.stream_sequence OR NEW.event_type IS NOT OLD.event_type OR NEW.schema_version IS NOT OLD.schema_version OR NEW.occurred_at IS NOT OLD.occurred_at OR NEW.recorded_at IS NOT OLD.recorded_at OR NEW.tenant IS NOT OLD.tenant OR NEW.correlation_id IS NOT OLD.correlation_id OR NEW.causation_id IS NOT OLD.causation_id OR NEW.run_id IS NOT OLD.run_id OR NEW.scope_id IS NOT OLD.scope_id OR NEW.component_id IS NOT OLD.component_id OR NEW.fiber_id IS NOT OLD.fiber_id OR NEW.semantic_ref IS NOT OLD.semantic_ref OR NEW.metadata IS NOT OLD.metadata OR OLD.erasure_reason IS NOT NULL
114
+ BEGIN SELECT RAISE(ABORT, 'events are append-only (spec §9.2)'); END;
115
+ `,
116
+ },
117
+ {
118
+ // DurableStore.listRecords (spec §22, DEBT-019) pushes equality filters down as json_extract expressions;
119
+ // these partial expression indexes let SQLite serve `runtime-bun`'s listRuns query (collection = 'runs',
120
+ // filtered by tenant/correlationId/agent) as an index search instead of scanning every run record.
121
+ version: 3,
122
+ sql: `
123
+ CREATE INDEX records_runs_tenant_idx ON records (json_extract(value, '$.tenant')) WHERE collection = 'runs';
124
+ CREATE INDEX records_runs_correlation_idx ON records (json_extract(value, '$.correlationId')) WHERE collection = 'runs';
125
+ CREATE INDEX records_runs_agent_idx ON records (json_extract(value, '$.agent')) WHERE collection = 'runs';
126
+ `,
127
+ },
128
+ ];
129
+
130
+ /** Apply any migration not yet recorded in `schema_versions`, inside one transaction. */
131
+ export function migrate(db: Database): void {
132
+ db.exec("CREATE TABLE IF NOT EXISTS schema_versions (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)");
133
+ const applied = new Set((db.query("SELECT version FROM schema_versions").all() as { version: number }[]).map((r) => r.version));
134
+ const run = db.transaction((): void => {
135
+ for (const migration of MIGRATIONS) {
136
+ if (applied.has(migration.version)) continue;
137
+ db.exec(migration.sql);
138
+ db.query("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)").run(migration.version, new Date().toISOString());
139
+ }
140
+ });
141
+ run.immediate();
142
+ }