@tessar/postgresql 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,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 2026 hphucdev-04
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 CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # @tessar/postgresql
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
+ PostgreSQL storage for Tessar checkpoints, execution records, sessions, and
4
+ plugin-owned state. Uses the native `pg` driver and database transactions.
5
+
6
+ ```ts
7
+ import { PostgresqlStoragePlugin } from "@tessar/postgresql";
8
+
9
+ const storage = new PostgresqlStoragePlugin({
10
+ connectionString: process.env.DATABASE_URL!,
11
+ schema: "tessar", // default
12
+ driverOptions: { max: 10 },
13
+ });
14
+ // Add storage to your Tessar plugins alongside model and application plugins.
15
+ ```
16
+
17
+ `createPostgresqlBackend(options)` creates the same backend directly. Each
18
+ backend owns its connection pool; call `close()` when done. Plugin setup registers
19
+ the backend with Tessar, which owns its disposal. `driverOptions` accepts native
20
+ `pg` pool options, including TLS configuration. `connectionString` is always the
21
+ top-level option. Initialization failure closes the pool.
22
+
23
+ The configured role needs permission to create the schema, tables, and indexes,
24
+ and to read and write them. Schema names must match `[a-zA-Z_][a-zA-Z0-9_]{0,62}`.
25
+ Use a separate schema per application or environment. Existing application tables
26
+ outside that schema are untouched. All backend instances for the same store must
27
+ use the same database and schema.
28
+
29
+ Publication is transactional and uses resource-scoped PostgreSQL advisory locks
30
+ to coordinate processes. Lease expiry uses PostgreSQL time; fencing tokens survive
31
+ release and thread purge. Message and execution changes use indexed revision
32
+ intervals, so unchanged history is not copied into each checkpoint. Reads that
33
+ hydrate multiple rows share a repeatable-read snapshot.
34
+
35
+ Run the repository's `pnpm test:storage` with `TESSAR_TEST_POSTGRES_URL` in the
36
+ environment or ignored `.env.storage`. Tests create unique `tessar_test_*` schemas
37
+ and remove only those schemas. Database tests explicitly skip without the URL;
38
+ they require a real PostgreSQL server and schema creation privileges.
39
+
40
+ The physical schema is versioned in `schema_metadata` (version 1). Initialization
41
+ is serialized by an advisory lock. Existing unversioned tables from the initial
42
+ adapter are adopted without resetting data; unsupported versions fail before
43
+ application-table DDL. SQLite's version 2 and this version 1 refer to different
44
+ physical layouts, not different Tessar state contracts.
45
+
46
+ Source responsibilities match the SQLite adapter: `schema.ts` initializes the
47
+ layout, `ownership.ts` manages leases, `versions.ts` stores historical records,
48
+ `queries.ts` implements paging, and `backend.ts` wires the storage contract.
@@ -0,0 +1,4 @@
1
+ import { type StorageBackend } from "@tessar/core";
2
+ import { type PostgresqlStorageOptions } from "./database.js";
3
+ export type { PostgresqlStorageOptions } from "./database.js";
4
+ export declare function createPostgresqlBackend(options: PostgresqlStorageOptions): Promise<StorageBackend>;
@@ -0,0 +1,315 @@
1
+ import { canonicalJson, buildThreadInfo, recordBinding, validateSession, commitFingerprint, validateBatch, fail, immutable, matchesScope, historyCursor, limitOf, encodeCursor, } from "@tessar/core";
2
+ import { openDatabase } from "./database.js";
3
+ import { initializeSchema, recordTables } from "./schema.js";
4
+ import { assertOwnership, createOwnership } from "./ownership.js";
5
+ import { page, scopeFilter } from "./queries.js";
6
+ import { readVersions, writeVersions, writeCheckpoint, hydrate, } from "./versions.js";
7
+ export async function createPostgresqlBackend(options) {
8
+ const db = openDatabase(options), table = db.table;
9
+ try {
10
+ await initializeSchema(db);
11
+ }
12
+ catch (error) {
13
+ await db.close().catch(() => { });
14
+ throw error;
15
+ }
16
+ const get = async (client, sql, values) => {
17
+ const { rows } = await client.query(sql, values);
18
+ return rows[0] ? immutable(rows[0].body) : null;
19
+ };
20
+ const head = (client, id) => get(client, `SELECT body FROM ${table("threads")} WHERE id=$1`, [id]);
21
+ const checkpoint = (client, id) => get(client, `SELECT body FROM ${table("checkpoints")} WHERE id=$1`, [id]);
22
+ const checkKind = (kind) => {
23
+ if (!recordTables.includes(kind))
24
+ fail("InvalidConfiguration", "Unknown record kind");
25
+ };
26
+ const records = async (client, kind, threadId, checkpointId) => {
27
+ checkKind(kind);
28
+ const cp = await checkpoint(client, checkpointId ?? (await head(client, threadId))?.currentCheckpointId ?? "");
29
+ return cp?.threadId === threadId
30
+ ? readVersions(db, client, kind, threadId, cp.revision)
31
+ : [];
32
+ };
33
+ const ownerKey = (key) => canonicalJson([key.ownerType, key.ownerId, key.pluginId, key.namespace]);
34
+ return {
35
+ id: "postgresql",
36
+ capabilities: {
37
+ durable: true,
38
+ atomicPublish: true,
39
+ coordination: "multi-process",
40
+ },
41
+ close: db.close,
42
+ sessions: {
43
+ get: (id, query = {}) => db.transaction(async (client) => {
44
+ const value = await get(client, `SELECT body FROM ${table("sessions")} WHERE id=$1`, [id]);
45
+ return value && matchesScope(value.scope, query.scope) ? value : null;
46
+ }),
47
+ page: (query) => db.transaction(async (client) => {
48
+ const values = [query.agentId];
49
+ return page(client, table("sessions"), "agent_id=$1 AND " + scopeFilter(query.scope, values), values, query, canonicalJson({ agentId: query.agentId, scope: query.scope ?? {} }), "created_at");
50
+ }),
51
+ compareAndSet: async (value, expected) => {
52
+ value = immutable(value);
53
+ return db.transaction(async (client) => {
54
+ const old = await get(client, `SELECT body FROM ${table("sessions")} WHERE id=$1 FOR UPDATE`, [value.id]);
55
+ validateSession(value, old, expected, value.selectedThreadId
56
+ ? await head(client, value.selectedThreadId)
57
+ : null);
58
+ await client.query(`INSERT INTO ${table("sessions")}(id,agent_id,selected_thread_id,revision,created_at,updated_at,body) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(id) DO UPDATE SET selected_thread_id=excluded.selected_thread_id,revision=excluded.revision,updated_at=excluded.updated_at,body=excluded.body`, [
59
+ value.id,
60
+ value.agentId,
61
+ value.selectedThreadId,
62
+ value.revision,
63
+ value.createdAt,
64
+ value.updatedAt,
65
+ canonicalJson(value),
66
+ ]);
67
+ }, [
68
+ "session:" + value.id,
69
+ ...(value.selectedThreadId
70
+ ? ["thread:" + value.selectedThreadId]
71
+ : []),
72
+ ]);
73
+ },
74
+ },
75
+ ownedState: {
76
+ get: (key) => db.transaction((client) => get(client, `SELECT body FROM ${table("owned_states")} WHERE owner_key=$1`, [ownerKey(key)])),
77
+ compareAndSet: async (state, expected) => {
78
+ state = immutable(state);
79
+ return db.transaction(async (client) => {
80
+ if (!["agent", "session"].includes(state.ownerType))
81
+ fail("InvalidConfiguration", "Execution state must use checkpoints");
82
+ const key = ownerKey(state), old = await get(client, `SELECT body FROM ${table("owned_states")} WHERE owner_key=$1`, [key]);
83
+ if ((old?.revision ?? 0) !== expected ||
84
+ state.revision !== expected + 1)
85
+ fail("CommitConflict", "Owned state revision changed");
86
+ await client.query(`INSERT INTO ${table("owned_states")}(owner_key,revision,body) VALUES($1,$2,$3) ON CONFLICT(owner_key) DO UPDATE SET revision=excluded.revision,body=excluded.body`, [key, state.revision, canonicalJson(state)]);
87
+ }, ["owned:" + ownerKey(state)]);
88
+ },
89
+ },
90
+ threads: {
91
+ get: (id, options) => db.transaction(async (client) => {
92
+ const value = await head(client, id);
93
+ return value && (!value.deleted || options?.includeDeleted)
94
+ ? value
95
+ : null;
96
+ }),
97
+ page: (query) => db.transaction(async (client) => {
98
+ const values = [];
99
+ return page(client, table("threads"), "deleted=FALSE AND " + scopeFilter(query.scope, values), values, query, canonicalJson(query.scope ?? {}), "created_at");
100
+ }),
101
+ list: (query = {}) => db.transaction(async (client) => {
102
+ const values = [], where = scopeFilter(query.scope, values);
103
+ return (await client.query(`SELECT body FROM ${table("threads")} WHERE deleted=FALSE AND ${where} ORDER BY created_at,id COLLATE "C"`, values)).rows.map((row) => immutable(row.body));
104
+ }),
105
+ purge: (id, query = {}) => db.transaction(async (client) => {
106
+ const info = await head(client, id);
107
+ if (!info || !matchesScope(info.scope, query.scope))
108
+ fail("ThreadNotFound", "Thread does not match query");
109
+ if (!info.deleted)
110
+ fail("ThreadNotDeleted", "Soft-delete the thread before purging");
111
+ const active = await client.query(`SELECT 1 FROM ${table("leases")} WHERE thread_id=$1 AND expires_at>clock_timestamp()`, [id]);
112
+ if (info.activeStreamId || active.rowCount)
113
+ fail("ThreadBusy", "Thread has active execution or ownership");
114
+ const referenced = await client.query(`SELECT 1 FROM ${table("threads")} WHERE body->>'parentThreadId'=$1 OR body->>'sourceCheckpointId' IN (SELECT id FROM ${table("checkpoints")} WHERE thread_id=$1) LIMIT 1`, [id]);
115
+ if (referenced.rowCount)
116
+ fail("ThreadReferenced", "Retained fork references this thread");
117
+ for (const name of [
118
+ ...recordTables,
119
+ "messages",
120
+ "checkpoints",
121
+ "commits",
122
+ "staging",
123
+ ])
124
+ await client.query(`DELETE FROM ${table(name)} WHERE thread_id=$1`, [id]);
125
+ await client.query(`DELETE FROM ${table("threads")} WHERE id=$1`, [
126
+ id,
127
+ ]);
128
+ // Lease tombstones preserve fencing tokens when a purged thread ID is reused.
129
+ }, ["thread:" + id]),
130
+ },
131
+ checkpoints: {
132
+ get: (id) => db.transaction(async (client) => {
133
+ const cp = await checkpoint(client, id);
134
+ return cp ? hydrate(db, client, cp) : null;
135
+ }),
136
+ list: (threadId) => db.transaction(async (client) => {
137
+ const { rows } = await client.query(`SELECT body FROM ${table("checkpoints")} WHERE thread_id=$1 ORDER BY revision`, [threadId]);
138
+ return Promise.all(rows.map((row) => hydrate(db, client, row.body)));
139
+ }),
140
+ page: (threadId, options) => db.transaction((client) => page(client, table("checkpoints"), "thread_id=$1", [threadId], options, "checkpoints:" + threadId, "created_at", (row) => ({
141
+ id: row.id,
142
+ threadId,
143
+ revision: row.revision,
144
+ createdAt: row.created_at,
145
+ cause: row.cause,
146
+ forkable: row.forkable,
147
+ unsafeReason: row.unsafe_reason,
148
+ }), "id,revision,created_at,cause,forkable,unsafe_reason")),
149
+ history: (threadId, options, query = {}) => db.transaction(async (client) => {
150
+ const info = await head(client, threadId);
151
+ if (!info || info.deleted || !matchesScope(info.scope, query.scope))
152
+ fail("ThreadNotFound", "Thread does not match query");
153
+ const { binding, cursor } = historyCursor(threadId, options, query), limit = limitOf(options.limit);
154
+ const { rows } = await client.query(`SELECT id,revision,message_count FROM ${table("checkpoints")} WHERE thread_id=$1 AND id=$2`, [
155
+ threadId,
156
+ cursor?.checkpointId ??
157
+ options.atCheckpointId ??
158
+ info.currentCheckpointId,
159
+ ]);
160
+ const cp = rows[0];
161
+ if (!cp)
162
+ fail("CheckpointNotFound", "No checkpoint for history");
163
+ const end = cursor?.end ?? cp.message_count;
164
+ if (end > cp.message_count)
165
+ fail("InvalidCursor", "Invalid history position");
166
+ const begin = Math.max(0, end - limit);
167
+ const messages = await client.query(`SELECT body FROM ${table("messages")} WHERE thread_id=$1 AND position>=$2 AND position<$3 AND from_revision<=$4 AND (to_revision IS NULL OR $4<to_revision) ORDER BY position LIMIT $5`, [threadId, begin, end, cp.revision, limit]);
168
+ return {
169
+ items: messages.rows.map((row) => immutable(row.body)),
170
+ checkpointId: cp.id,
171
+ revision: cp.revision,
172
+ nextCursor: begin
173
+ ? encodeCursor({ v: 1, binding, checkpointId: cp.id, end: begin })
174
+ : null,
175
+ };
176
+ }),
177
+ },
178
+ executions: {
179
+ listRecords: (kind, threadId, query) => db.transaction((client) => records(client, kind, threadId, query?.atCheckpointId)),
180
+ get: (kind, id, query) => db.transaction(async (client) => {
181
+ checkKind(kind);
182
+ const cp = query?.atCheckpointId
183
+ ? await checkpoint(client, query.atCheckpointId)
184
+ : null;
185
+ const threadId = query?.threadId ?? cp?.threadId;
186
+ if (threadId)
187
+ return ((await records(client, kind, threadId, query?.atCheckpointId)).find((record) => record.id === id) ?? null);
188
+ if (query?.atCheckpointId)
189
+ return null;
190
+ return get(client, `SELECT r.body FROM ${table(kind)} r JOIN ${table("threads")} t ON r.thread_id=t.id WHERE r.id=$1 AND r.to_revision IS NULL AND t.deleted=FALSE ORDER BY r.thread_id LIMIT 1`, [id]);
191
+ }),
192
+ page: (kind, threadId, query) => db.transaction(async (client) => {
193
+ checkKind(kind);
194
+ const cp = await checkpoint(client, query.atCheckpointId ??
195
+ (await head(client, threadId))?.currentCheckpointId ??
196
+ "");
197
+ if (!cp || cp.threadId !== threadId)
198
+ fail("CheckpointNotFound", "No checkpoint for records");
199
+ const values = [threadId, cp.revision];
200
+ let where = "thread_id=$1 AND from_revision<=$2 AND (to_revision IS NULL OR $2<to_revision)";
201
+ for (const [field, column] of [
202
+ ["streamId", "stream_id"],
203
+ ["turnId", "turn_id"],
204
+ ["status", "status"],
205
+ ])
206
+ if (query[field] !== undefined) {
207
+ values.push(query[field]);
208
+ where += ` AND ${column}=$${values.length}`;
209
+ }
210
+ return page(client, table(kind), where, values, query, recordBinding(kind, threadId, query), "sort_date");
211
+ }),
212
+ },
213
+ ownership: createOwnership(db),
214
+ commits: {
215
+ stage: async (batch) => {
216
+ batch = immutable(batch);
217
+ validateBatch(batch);
218
+ const fingerprint = await commitFingerprint(batch);
219
+ await db.transaction(async (client) => {
220
+ const prior = await client.query(`SELECT fingerprint FROM ${table("commits")} WHERE id=$1 UNION ALL SELECT fingerprint FROM ${table("staging")} WHERE id=$1`, [batch.commitId]);
221
+ if (prior.rows[0]) {
222
+ if (prior.rows[0].fingerprint !== fingerprint)
223
+ fail("CommitConflict", "commitId payload mismatch");
224
+ return;
225
+ }
226
+ await client.query(`INSERT INTO ${table("staging")}(id,thread_id,body,fingerprint) VALUES($1,$2,$3,$4)`, [
227
+ batch.commitId,
228
+ batch.threadId,
229
+ canonicalJson(batch),
230
+ fingerprint,
231
+ ]);
232
+ }, ["commit:" + batch.commitId]);
233
+ },
234
+ lookupCommit: (id) => db.transaction((client) => get(client, `SELECT body FROM ${table("commits")} WHERE id=$1`, [id])),
235
+ publish: async (request) => {
236
+ request = immutable(request);
237
+ // Staged payloads cannot change; discover the source to lock both fork threads in order.
238
+ const staged = await db.transaction((client) => get(client, `SELECT body FROM ${table("staging")} WHERE id=$1`, [request.commitId]));
239
+ return db.transaction(async (client) => {
240
+ const prior = await get(client, `SELECT body FROM ${table("commits")} WHERE id=$1`, [request.commitId]);
241
+ if (prior) {
242
+ if (prior.threadId !== request.threadId ||
243
+ prior.revision !== request.expectedRevision + 1)
244
+ fail("CommitConflict", "Commit request mismatch");
245
+ return prior;
246
+ }
247
+ if (request.lease.threadId !== request.threadId)
248
+ fail("OwnershipLost", "Lease belongs to another thread");
249
+ await assertOwnership(db, client, request.lease);
250
+ const batch = await get(client, `SELECT body FROM ${table("staging")} WHERE id=$1`, [request.commitId]);
251
+ if (!batch ||
252
+ batch.threadId !== request.threadId ||
253
+ batch.expectedRevision !== request.expectedRevision)
254
+ fail("CommitConflict", "Missing staged batch");
255
+ if (batch.lineage) {
256
+ // A stage inserted after discovery must be retried with the source lock.
257
+ if (staged?.lineage?.parentThreadId !== batch.lineage.parentThreadId)
258
+ fail("CommitConflict", "Fork staging changed; retry publication");
259
+ const parent = await head(client, batch.lineage.parentThreadId), source = await checkpoint(client, batch.lineage.sourceCheckpointId);
260
+ if (!parent || parent.deleted || source?.threadId !== parent.id)
261
+ fail("ThreadNotFound", "Fork source is no longer available");
262
+ }
263
+ const old = await head(client, batch.threadId), cp = batch.checkpoint;
264
+ if ((old?.revision ?? 0) !== batch.expectedRevision ||
265
+ old?.deleted ||
266
+ cp.parentCheckpointId !== (old?.currentCheckpointId ?? null))
267
+ fail("CommitConflict", "Head changed");
268
+ const referenced = async (kind, id) => {
269
+ const entry = batch.records.find((record) => record.kind === kind && record.id === id);
270
+ return entry
271
+ ? entry.data
272
+ : get(client, `SELECT body FROM ${table(kind)} WHERE thread_id=$1 AND id=$2 AND to_revision IS NULL`, [cp.threadId, id]);
273
+ };
274
+ const stream = cp.execution
275
+ ? await referenced("streams", cp.execution.streamId)
276
+ : null;
277
+ if (cp.execution && !stream)
278
+ fail("CommitConflict", "Missing stream reference");
279
+ if (cp.execution?.pendingInterruptId &&
280
+ !(await referenced("interrupts", cp.execution.pendingInterruptId)))
281
+ fail("CommitConflict", "Missing interrupt reference");
282
+ await writeCheckpoint(db, client, cp);
283
+ for (const kind of recordTables)
284
+ await writeVersions(db, client, kind, cp.threadId, cp.revision, batch.records
285
+ .filter((entry) => entry.kind === kind)
286
+ .map((entry) => ({ id: entry.id, data: entry.data })));
287
+ const info = buildThreadInfo(batch, old, stream);
288
+ await client.query(`INSERT INTO ${table("threads")}(id,body,created_at,deleted) VALUES($1,$2,$3,$4) ON CONFLICT(id) DO UPDATE SET body=excluded.body,created_at=excluded.created_at,deleted=excluded.deleted`, [info.id, canonicalJson(info), info.createdAt, info.deleted]);
289
+ if (info.deleted)
290
+ await client.query(`UPDATE ${table("sessions")} SET selected_thread_id=NULL,revision=revision+1,updated_at=$2,body=body || jsonb_build_object('selectedThreadId',NULL,'revision',revision+1,'updatedAt',$2::text) WHERE selected_thread_id=$1`, [info.id, cp.createdAt]);
291
+ // Re-check database time after writing: a lease can expire during a long publish.
292
+ await assertOwnership(db, client, request.lease);
293
+ const receipt = {
294
+ commitId: batch.commitId,
295
+ threadId: batch.threadId,
296
+ revision: cp.revision,
297
+ checkpointId: cp.id,
298
+ };
299
+ await client.query(`INSERT INTO ${table("commits")}(id,thread_id,body,fingerprint) SELECT id,thread_id,$2::jsonb,fingerprint FROM ${table("staging")} WHERE id=$1`, [batch.commitId, canonicalJson(receipt)]);
300
+ await client.query(`DELETE FROM ${table("staging")} WHERE id=$1`, [
301
+ batch.commitId,
302
+ ]);
303
+ return receipt;
304
+ }, [
305
+ "commit:" + request.commitId,
306
+ "thread:" + request.threadId,
307
+ ...(staged?.lineage
308
+ ? ["thread:" + staged.lineage.parentThreadId]
309
+ : []),
310
+ ]);
311
+ },
312
+ },
313
+ };
314
+ }
315
+ //# sourceMappingURL=backend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.js","sourceRoot":"","sources":["../src/backend.ts"],"names":[],"mappings":"AACA,OAAO,EACL,aAAa,EACb,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,EACjB,aAAa,EACb,IAAI,EACJ,SAA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,OAAO;wBACd,MAAM,MAAM,CAAC,KAAK,CAChB,UAAU,KAAK,CAAC,UAAU,CAAC,gMAAgM,EAC3N,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,SAAS,CAAC,CACxB,CAAC;oBACJ,kFAAkF;oBAClF,MAAM,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;oBACjD,MAAM,OAAO,GAAkB;wBAC7B,QAAQ,EAAE,KAAK,CAAC,QAAQ;wBACxB,QAAQ,EAAE,KAAK,CAAC,QAAQ;wBACxB,QAAQ,EAAE,EAAE,CAAC,QAAQ;wBACrB,YAAY,EAAE,EAAE,CAAC,EAAE;qBACpB,CAAC;oBACF,MAAM,MAAM,CAAC,KAAK,CAChB,eAAe,KAAK,CAAC,SAAS,CAAC,kFAAkF,KAAK,CAAC,SAAS,CAAC,cAAc,EAC/I,CAAC,KAAK,CAAC,QAAQ,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC,CACzC,CAAC;oBACF,MAAM,MAAM,CAAC,KAAK,CAAC,eAAe,KAAK,CAAC,SAAS,CAAC,cAAc,EAAE;wBAChE,KAAK,CAAC,QAAQ;qBACf,CAAC,CAAC;oBACH,OAAO,OAAO,CAAC;gBACjB,CAAC,EACD;oBACE,SAAS,GAAG,OAAO,CAAC,QAAQ;oBAC5B,SAAS,GAAG,OAAO,CAAC,QAAQ;oBAC5B,GAAG,CAAC,MAAM,EAAE,OAAO;wBACjB,CAAC,CAAC,CAAC,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC;wBAC7C,CAAC,CAAC,EAAE,CAAC;iBACR,CACF,CAAC;YACJ,CAAC;SACF;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { type PoolClient, type PoolConfig } from "pg";
2
+ export interface PostgresqlStorageOptions {
3
+ connectionString: string;
4
+ schema?: string;
5
+ driverOptions?: Omit<PoolConfig, "connectionString">;
6
+ }
7
+ export type Database = ReturnType<typeof openDatabase>;
8
+ export declare function openDatabase(options: PostgresqlStorageOptions): {
9
+ schema: string;
10
+ table: (name: string) => string;
11
+ transaction: <T>(action: (client: PoolClient) => Promise<T>, keys?: readonly string[]) => Promise<T>;
12
+ close: () => Promise<void>;
13
+ };
@@ -0,0 +1,42 @@
1
+ import { Pool } from "pg";
2
+ import { fail } from "@tessar/core";
3
+ export function openDatabase(options) {
4
+ const schema = options.schema ?? "tessar";
5
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(schema))
6
+ fail("InvalidConfiguration", "Invalid PostgreSQL schema name");
7
+ const table = (name) => `"${schema}"."${name}"`;
8
+ const pool = new Pool({
9
+ ...options.driverOptions,
10
+ connectionString: options.connectionString,
11
+ });
12
+ let closing;
13
+ const close = () => (closing ??= pool.end());
14
+ async function transaction(action, keys) {
15
+ const client = await pool.connect();
16
+ try {
17
+ await client.query(keys ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");
18
+ // Sorted resource locks also serialize creation, where no row exists to lock yet.
19
+ for (const key of [...new Set(keys ?? [])].sort())
20
+ await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [schema + ":" + key]);
21
+ const result = await action(client);
22
+ await client.query("COMMIT");
23
+ return result;
24
+ }
25
+ catch (error) {
26
+ try {
27
+ await client.query("ROLLBACK");
28
+ }
29
+ catch {
30
+ /* Preserve the original driver error. */
31
+ }
32
+ if (error.code === "23505")
33
+ fail("CommitConflict", "Storage key already exists");
34
+ throw error;
35
+ }
36
+ finally {
37
+ client.release();
38
+ }
39
+ }
40
+ return { schema, table, transaction, close };
41
+ }
42
+ //# sourceMappingURL=database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAoC,MAAM,IAAI,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AASpC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AAC,KAAK,CAAC,UAAU,CAAC,CAAC;YACjC,CAAC;YAAC,MAAM,CAAC;gBACP,yCAAyC;YAC3C,CAAC;YACD,IAAK,KAA2B,CAAC,IAAI,KAAK,OAAO;gBAC/C,IAAI,CAAC,gBAAgB,EAAE,4BAA4B,CAAC,CAAC;YACvD,MAAM,KAAK,CAAC;QACd,CAAC;gBAAS,CAAC;YACT,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;AAC/C,CAAC"}
@@ -0,0 +1,9 @@
1
+ export { createPostgresqlBackend, type PostgresqlStorageOptions, } from "./backend.js";
2
+ import type { Plugin, PluginContext } from "@tessar/core";
3
+ import { type PostgresqlStorageOptions } from "./backend.js";
4
+ export declare class PostgresqlStoragePlugin implements Plugin {
5
+ private readonly options;
6
+ readonly id = "storage.postgresql";
7
+ constructor(options: PostgresqlStorageOptions);
8
+ setup(tessar: PluginContext): Promise<void>;
9
+ }
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ export { createPostgresqlBackend, } from "./backend.js";
2
+ import { createPostgresqlBackend, } from "./backend.js";
3
+ export class PostgresqlStoragePlugin {
4
+ options;
5
+ id = "storage.postgresql";
6
+ constructor(options) {
7
+ this.options = options;
8
+ }
9
+ async setup(tessar) {
10
+ const backend = await createPostgresqlBackend(this.options);
11
+ try {
12
+ tessar.storage.register(backend);
13
+ }
14
+ catch (error) {
15
+ await backend.close().catch(() => { });
16
+ throw error;
17
+ }
18
+ }
19
+ }
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,uBAAuB,GAExB,MAAM,cAAc,CAAC;AAEtB,MAAM,OAAO,uBAAuB;IAEL,OAAO;IAD3B,EAAE,GAAG,oBAAoB,CAAC;IACnC,YAA6B,OAAiC;uBAAjC,OAAO;IAA6B,CAAC;IAClE,KAAK,CAAC,KAAK,CAAC,MAAqB;QAC/B,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5D,IAAI,CAAC;YACH,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACtC,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,5 @@
1
+ import type { PoolClient } from "pg";
2
+ import { type Lease, type OwnershipPort } from "@tessar/core";
3
+ import type { Database } from "./database.js";
4
+ export declare function assertOwnership(db: Database, client: PoolClient, lease: Lease): Promise<void>;
5
+ export declare function createOwnership(db: Database): OwnershipPort;
@@ -0,0 +1,48 @@
1
+ import { fail, immutable } from "@tessar/core";
2
+ export async function assertOwnership(db, client, lease) {
3
+ const result = await client.query(`SELECT 1 FROM ${db.table("leases")} WHERE thread_id=$1 AND owner_token=$2 AND fencing_token=$3 AND expires_at>clock_timestamp()`, [lease.threadId, lease.ownerToken, lease.fencingToken]);
4
+ if (!result.rowCount)
5
+ fail("OwnershipLost", "Lease no longer owns thread");
6
+ }
7
+ export function createOwnership(db) {
8
+ const table = db.table;
9
+ const toLease = (row) => ({
10
+ threadId: row.thread_id,
11
+ ownerToken: row.owner_token,
12
+ fencingToken: Number(row.fencing_token),
13
+ expiresAt: row.expires_at.toISOString(),
14
+ });
15
+ const validTtl = (ttl) => {
16
+ if (!Number.isFinite(ttl) || ttl <= 0)
17
+ fail("InvalidConfiguration", "Invalid lease duration");
18
+ };
19
+ return {
20
+ acquire: async (request) => {
21
+ request = immutable(request);
22
+ return db.transaction(async (client) => {
23
+ validTtl(request.ttlMs);
24
+ const { rows } = await client.query(`INSERT INTO ${table("leases")}(thread_id,owner_token,fencing_token,expires_at) VALUES($1,$2,1,clock_timestamp()+$3::double precision*interval '1 millisecond') ON CONFLICT(thread_id) DO UPDATE SET owner_token=excluded.owner_token,fencing_token=${table("leases")}.fencing_token+1,expires_at=clock_timestamp()+$3::double precision*interval '1 millisecond' WHERE ${table("leases")}.expires_at<=clock_timestamp() RETURNING *`, [request.threadId, request.ownerToken, request.ttlMs]);
25
+ if (!rows[0])
26
+ fail("OwnerActive", "Thread has active owner");
27
+ return toLease(rows[0]);
28
+ }, ["thread:" + request.threadId]);
29
+ },
30
+ renew: async (lease, ttlMs) => {
31
+ lease = immutable(lease);
32
+ return db.transaction(async (client) => {
33
+ validTtl(ttlMs);
34
+ const { rows } = await client.query(`UPDATE ${table("leases")} SET expires_at=clock_timestamp()+$4::double precision*interval '1 millisecond' WHERE thread_id=$1 AND owner_token=$2 AND fencing_token=$3 AND expires_at>clock_timestamp() RETURNING *`, [lease.threadId, lease.ownerToken, lease.fencingToken, ttlMs]);
35
+ if (!rows[0])
36
+ fail("OwnershipLost", "Lease no longer owns thread");
37
+ return toLease(rows[0]);
38
+ }, ["thread:" + lease.threadId]);
39
+ },
40
+ release: async (lease) => {
41
+ lease = immutable(lease);
42
+ return db.transaction(async (client) => {
43
+ await client.query(`UPDATE ${table("leases")} SET expires_at='epoch' WHERE thread_id=$1 AND owner_token=$2 AND fencing_token=$3`, [lease.threadId, lease.ownerToken, lease.fencingToken]);
44
+ }, ["thread:" + lease.threadId]);
45
+ },
46
+ };
47
+ }
48
+ //# sourceMappingURL=ownership.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ownership.js","sourceRoot":"","sources":["../src/ownership.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,SAAS,EAAkC,MAAM,cAAc,CAAC;AAG/E,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,EAAY,EACZ,MAAkB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AK,CAChB,UAAU,KAAK,CAAC,QAAQ,CAAC,oFAAoF,EAC7G,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CACvD,CAAC;YACJ,CAAC,EACD,CAAC,SAAS,GAAG,KAAK,CAAC,QAAQ,CAAC,CAC7B,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { PoolClient } from "pg";
2
+ import { type Scope, type PageOptions, type Page } from "@tessar/core";
3
+ export declare function scopeFilter(scope: Scope | undefined, values: unknown[]): string;
4
+ export declare function page<T>(client: PoolClient, table: string, where: string, values: unknown[], options: PageOptions, binding: string, date: string, map?: (row: any) => T, columns?: string): Promise<Page<T>>;
@@ -0,0 +1,23 @@
1
+ import { canonicalJson, immutable, normalizeScope, pageAfter, limitOf, encodeCursor, } from "@tessar/core";
2
+ export function scopeFilter(scope = {}, values) {
3
+ normalizeScope(scope);
4
+ values.push(canonicalJson(scope));
5
+ return `body->'scope' @> $${values.length}::jsonb`;
6
+ }
7
+ export async function page(client, table, where, values, options, binding, date, map = (row) => immutable(row.body), columns = "*") {
8
+ const after = pageAfter(options, binding), limit = limitOf(options.limit);
9
+ if (after) {
10
+ values.push(after[0], after[1]);
11
+ where += ` AND (${date},id COLLATE "C")>($${values.length - 1},$${values.length})`;
12
+ }
13
+ values.push(limit + 1);
14
+ const { rows } = await client.query(`SELECT ${columns},${date} AS page_date FROM ${table} WHERE ${where} ORDER BY ${date},id COLLATE "C" LIMIT $${values.length}`, values);
15
+ const selected = rows.slice(0, limit), last = selected.at(-1);
16
+ return {
17
+ items: selected.map(map),
18
+ nextCursor: rows.length > limit
19
+ ? encodeCursor({ v: 2, binding, after: [last.page_date, last.id] })
20
+ : null,
21
+ };
22
+ }
23
+ //# sourceMappingURL=queries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queries.js","sourceRoot":"","sources":["../src/queries.ts"],"names":[],"m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K,CAAC,EACnC,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACzB,OAAO;QACL,KAAK,EAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC;QACxB,UAAU,EACR,IAAI,CAAC,MAAM,GAAG,KAAK;YACjB,CAAC,CAAC,YAAY,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,IAAK,CAAC,SAAS,EAAE,IAAK,CAAC,EAAE,CAAC,EAAE,CAAC;YACrE,CAAC,CAAC,IAAI;KACX,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Database } from "./database.js";
2
+ export declare const recordTables: readonly ["streams", "turns", "model_attempts", "tool_executions", "interrupts"];
3
+ export declare function initializeSchema(db: Database): Promise<void>;
package/dist/schema.js ADDED
@@ -0,0 +1,52 @@
1
+ import { fail } from "@tessar/core";
2
+ export const recordTables = [
3
+ "streams",
4
+ "turns",
5
+ "model_attempts",
6
+ "tool_executions",
7
+ "interrupts",
8
+ ];
9
+ export async function initializeSchema(db) {
10
+ const { table, schema } = db;
11
+ await db.transaction(async (client) => {
12
+ // Reject future versions before touching application tables or indexes.
13
+ const metadata = await client.query("SELECT to_regclass($1) AS relation", [table("schema_metadata")]);
14
+ if (metadata.rows[0].relation) {
15
+ const { rows } = await client.query(`SELECT id,version FROM ${table("schema_metadata")}`);
16
+ if (rows.length !== 1 ||
17
+ rows[0].id !== "postgresql" ||
18
+ rows[0].version !== 1)
19
+ fail("InvalidConfiguration", "Unsupported PostgreSQL schema version");
20
+ }
21
+ await client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}"`);
22
+ await client.query(`
23
+ CREATE TABLE IF NOT EXISTS ${table("threads")}(id TEXT PRIMARY KEY,body JSONB NOT NULL,created_at TEXT COLLATE "C" NOT NULL,deleted BOOLEAN NOT NULL);
24
+ CREATE TABLE IF NOT EXISTS ${table("checkpoints")}(id TEXT COLLATE "C" PRIMARY KEY,thread_id TEXT NOT NULL REFERENCES ${table("threads")}(id) DEFERRABLE INITIALLY DEFERRED,revision INTEGER NOT NULL,created_at TEXT COLLATE "C" NOT NULL,cause TEXT NOT NULL,message_count INTEGER NOT NULL,forkable BOOLEAN NOT NULL,unsafe_reason TEXT,body JSONB NOT NULL,UNIQUE(thread_id,revision));
25
+ CREATE INDEX IF NOT EXISTS checkpoints_page ON ${table("checkpoints")}(thread_id,created_at,id);
26
+ CREATE INDEX IF NOT EXISTS threads_page ON ${table("threads")}(deleted,created_at,id COLLATE "C");
27
+ CREATE INDEX IF NOT EXISTS threads_parent ON ${table("threads")}((body->>'parentThreadId'));
28
+ CREATE INDEX IF NOT EXISTS threads_source ON ${table("threads")}((body->>'sourceCheckpointId'));
29
+ CREATE TABLE IF NOT EXISTS ${table("staging")}(id TEXT PRIMARY KEY,thread_id TEXT NOT NULL,body JSONB NOT NULL,fingerprint TEXT NOT NULL);
30
+ CREATE INDEX IF NOT EXISTS staging_thread ON ${table("staging")}(thread_id);
31
+ CREATE TABLE IF NOT EXISTS ${table("commits")}(id TEXT PRIMARY KEY,thread_id TEXT NOT NULL REFERENCES ${table("threads")}(id),body JSONB NOT NULL,fingerprint TEXT NOT NULL);
32
+ CREATE INDEX IF NOT EXISTS commits_thread ON ${table("commits")}(thread_id);
33
+ CREATE TABLE IF NOT EXISTS ${table("leases")}(thread_id TEXT PRIMARY KEY,owner_token TEXT NOT NULL,fencing_token BIGINT NOT NULL,expires_at TIMESTAMPTZ NOT NULL);
34
+ CREATE TABLE IF NOT EXISTS ${table("owned_states")}(owner_key TEXT PRIMARY KEY,revision INTEGER NOT NULL,body JSONB NOT NULL);
35
+ CREATE TABLE IF NOT EXISTS ${table("sessions")}(id TEXT PRIMARY KEY,agent_id TEXT NOT NULL,selected_thread_id TEXT REFERENCES ${table("threads")}(id),revision INTEGER NOT NULL,created_at TEXT COLLATE "C" NOT NULL,updated_at TEXT NOT NULL,body JSONB NOT NULL);
36
+ CREATE INDEX IF NOT EXISTS sessions_page ON ${table("sessions")}(agent_id,created_at,id COLLATE "C");
37
+ CREATE INDEX IF NOT EXISTS sessions_thread ON ${table("sessions")}(selected_thread_id);
38
+ `);
39
+ for (const name of ["messages", ...recordTables])
40
+ await client.query(`
41
+ CREATE TABLE IF NOT EXISTS ${table(name)}(thread_id TEXT NOT NULL REFERENCES ${table("threads")}(id) DEFERRABLE INITIALLY DEFERRED,id TEXT COLLATE "C" NOT NULL,from_revision INTEGER NOT NULL,to_revision INTEGER,position INTEGER,stream_id TEXT,turn_id TEXT,status TEXT,sort_date TEXT COLLATE "C" NOT NULL,body JSONB NOT NULL,PRIMARY KEY(thread_id,id,from_revision),CHECK(to_revision IS NULL OR to_revision>from_revision));
42
+ CREATE UNIQUE INDEX IF NOT EXISTS ${name}_current ON ${table(name)}(thread_id,id) WHERE to_revision IS NULL;
43
+ CREATE INDEX IF NOT EXISTS ${name}_page ON ${table(name)}(thread_id,sort_date,id,from_revision);
44
+ CREATE INDEX IF NOT EXISTS ${name}_stream ON ${table(name)}(thread_id,stream_id,sort_date,id);
45
+ CREATE INDEX IF NOT EXISTS ${name}_turn ON ${table(name)}(thread_id,turn_id,sort_date,id);
46
+ `);
47
+ await client.query(`CREATE INDEX IF NOT EXISTS messages_history ON ${table("messages")}(thread_id,position,from_revision)`);
48
+ await client.query(`CREATE TABLE IF NOT EXISTS ${table("schema_metadata")}(id TEXT PRIMARY KEY CHECK(id='postgresql'),version INTEGER NOT NULL)`);
49
+ await client.query(`INSERT INTO ${table("schema_metadata")}(id,version) VALUES('postgresql',1) ON CONFLICT(id) DO NOTHING`);
50
+ }, ["initialize"]);
51
+ }
52
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,SA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S,CAAC;mDACzE,KAAK,CAAC,SAAS,CAAC;iCAClC,KAAK,CAAC,QAAQ,CAAC;iCACf,KAAK,CAAC,cAAc,CAAC;iCACrB,KAAK,CAAC,UAAU,CAAC,kFAAkF,KAAK,CAAC,SAAS,CAAC;kDAClG,KAAK,CAAC,UAAU,CAAC;oDACf,KAAK,CAAC,UAAU,CAAC;GAClE,CAAC,CAAC;QACC,KAAK,MAAM,IAAI,IAAI,CAAC,UAAU,EAAE,GAAG,YAAY,CAAC;YAC9C,MAAM,MAAM,CAAC,KAAK,CAAC;iCACM,KAAK,CAAC,IAAI,CAAC,uCAAuC,KAAK,CAAC,SAAS,CAAC;wCAC3D,IAAI,eAAe,KAAK,CAAC,IAAI,CAAC;iCACrC,IAAI,YAAY,KAAK,CAAC,IAAI,CAAC;iCAC3B,IAAI,cAAc,KAAK,CAAC,IAAI,CAAC;iCAC7B,IAAI,YAAY,KAAK,CAAC,IAAI,CAAC;GACzD,CAAC,CAAC;QACC,MAAM,MAAM,CAAC,KAAK,CAChB,kDAAkD,KAAK,CAAC,UAAU,CAAC,oCAAoC,CACxG,CAAC;QACF,MAAM,MAAM,CAAC,KAAK,CAChB,8BAA8B,KAAK,CAAC,iBAAiB,CAAC,uEAAuE,CAC9H,CAAC;QACF,MAAM,MAAM,CAAC,KAAK,CAChB,eAAe,KAAK,CAAC,iBAAiB,CAAC,gEAAgE,CACxG,CAAC;IACJ,CAAC,EACD,CAAC,YAAY,CAAC,CACf,CAAC;AACJ,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { PoolClient } from "pg";
2
+ import { type Checkpoint, type RecordKind } from "@tessar/core";
3
+ import type { Database } from "./database.js";
4
+ export type VersionTable = RecordKind | "messages";
5
+ export declare function writeVersions(db: Database, client: PoolClient, name: VersionTable, threadId: string, revision: number, entries: readonly {
6
+ id: string;
7
+ data: unknown;
8
+ position?: number;
9
+ }[], replace?: boolean): Promise<void>;
10
+ export declare function readVersions<T>(db: Database, client: PoolClient, name: VersionTable, threadId: string, revision: number): Promise<T[]>;
11
+ export declare function writeCheckpoint(db: Database, client: PoolClient, cp: Checkpoint): Promise<void>;
12
+ export declare function hydrate(db: Database, client: PoolClient, cp: Checkpoint): Promise<Checkpoint>;
@@ -0,0 +1,64 @@
1
+ import { canonicalJson, immutable, checkpointSafety, } from "@tessar/core";
2
+ export async function writeVersions(db, client, name, threadId, revision, entries, replace = false) {
3
+ const table = db.table(name);
4
+ const { rows } = await client.query(`SELECT id,body,position FROM ${table} WHERE thread_id=$1 AND to_revision IS NULL`, [threadId]);
5
+ const current = new Map(rows.map((row) => [row.id, row]));
6
+ for (const entry of entries) {
7
+ const old = current.get(entry.id);
8
+ current.delete(entry.id);
9
+ const body = canonicalJson(entry.data);
10
+ if (old &&
11
+ canonicalJson(old.body) === body &&
12
+ old.position === (entry.position ?? null))
13
+ continue;
14
+ if (old)
15
+ await client.query(`UPDATE ${table} SET to_revision=$1 WHERE thread_id=$2 AND id=$3 AND to_revision IS NULL`, [revision, threadId, entry.id]);
16
+ const value = entry.data;
17
+ await client.query(`INSERT INTO ${table}(thread_id,id,from_revision,position,stream_id,turn_id,status,sort_date,body) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [
18
+ threadId,
19
+ entry.id,
20
+ revision,
21
+ entry.position ?? null,
22
+ value.streamId ?? null,
23
+ value.turnId ?? null,
24
+ value.status ?? null,
25
+ value.createdAt ?? value.startedAt ?? "",
26
+ body,
27
+ ]);
28
+ }
29
+ if (replace && current.size)
30
+ await client.query(`UPDATE ${table} SET to_revision=$1 WHERE thread_id=$2 AND id=ANY($3::text[]) AND to_revision IS NULL`, [revision, threadId, [...current.keys()]]);
31
+ }
32
+ export async function readVersions(db, client, name, threadId, revision) {
33
+ const { rows } = await client.query(`SELECT body FROM ${db.table(name)} WHERE thread_id=$1 AND from_revision<=$2 AND (to_revision IS NULL OR $2<to_revision) ORDER BY ${name === "messages" ? "position" : 'sort_date,id COLLATE "C"'}`, [threadId, revision]);
34
+ return rows.map((row) => immutable(row.body));
35
+ }
36
+ export async function writeCheckpoint(db, client, cp) {
37
+ await writeVersions(db, client, "messages", cp.threadId, cp.revision, cp.state.messages.map((data, position) => ({
38
+ id: data.id,
39
+ data,
40
+ position,
41
+ })), true);
42
+ const { messages, ...state } = cp.state, safety = checkpointSafety(cp);
43
+ await client.query(`INSERT INTO ${db.table("checkpoints")}(id,thread_id,revision,created_at,cause,message_count,forkable,unsafe_reason,body) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [
44
+ cp.id,
45
+ cp.threadId,
46
+ cp.revision,
47
+ cp.createdAt,
48
+ cp.cause,
49
+ messages.length,
50
+ safety.forkable,
51
+ safety.unsafeReason,
52
+ canonicalJson({ ...cp, state }),
53
+ ]);
54
+ }
55
+ export async function hydrate(db, client, cp) {
56
+ return immutable({
57
+ ...cp,
58
+ state: {
59
+ ...cp.state,
60
+ messages: await readVersions(db, client, "messages", cp.threadId, cp.revision),
61
+ },
62
+ });
63
+ }
64
+ //# sourceMappingURL=versions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":"AACA,OAAO,EACL,aAAa,EACb,SAAS,EACT,gBAAgB,GAIjB,MAAM,cAAc,CAAC;AAItB,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,EAAY,EACZ,MAAkB,EAClB,IAAkB,EAClB,QAAgB,EAChB,QAAgB,EAChB,OAAoE,EACpE,OAAO,GAAG,KAAK;IAEf,MAAM,KAAK,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC7B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,gCAAgC,KAAK,6CAA6C,EAClF,CAAC,QAAQ,CAAC,CACX,CAAC;IACF,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,CAA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AY;QACnB,aAAa,CAAC,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC;KAChC,CACF,CAAC;AACJ,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,EAAY,EACZ,MAAkB,EAClB,EAAc;IAEd,OAAO,SAAS,CAAC;QACf,GAAG,EAAE;QACL,KAAK,EAAE;YACL,GAAG,EAAE,CAAC,KAAK;YACX,QAAQ,EAAE,MAAM,YAAY,CAC1B,EAAE,EACF,MAAM,EACN,UAAU,EACV,EAAE,CAAC,QAAQ,EACX,EAAE,CAAC,QAAQ,CACZ;SACF;KACF,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@tessar/postgresql",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "license": "Apache-2.0",
5
+ "description": "PostgreSQL persistence for Tessar state and checkpoints.",
6
+ "keywords": [
7
+ "tessar",
8
+ "ai-agent",
9
+ "postgresql",
10
+ "postgres",
11
+ "storage",
12
+ "persistence",
13
+ "checkpoints",
14
+ "typescript"
15
+ ],
16
+ "type": "module",
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "engines": {
21
+ "node": ">=24.14.0"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/tessar-ai/tessar.git",
26
+ "directory": "packages/postgresql"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org/"
31
+ },
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js"
36
+ }
37
+ },
38
+ "dependencies": {
39
+ "pg": "^8.16.3",
40
+ "@types/pg": "^8.15.5",
41
+ "@tessar/core": "0.1.1"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json",
45
+ "typecheck": "tsc --noEmit -p tsconfig.json"
46
+ }
6
47
  }