@jami-studio/harness-store-hosted 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +159 -0
  2. package/README.md +36 -0
  3. package/package.json +41 -0
  4. package/src/index.mjs +278 -0
package/LICENSE ADDED
@@ -0,0 +1,159 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ or more of the outstanding shares, or (iii) beneficial ownership of such
21
+ entity.
22
+
23
+ "You" or "Your" shall mean an individual or Legal Entity exercising
24
+ 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 source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation or
31
+ translation of a Source form, including but not limited to compiled object
32
+ code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work.
37
+
38
+ "Derivative Works" shall mean any work, whether in Source or Object form,
39
+ that is based on or derived from the Work and for which the editorial
40
+ revisions, annotations, elaborations, or other modifications represent, as a
41
+ whole, an original work of authorship. For the purposes of this License,
42
+ Derivative Works shall not include works that remain separable from, or
43
+ merely link or bind by name to the interfaces of, the Work and Derivative
44
+ Works thereof.
45
+
46
+ "Contribution" shall mean any work of authorship, including the original
47
+ version of the Work and any modifications or additions to that Work or
48
+ Derivative Works thereof, that is intentionally submitted to Licensor for
49
+ inclusion in the Work by the copyright owner or by an individual or Legal
50
+ Entity authorized to submit on behalf of the copyright owner. For the purposes
51
+ of this definition, "submitted" means any form of electronic, verbal, or
52
+ written communication sent to the Licensor or its representatives, including
53
+ but not limited to communication on electronic mailing lists, source code
54
+ control systems, and issue tracking systems that are managed by, or on behalf
55
+ of, the Licensor for the purpose of discussing and improving the Work, but
56
+ excluding communication that is conspicuously marked or otherwise designated
57
+ in writing by the copyright owner as "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
60
+ behalf of whom a Contribution has been received by Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
64
+ License, each Contributor hereby grants to You a perpetual, worldwide,
65
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
66
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
67
+ sublicense, and distribute the Work and such Derivative Works in Source or
68
+ Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of this
71
+ License, each Contributor hereby grants to You a perpetual, worldwide,
72
+ non-exclusive, no-charge, royalty-free, irrevocable patent license to make,
73
+ have made, use, offer to sell, sell, import, and otherwise transfer the Work,
74
+ where such license applies only to those patent claims licensable by such
75
+ Contributor that are necessarily infringed by their Contribution alone or by
76
+ combination of their Contribution with the Work to which such Contribution was
77
+ submitted. If You institute patent litigation against any entity alleging that
78
+ the Work or a Contribution incorporated within the Work constitutes direct or
79
+ contributory patent infringement, then any patent licenses granted to You
80
+ under this License for that Work shall terminate as of the date such
81
+ litigation is filed.
82
+
83
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
84
+ Derivative Works thereof in any medium, with or without modifications, and in
85
+ Source or Object form, provided that You meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or Derivative Works a copy
88
+ of this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices stating that
91
+ You changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works that You
94
+ distribute, all copyright, patent, trademark, and attribution notices from the
95
+ Source form of the Work, excluding those notices that do not pertain to any
96
+ part of the Derivative Works; and
97
+
98
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
99
+ any Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of
102
+ the following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents
106
+ of the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+
112
+ You may add Your own copyright statement to Your modifications and may provide
113
+ additional or different license terms and conditions for use, reproduction, or
114
+ distribution of Your modifications, or for any such Derivative Works as a
115
+ whole, provided Your use, reproduction, and distribution of the Work otherwise
116
+ complies with the conditions stated in this License.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
119
+ Contribution intentionally submitted for inclusion in the Work by You to the
120
+ Licensor shall be under the terms and conditions of this License, without any
121
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
122
+ supersede or modify the terms of any separate license agreement you may have
123
+ executed with Licensor regarding such Contributions.
124
+
125
+ 6. Trademarks. This License does not grant permission to use the trade names,
126
+ trademarks, service marks, or product names of the Licensor, except as
127
+ required for reasonable and customary use in describing the origin of the Work
128
+ and reproducing the content of the NOTICE file.
129
+
130
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
131
+ writing, Licensor provides the Work on an "AS IS" BASIS, WITHOUT WARRANTIES OR
132
+ CONDITIONS OF ANY KIND, either express or implied, including, without
133
+ limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
134
+ MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely
135
+ responsible for determining the appropriateness of using or redistributing the
136
+ Work and assume any risks associated with Your exercise of permissions under
137
+ this License.
138
+
139
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
140
+ tort, contract, or otherwise, unless required by applicable law or agreed to in
141
+ writing, shall any Contributor be liable to You for damages, including any
142
+ direct, indirect, special, incidental, or consequential damages of any
143
+ character arising as a result of this License or out of the use or inability
144
+ to use the Work, including but not limited to damages for loss of goodwill,
145
+ work stoppage, computer failure or malfunction, or any and all other
146
+ commercial damages or losses, even if such Contributor has been advised of the
147
+ possibility of such damages.
148
+
149
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
150
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
151
+ acceptance of support, warranty, indemnity, or other liability obligations
152
+ and/or rights consistent with this License. However, in accepting such
153
+ obligations, You may act only on Your own behalf and on Your sole
154
+ responsibility, not on behalf of any other Contributor, and only if You agree
155
+ to indemnify, defend, and hold each Contributor harmless for any liability
156
+ incurred by, or claims asserted against, such Contributor by reason of your
157
+ accepting any such warranty or additional liability.
158
+
159
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # @jami-studio/harness-store-hosted
2
+
3
+ Hosted **Postgres + pgvector** durable memory store for Jami Harness.
4
+
5
+ It provides org-scoped, ranked vector retrieval over `node-postgres`, using the deterministic local
6
+ embedding contract from `@jami-studio/harness-memory` so local and hosted similarity are comparable.
7
+ The Drizzle ORM schema (`memoryRecords`) is the source of truth for columns and migrations.
8
+
9
+ ## No-fallback / fail-closed posture
10
+
11
+ There is **no in-memory or noop fallback**. The store is real hosted code:
12
+
13
+ - Without an injected driver and without a `DATABASE_URL`, every operation throws
14
+ `HostedStoreError("hosted_store_unavailable")` — it never serves an in-memory substitute behind a
15
+ hosted claim.
16
+ - If `DATABASE_URL` is set but the optional `pg` driver is not installed, operations throw
17
+ `HostedStoreError("hosted_driver_missing")`.
18
+ - Every operation is org-scoped. A missing `orgId` throws
19
+ `HostedStoreError("org_isolation_required")`, so records can never leak across organizations.
20
+
21
+ ## Capabilities
22
+
23
+ - `init()` — creates the `vector` extension, `memory_records` table, the org index, and an HNSW
24
+ cosine index.
25
+ - `write(input)` — upserts a normalized memory record with its embedding.
26
+ - `search(query)` — org-scoped ranked retrieval (`embedding <=> $vector` cosine distance) with
27
+ project / user / freshness / recency filters, permission filtering, and `minScore` / `limit`.
28
+ - `delete(memoryId, { orgId })`, `purgeExpired({ orgId })` — retention/deletion at the query
29
+ boundary.
30
+
31
+ ## Verification status
32
+
33
+ The SQL generation, org isolation, ranking, and fail-closed behavior are covered by a deterministic
34
+ driver-boundary contract test (the driver is injected at the boundary). A live Postgres + pgvector
35
+ integration is **operator-deferred**: provision a database, set `DATABASE_URL`, install `pg`, and run
36
+ `init()` to exercise the real engine. No database is provisioned in CI by default.
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@jami-studio/harness-store-hosted",
3
+ "version": "0.1.0",
4
+ "description": "Hosted Postgres + pgvector durable memory store for Jami Harness: org-scoped, ranked vector retrieval with explicit fail-closed behavior when no database is provisioned.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/studio-jami/jami-harness.git",
9
+ "directory": "packages/store-hosted"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": "./src/index.mjs"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src/",
20
+ "README.md"
21
+ ],
22
+ "jamiRelease": {
23
+ "publishable": true
24
+ },
25
+ "dependencies": {
26
+ "@jami-studio/harness-context": "0.1.0",
27
+ "@jami-studio/harness-memory": "0.1.0",
28
+ "drizzle-orm": "0.45.2"
29
+ },
30
+ "optionalDependencies": {
31
+ "pg": "^8.13.1"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "pg": {
35
+ "optional": true
36
+ }
37
+ },
38
+ "scripts": {
39
+ "test": "node --test test/*.test.mjs"
40
+ }
41
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,278 @@
1
+ import { pgTable, text, timestamp, jsonb, vector, index } from "drizzle-orm/pg-core";
2
+ import { embedText, cosineSimilarity, normalizeMemoryRecord, memoryEmbeddingDimension } from "@jami-studio/harness-memory";
3
+
4
+ /**
5
+ * Drizzle ORM schema for the hosted Postgres + pgvector memory store. This is the source of truth
6
+ * for columns and migrations; the adapter below runs parameterized queries against the same shape.
7
+ */
8
+ export const memoryRecords = pgTable(
9
+ "memory_records",
10
+ {
11
+ memoryId: text("memory_id").primaryKey(),
12
+ orgId: text("org_id").notNull(),
13
+ projectId: text("project_id").notNull(),
14
+ userId: text("user_id"),
15
+ kind: text("kind").notNull(),
16
+ summary: text("summary"),
17
+ content: text("content"),
18
+ record: jsonb("record").notNull(),
19
+ embedding: vector("embedding", { dimensions: memoryEmbeddingDimension }).notNull(),
20
+ freshnessClass: text("freshness_class").notNull(),
21
+ forgetAfter: timestamp("forget_after", { withTimezone: true }).notNull(),
22
+ recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull(),
23
+ },
24
+ (table) => ({
25
+ orgIdx: index("memory_records_org_idx").on(table.orgId),
26
+ embeddingIdx: index("memory_records_embedding_idx").using("hnsw", table.embedding.op("vector_cosine_ops")),
27
+ }),
28
+ );
29
+
30
+ export class HostedStoreError extends Error {
31
+ constructor(code, message) {
32
+ super(message);
33
+ this.name = "HostedStoreError";
34
+ this.code = code;
35
+ }
36
+ }
37
+
38
+ const CREATE_STATEMENTS = [
39
+ "CREATE EXTENSION IF NOT EXISTS vector",
40
+ `CREATE TABLE IF NOT EXISTS memory_records (
41
+ memory_id text PRIMARY KEY,
42
+ org_id text NOT NULL,
43
+ project_id text NOT NULL,
44
+ user_id text,
45
+ kind text NOT NULL,
46
+ summary text,
47
+ content text,
48
+ record jsonb NOT NULL,
49
+ embedding vector(${memoryEmbeddingDimension}) NOT NULL,
50
+ freshness_class text NOT NULL,
51
+ forget_after timestamptz NOT NULL,
52
+ recorded_at timestamptz NOT NULL
53
+ )`,
54
+ "CREATE INDEX IF NOT EXISTS memory_records_org_idx ON memory_records (org_id)",
55
+ "CREATE INDEX IF NOT EXISTS memory_records_embedding_idx ON memory_records USING hnsw (embedding vector_cosine_ops)",
56
+ ];
57
+
58
+ /**
59
+ * Hosted Postgres + pgvector memory store.
60
+ *
61
+ * Real org-scoped vector retrieval over node-postgres. There is NO in-memory or noop fallback: if no
62
+ * driver and no connection string are available the store is constructed but every operation fails
63
+ * closed with HostedStoreError("hosted_store_unavailable"). Every query is org-scoped; a missing
64
+ * orgId fails closed with HostedStoreError("org_isolation_required") so records can never leak across
65
+ * organizations.
66
+ *
67
+ * options:
68
+ * - driver: injected driver `{ query(text, params) => Promise<{ rows }>, end?() }`
69
+ * (used for the deterministic driver-boundary contract test).
70
+ * - connectionString: Postgres URL; defaults to process.env.DATABASE_URL.
71
+ * - now: clock function for retention.
72
+ */
73
+ export function createHostedMemoryStore(options = {}) {
74
+ const now = options.now ?? (() => new Date());
75
+ const connectionString = options.connectionString ?? process.env.DATABASE_URL ?? null;
76
+ let driver = options.driver ?? null;
77
+ let ownsDriver = false;
78
+ let driverInit = null;
79
+
80
+ async function resolveDriver() {
81
+ if (driver) return driver;
82
+ if (!connectionString) {
83
+ throw new HostedStoreError(
84
+ "hosted_store_unavailable",
85
+ "hosted memory store requires an injected driver or DATABASE_URL connection string; refusing to serve an in-memory substitute for a hosted claim",
86
+ );
87
+ }
88
+ if (!driverInit) {
89
+ driverInit = (async () => {
90
+ let pg;
91
+ try {
92
+ pg = await import("pg");
93
+ } catch {
94
+ throw new HostedStoreError(
95
+ "hosted_driver_missing",
96
+ "the optional 'pg' driver is not installed; install pg + a reachable Postgres with the pgvector extension to use the hosted memory store",
97
+ );
98
+ }
99
+ const Pool = pg.default?.Pool ?? pg.Pool;
100
+ const pool = new Pool({ connectionString });
101
+ ownsDriver = true;
102
+ driver = {
103
+ query: (sql, params) => pool.query(sql, params),
104
+ end: () => pool.end(),
105
+ };
106
+ return driver;
107
+ })();
108
+ }
109
+ return driverInit;
110
+ }
111
+
112
+ return {
113
+ capabilities: { mode: "hosted_pgvector", readable: true, writable: true, searchable: true, ranked: true, hosted: true, durable: true },
114
+
115
+ async init() {
116
+ const db = await resolveDriver();
117
+ for (const statement of CREATE_STATEMENTS) {
118
+ await db.query(statement);
119
+ }
120
+ return { initialized: true };
121
+ },
122
+
123
+ async write(input) {
124
+ const orgId = requireOrgId(input.orgId);
125
+ const record = normalizeMemoryRecord(input, { now });
126
+ const embedding = formatVector(embedText(`${record.summary ?? ""} ${record.content ?? ""}`));
127
+ const db = await resolveDriver();
128
+ await db.query(
129
+ `INSERT INTO memory_records
130
+ (memory_id, org_id, project_id, user_id, kind, summary, content, record, embedding, freshness_class, forget_after, recorded_at)
131
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
132
+ ON CONFLICT (memory_id) DO UPDATE SET
133
+ org_id = EXCLUDED.org_id,
134
+ project_id = EXCLUDED.project_id,
135
+ user_id = EXCLUDED.user_id,
136
+ kind = EXCLUDED.kind,
137
+ summary = EXCLUDED.summary,
138
+ content = EXCLUDED.content,
139
+ record = EXCLUDED.record,
140
+ embedding = EXCLUDED.embedding,
141
+ freshness_class = EXCLUDED.freshness_class,
142
+ forget_after = EXCLUDED.forget_after,
143
+ recorded_at = EXCLUDED.recorded_at`,
144
+ [
145
+ record.memoryId,
146
+ orgId,
147
+ record.scope.projectId,
148
+ input.userId ?? null,
149
+ record.kind,
150
+ record.summary ?? null,
151
+ record.content ?? null,
152
+ JSON.stringify(record),
153
+ embedding,
154
+ record.freshness.class,
155
+ record.retention.forgetAfter,
156
+ record.source.recordedAt,
157
+ ],
158
+ );
159
+ return { written: true, record };
160
+ },
161
+
162
+ async search(query = {}) {
163
+ const orgId = requireOrgId(query.orgId);
164
+ const db = await resolveDriver();
165
+ const params = [orgId, isoNow(now)];
166
+ const conditions = ["org_id = $1", "forget_after > $2"];
167
+
168
+ if (query.projectId) {
169
+ params.push(query.projectId);
170
+ conditions.push(`project_id = $${params.length}`);
171
+ }
172
+ if (query.userId) {
173
+ params.push(query.userId);
174
+ conditions.push(`user_id = $${params.length}`);
175
+ }
176
+ if (query.freshness) {
177
+ const allowed = Array.isArray(query.freshness) ? query.freshness : [query.freshness];
178
+ params.push(allowed);
179
+ conditions.push(`freshness_class = ANY($${params.length})`);
180
+ }
181
+
182
+ let order = "recorded_at DESC, memory_id ASC";
183
+ let scoreSelect = "NULL::float8 AS score";
184
+ if (query.text) {
185
+ params.push(formatVector(embedText(query.text)));
186
+ const vectorParam = `$${params.length}`;
187
+ scoreSelect = `1 - (embedding <=> ${vectorParam}) AS score`;
188
+ order = `embedding <=> ${vectorParam} ASC`;
189
+ }
190
+
191
+ const sql = `SELECT record, ${scoreSelect} FROM memory_records WHERE ${conditions.join(" AND ")} ORDER BY ${order}`;
192
+ const { rows } = await db.query(sql, params);
193
+
194
+ const minScore = Number.isFinite(query.minScore) ? query.minScore : null;
195
+ const droppedItems = [];
196
+ const items = [];
197
+ const limit = Number.isInteger(query.limit) && query.limit >= 0 ? query.limit : null;
198
+ for (const row of rows) {
199
+ const record = typeof row.record === "string" ? JSON.parse(row.record) : row.record;
200
+ if (!canReadMemory(record, query.actor ?? {})) {
201
+ droppedItems.push({ sourceRef: record.memoryId, reason: "permission_denied" });
202
+ continue;
203
+ }
204
+ const score = row.score === null || row.score === undefined ? null : Number(row.score);
205
+ if (minScore !== null && score !== null && score < minScore) continue;
206
+ items.push({
207
+ record: redactForRecall(record),
208
+ citation: record.citation,
209
+ score,
210
+ inclusionReason: score === null ? "org-scoped match" : "org-scoped vector relevance match",
211
+ });
212
+ if (limit !== null && items.length >= limit) break;
213
+ }
214
+ return { items, droppedItems };
215
+ },
216
+
217
+ async delete(memoryId, opts = {}) {
218
+ const orgId = requireOrgId(opts.orgId);
219
+ const db = await resolveDriver();
220
+ const { rowCount } = await db.query("DELETE FROM memory_records WHERE memory_id = $1 AND org_id = $2", [memoryId, orgId]);
221
+ return { deleted: (rowCount ?? 0) > 0, memoryId };
222
+ },
223
+
224
+ async purgeExpired(opts = {}) {
225
+ const orgId = requireOrgId(opts.orgId);
226
+ const db = await resolveDriver();
227
+ const { rowCount } = await db.query("DELETE FROM memory_records WHERE org_id = $1 AND forget_after <= $2", [orgId, isoNow(now)]);
228
+ return { purged: rowCount ?? 0 };
229
+ },
230
+
231
+ async close() {
232
+ if (ownsDriver && driver?.end) await driver.end();
233
+ },
234
+ };
235
+ }
236
+
237
+ // --- internals -------------------------------------------------------------
238
+
239
+ function requireOrgId(orgId) {
240
+ if (typeof orgId !== "string" || orgId.length === 0) {
241
+ throw new HostedStoreError("org_isolation_required", "hosted memory operations require an orgId; org-scoped isolation cannot be bypassed");
242
+ }
243
+ return orgId;
244
+ }
245
+
246
+ function canReadMemory(record, actor) {
247
+ const allowedActorIds = record.scope?.allowedActorIds ?? [];
248
+ if (allowedActorIds.length > 0 && !allowedActorIds.includes(actor.actorId)) return false;
249
+ const actorScopes = new Set(actor.scopes ?? []);
250
+ return (record.scope?.allowedScopes ?? []).every((scope) => actorScopes.has(scope));
251
+ }
252
+
253
+ function redactForRecall(record) {
254
+ if (record.redaction?.mode === "omitted") {
255
+ return { ...record, content: undefined, summary: "[omitted]" };
256
+ }
257
+ if (record.redaction?.mode !== "redacted") return record;
258
+ return {
259
+ ...record,
260
+ content: redactString(record.content),
261
+ summary: redactString(record.summary),
262
+ };
263
+ }
264
+
265
+ function redactString(value) {
266
+ if (typeof value !== "string") return value;
267
+ return value.replace(/(secret|token|password|credential)[^\s]*/gi, "[redacted]");
268
+ }
269
+
270
+ function formatVector(vectorArray) {
271
+ return `[${vectorArray.join(",")}]`;
272
+ }
273
+
274
+ function isoNow(now) {
275
+ return now().toISOString();
276
+ }
277
+
278
+ export { cosineSimilarity };