@rine-kit/agent-memory-postgres 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/dist/consolidation.d.ts +150 -0
- package/dist/consolidation.js +1072 -0
- package/dist/conversation-checkpoints.d.ts +15 -0
- package/dist/conversation-checkpoints.js +72 -0
- package/dist/dreaming-run-store.d.ts +15 -0
- package/dist/dreaming-run-store.js +22 -0
- package/dist/embedding-budget.d.ts +9 -0
- package/dist/embedding-budget.js +45 -0
- package/dist/index-generation.d.ts +39 -0
- package/dist/index-generation.js +229 -0
- package/dist/index-worker.d.ts +17 -0
- package/dist/index-worker.js +266 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +10 -0
- package/dist/migrate.d.ts +10 -0
- package/dist/migrate.js +63 -0
- package/dist/retention.d.ts +13 -0
- package/dist/retention.js +14 -0
- package/dist/scope.d.ts +23 -0
- package/dist/scope.js +25 -0
- package/dist/store.d.ts +48 -0
- package/dist/store.js +490 -0
- package/migrations/0001_memory_foundation.sql +67 -0
- package/migrations/0002_memory_embedding_index.sql +76 -0
- package/migrations/0003_memory_dreaming_runs.sql +19 -0
- package/migrations/0004_memory_consolidation.sql +101 -0
- package/migrations/0005_memory_conversation_checkpoints.sql +18 -0
- package/migrations/vector/0001_memory_pgvector.sql +34 -0
- package/package.json +40 -3
- package/README.md +0 -3
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { estimateMemoryEmbeddingTokens } from '@rine-kit/agent-memory';
|
|
3
|
+
import { reserveMemoryEmbeddingBudget, settleMemoryEmbeddingBudget } from './embedding-budget.js';
|
|
4
|
+
import { MemoryIndexGenerationManager } from './index-generation.js';
|
|
5
|
+
function vectorLiteral(values) {
|
|
6
|
+
return `[${values
|
|
7
|
+
.map((value) => {
|
|
8
|
+
if (!Number.isFinite(value))
|
|
9
|
+
throw new Error('agent_memory_embedding_vector_invalid');
|
|
10
|
+
return String(value);
|
|
11
|
+
})
|
|
12
|
+
.join(',')}]`;
|
|
13
|
+
}
|
|
14
|
+
async function transaction(pool, work) {
|
|
15
|
+
const client = await pool.connect();
|
|
16
|
+
try {
|
|
17
|
+
await client.query('BEGIN');
|
|
18
|
+
const result = await work(client);
|
|
19
|
+
await client.query('COMMIT');
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
await client.query('ROLLBACK').catch(() => undefined);
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
client.release();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class MemoryIndexWorker {
|
|
31
|
+
pool;
|
|
32
|
+
provider;
|
|
33
|
+
maxAttempts;
|
|
34
|
+
constructor(pool, provider, maxAttempts = 6) {
|
|
35
|
+
this.pool = pool;
|
|
36
|
+
this.provider = provider;
|
|
37
|
+
this.maxAttempts = maxAttempts;
|
|
38
|
+
if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 12) {
|
|
39
|
+
throw new Error('agent_memory_embedding_worker_limits_invalid');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async claim() {
|
|
43
|
+
const result = await this.pool.query(`WITH candidate AS (
|
|
44
|
+
SELECT job.job_id FROM agent_memory_embedding_jobs job
|
|
45
|
+
WHERE ((job.status IN ('pending','retry') AND job.next_attempt_at<=now())
|
|
46
|
+
OR (job.status='processing' AND job.lease_until<=now()))
|
|
47
|
+
AND (job.operation='delete' OR $1::TEXT IS NULL OR (
|
|
48
|
+
job.index_version=$4 AND (
|
|
49
|
+
EXISTS (SELECT 1 FROM agent_memory_entries memory
|
|
50
|
+
JOIN agent_memory_index_generation_state state USING (namespace)
|
|
51
|
+
WHERE memory.memory_id=job.memory_id AND state.active_index_version=job.index_version
|
|
52
|
+
AND state.active_provider_id=$1 AND state.active_model_id=$2 AND state.active_dimensions=$3)
|
|
53
|
+
OR EXISTS (SELECT 1 FROM agent_memory_entries memory
|
|
54
|
+
JOIN agent_memory_index_generation_state state USING (namespace)
|
|
55
|
+
WHERE memory.memory_id=job.memory_id AND state.reindex_status='building'
|
|
56
|
+
AND state.building_index_version=job.index_version
|
|
57
|
+
AND state.building_provider_id=$1 AND state.building_model_id=$2
|
|
58
|
+
AND state.building_dimensions=$3)
|
|
59
|
+
OR (job.index_version=1 AND NOT EXISTS (SELECT 1 FROM agent_memory_entries memory
|
|
60
|
+
JOIN agent_memory_index_generation_state state USING (namespace)
|
|
61
|
+
WHERE memory.memory_id=job.memory_id))
|
|
62
|
+
)
|
|
63
|
+
))
|
|
64
|
+
ORDER BY (job.operation='delete') DESC,job.next_attempt_at,job.created_at,job.job_id
|
|
65
|
+
FOR UPDATE OF job SKIP LOCKED LIMIT 1
|
|
66
|
+
)
|
|
67
|
+
UPDATE agent_memory_embedding_jobs job SET status='processing',attempt_count=job.attempt_count+1,
|
|
68
|
+
lease_token=gen_random_uuid(),lease_until=now()+interval '60 seconds',updated_at=now()
|
|
69
|
+
FROM candidate WHERE job.job_id=candidate.job_id
|
|
70
|
+
RETURNING job.job_id,job.memory_id,job.source_revision,job.index_version,job.operation,job.attempt_count,job.lease_token`, [
|
|
71
|
+
this.provider?.contract.providerId ?? null,
|
|
72
|
+
this.provider?.contract.modelId ?? null,
|
|
73
|
+
this.provider?.contract.dimensions ?? null,
|
|
74
|
+
this.provider?.contract.indexVersion ?? null,
|
|
75
|
+
]);
|
|
76
|
+
return result.rows[0] ?? null;
|
|
77
|
+
}
|
|
78
|
+
async availability() {
|
|
79
|
+
const result = await this.pool.query(`SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname='vector') AS extension,
|
|
80
|
+
to_regclass('agent_memory_embeddings') IS NOT NULL AS table`);
|
|
81
|
+
return result.rows[0] ?? { extension: false, table: false };
|
|
82
|
+
}
|
|
83
|
+
async releaseUnconfigured(job) {
|
|
84
|
+
await this.pool.query(`UPDATE agent_memory_embedding_jobs SET status='retry',lease_token=NULL,lease_until=NULL,
|
|
85
|
+
next_attempt_at=now()+interval '5 minutes',updated_at=now()
|
|
86
|
+
WHERE job_id=$1 AND status='processing' AND lease_token=$2`, [job.job_id, job.lease_token]);
|
|
87
|
+
}
|
|
88
|
+
async finish(job) {
|
|
89
|
+
await this.pool.query(`UPDATE agent_memory_embedding_jobs SET status='done',lease_token=NULL,lease_until=NULL,
|
|
90
|
+
last_error_code=NULL,finished_at=now(),updated_at=now()
|
|
91
|
+
WHERE job_id=$1 AND status='processing' AND lease_token=$2`, [job.job_id, job.lease_token]);
|
|
92
|
+
}
|
|
93
|
+
async failed(job, reason) {
|
|
94
|
+
const dead = job.attempt_count >= this.maxAttempts;
|
|
95
|
+
const delaySeconds = Math.min(3600, 5 * 2 ** Math.min(job.attempt_count, 10));
|
|
96
|
+
await this.pool.query(`UPDATE agent_memory_embedding_jobs SET status=$3,lease_token=NULL,lease_until=NULL,
|
|
97
|
+
last_error_code=$4,next_attempt_at=now()+($5::INTEGER*interval '1 second'),
|
|
98
|
+
finished_at=CASE WHEN $3='dead' THEN now() ELSE NULL END,updated_at=now()
|
|
99
|
+
WHERE job_id=$1 AND status='processing' AND lease_token=$2`, [job.job_id, job.lease_token, dead ? 'dead' : 'retry', reason, delaySeconds]);
|
|
100
|
+
return dead ? 'dead' : 'retry';
|
|
101
|
+
}
|
|
102
|
+
async memory(job) {
|
|
103
|
+
const result = await this.pool.query(`SELECT memory.memory_id,memory.namespace,memory.scope_kind,memory.scope_key,
|
|
104
|
+
memory.memory_key,memory.content,
|
|
105
|
+
memory.revision,memory.revoked_at
|
|
106
|
+
FROM agent_memory_entries memory WHERE memory.memory_id=$1`, [job.memory_id]);
|
|
107
|
+
return result.rows[0] ?? null;
|
|
108
|
+
}
|
|
109
|
+
async writeEmbedding(job, memory, batch) {
|
|
110
|
+
const vector = batch.vectors[0];
|
|
111
|
+
const contentHash = batch.contentHashes[0];
|
|
112
|
+
const norm = vector?.reduce((sum, value) => sum + value * value, 0) ?? 0;
|
|
113
|
+
if (!this.provider ||
|
|
114
|
+
!vector ||
|
|
115
|
+
!contentHash ||
|
|
116
|
+
batch.vectors.length !== 1 ||
|
|
117
|
+
batch.contract.modelId !== this.provider.contract.modelId ||
|
|
118
|
+
batch.contract.providerId !== this.provider.contract.providerId ||
|
|
119
|
+
batch.contract.dimensions !== this.provider.contract.dimensions ||
|
|
120
|
+
batch.contract.normalization !== 'l2_unit' ||
|
|
121
|
+
batch.contract.indexVersion !== this.provider.contract.indexVersion ||
|
|
122
|
+
batch.contract.indexVersion !== job.index_version ||
|
|
123
|
+
vector.length !== this.provider.contract.dimensions ||
|
|
124
|
+
vector.some((value) => !Number.isFinite(value)) ||
|
|
125
|
+
!Number.isFinite(norm) ||
|
|
126
|
+
Math.abs(Math.sqrt(norm) - 1) > 1e-3) {
|
|
127
|
+
throw new Error('agent_memory_embedding_contract_invalid');
|
|
128
|
+
}
|
|
129
|
+
const currentTextHash = createHash('sha256')
|
|
130
|
+
.update(`${memory.memory_key}\n${memory.content}`)
|
|
131
|
+
.digest('hex');
|
|
132
|
+
if (contentHash !== currentTextHash)
|
|
133
|
+
throw new Error('agent_memory_embedding_content_hash_invalid');
|
|
134
|
+
return transaction(this.pool, async (client) => {
|
|
135
|
+
const current = await client.query(`SELECT memory.memory_id,memory.namespace,memory.scope_kind,memory.scope_key,
|
|
136
|
+
memory.memory_key,memory.content,
|
|
137
|
+
memory.revision,memory.revoked_at
|
|
138
|
+
FROM agent_memory_entries memory WHERE memory.memory_id=$1 FOR UPDATE`, [job.memory_id]);
|
|
139
|
+
const row = current.rows[0];
|
|
140
|
+
if (!row || String(row.revision) !== job.source_revision || row.revoked_at !== null) {
|
|
141
|
+
if (!row || row.revoked_at !== null) {
|
|
142
|
+
await client.query('DELETE FROM agent_memory_embeddings WHERE memory_id=$1', [
|
|
143
|
+
job.memory_id,
|
|
144
|
+
]);
|
|
145
|
+
}
|
|
146
|
+
await client.query(`UPDATE agent_memory_embedding_jobs SET status='done',lease_token=NULL,lease_until=NULL,
|
|
147
|
+
finished_at=now(),updated_at=now() WHERE job_id=$1 AND status='processing' AND lease_token=$2`, [job.job_id, job.lease_token]);
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
const generation = await client.query(`SELECT active_index_version,active_provider_id,active_model_id,active_dimensions,
|
|
151
|
+
building_index_version,building_provider_id,building_model_id,building_dimensions,reindex_status
|
|
152
|
+
FROM agent_memory_index_generation_state WHERE namespace=$1 FOR SHARE`, [memory.namespace]);
|
|
153
|
+
const state = generation.rows[0];
|
|
154
|
+
const generationAllowed = state
|
|
155
|
+
? (state.active_index_version === job.index_version &&
|
|
156
|
+
state.active_provider_id === batch.contract.providerId &&
|
|
157
|
+
state.active_model_id === batch.contract.modelId &&
|
|
158
|
+
state.active_dimensions === batch.contract.dimensions) ||
|
|
159
|
+
(state.reindex_status === 'building' &&
|
|
160
|
+
state.building_index_version === job.index_version &&
|
|
161
|
+
state.building_provider_id === batch.contract.providerId &&
|
|
162
|
+
state.building_model_id === batch.contract.modelId &&
|
|
163
|
+
state.building_dimensions === batch.contract.dimensions)
|
|
164
|
+
: job.index_version === 1;
|
|
165
|
+
if (!generationAllowed) {
|
|
166
|
+
await client.query(`UPDATE agent_memory_embedding_jobs SET status='done',lease_token=NULL,lease_until=NULL,
|
|
167
|
+
finished_at=now(),updated_at=now() WHERE job_id=$1 AND status='processing' AND lease_token=$2`, [job.job_id, job.lease_token]);
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
await client.query(`INSERT INTO agent_memory_embeddings(
|
|
171
|
+
memory_id,namespace,scope_kind,scope_key,
|
|
172
|
+
source_revision,provider_id,model_id,dimensions,normalization,index_version,content_hash,embedding
|
|
173
|
+
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'l2_unit',$9,$10,$11::vector)
|
|
174
|
+
ON CONFLICT (memory_id,provider_id,model_id,index_version) DO UPDATE SET
|
|
175
|
+
namespace=EXCLUDED.namespace,scope_kind=EXCLUDED.scope_kind,scope_key=EXCLUDED.scope_key,
|
|
176
|
+
source_revision=EXCLUDED.source_revision,
|
|
177
|
+
dimensions=EXCLUDED.dimensions,normalization=EXCLUDED.normalization,
|
|
178
|
+
content_hash=EXCLUDED.content_hash,embedding=EXCLUDED.embedding,created_at=now()`, [
|
|
179
|
+
row.memory_id,
|
|
180
|
+
row.namespace,
|
|
181
|
+
row.scope_kind,
|
|
182
|
+
row.scope_key,
|
|
183
|
+
row.revision,
|
|
184
|
+
batch.contract.providerId,
|
|
185
|
+
batch.contract.modelId,
|
|
186
|
+
batch.contract.dimensions,
|
|
187
|
+
batch.contract.indexVersion,
|
|
188
|
+
contentHash,
|
|
189
|
+
vectorLiteral(vector),
|
|
190
|
+
]);
|
|
191
|
+
await client.query(`UPDATE agent_memory_embedding_jobs SET status='done',lease_token=NULL,lease_until=NULL,
|
|
192
|
+
last_error_code=NULL,finished_at=now(),updated_at=now()
|
|
193
|
+
WHERE job_id=$1 AND status='processing' AND lease_token=$2`, [job.job_id, job.lease_token]);
|
|
194
|
+
return true;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
async processOne(signal) {
|
|
198
|
+
const job = await this.claim();
|
|
199
|
+
if (!job)
|
|
200
|
+
return 'empty';
|
|
201
|
+
if (job.operation === 'delete') {
|
|
202
|
+
try {
|
|
203
|
+
const availability = await this.availability();
|
|
204
|
+
if (availability.table)
|
|
205
|
+
await this.pool.query('DELETE FROM agent_memory_embeddings WHERE memory_id=$1', [
|
|
206
|
+
job.memory_id,
|
|
207
|
+
]);
|
|
208
|
+
await this.finish(job);
|
|
209
|
+
return 'deleted';
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return this.failed(job, 'embedding_delete_failed');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (!this.provider) {
|
|
216
|
+
await this.releaseUnconfigured(job);
|
|
217
|
+
return 'semantic_unconfigured';
|
|
218
|
+
}
|
|
219
|
+
let reservedTokens = 0;
|
|
220
|
+
let budgetDay = null;
|
|
221
|
+
let settled = false;
|
|
222
|
+
try {
|
|
223
|
+
const availability = await this.availability();
|
|
224
|
+
if (!availability.extension || !availability.table) {
|
|
225
|
+
await this.releaseUnconfigured(job);
|
|
226
|
+
return 'semantic_unconfigured';
|
|
227
|
+
}
|
|
228
|
+
const row = await this.memory(job);
|
|
229
|
+
if (!row || row.revoked_at !== null || String(row.revision) !== job.source_revision) {
|
|
230
|
+
if (!row || row.revoked_at !== null) {
|
|
231
|
+
await this.pool.query('DELETE FROM agent_memory_embeddings WHERE memory_id=$1', [
|
|
232
|
+
job.memory_id,
|
|
233
|
+
]);
|
|
234
|
+
}
|
|
235
|
+
await this.finish(job);
|
|
236
|
+
return 'obsolete';
|
|
237
|
+
}
|
|
238
|
+
if (job.index_version === 1) {
|
|
239
|
+
await new MemoryIndexGenerationManager(this.pool).initialize(row.namespace, this.provider.contract);
|
|
240
|
+
}
|
|
241
|
+
const value = `${row.memory_key}\n${row.content}`;
|
|
242
|
+
reservedTokens = estimateMemoryEmbeddingTokens([value]);
|
|
243
|
+
budgetDay = await reserveMemoryEmbeddingBudget(this.pool, row.namespace, reservedTokens, this.provider);
|
|
244
|
+
if (!budgetDay) {
|
|
245
|
+
await this.releaseUnconfigured(job);
|
|
246
|
+
return 'budget_deferred';
|
|
247
|
+
}
|
|
248
|
+
const batch = await this.provider.embedMany([value], signal);
|
|
249
|
+
await settleMemoryEmbeddingBudget(this.pool, row.namespace, budgetDay, reservedTokens, batch.inputTokens);
|
|
250
|
+
settled = true;
|
|
251
|
+
const written = await this.writeEmbedding(job, row, batch);
|
|
252
|
+
return written ? 'indexed' : 'obsolete';
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
if (budgetDay && !settled) {
|
|
256
|
+
const row = await this.memory(job).catch(() => null);
|
|
257
|
+
if (row)
|
|
258
|
+
await settleMemoryEmbeddingBudget(this.pool, row.namespace, budgetDay, reservedTokens, null).catch(() => undefined);
|
|
259
|
+
}
|
|
260
|
+
const reason = error instanceof Error && /^[a-z0-9_]{1,64}$/u.test(error.message)
|
|
261
|
+
? error.message
|
|
262
|
+
: 'embedding_index_failed';
|
|
263
|
+
return this.failed(job, reason);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { PostgresMemoryStore, canonicalStoredMemoryKey, validateStoredMemoryDraft, } from './store.js';
|
|
2
|
+
export type { PostgresMemoryStoreOptions } from './store.js';
|
|
3
|
+
export { boundedText, scopeArgs, SCOPE_FILTER } from './scope.js';
|
|
4
|
+
export type { MemoryAuthorization, MemoryScope } from './scope.js';
|
|
5
|
+
export { reserveMemoryEmbeddingBudget, settleMemoryEmbeddingBudget } from './embedding-budget.js';
|
|
6
|
+
export type { MemoryEmbeddingBudgetLimits } from './embedding-budget.js';
|
|
7
|
+
export { MemoryIndexGenerationManager } from './index-generation.js';
|
|
8
|
+
export type { MemoryIndexGenerationState, MemoryIndexScanResult } from './index-generation.js';
|
|
9
|
+
export { MemoryIndexWorker } from './index-worker.js';
|
|
10
|
+
export type { MemoryIndexWorkerResult } from './index-worker.js';
|
|
11
|
+
export { PostgresMemoryDreamingRunStore } from './dreaming-run-store.js';
|
|
12
|
+
export type { MemoryDreamingRunIdentity } from './dreaming-run-store.js';
|
|
13
|
+
export { enableMemoryVectorIndex, memoryVectorAvailable, migrateMemoryDatabase, } from './migrate.js';
|
|
14
|
+
export { MemoryConsolidationCandidateSchema, MemoryConsolidationConsentService, MemoryConsolidationWorker, } from './consolidation.js';
|
|
15
|
+
export type { MemoryConsolidationConsent, MemoryConsolidationPlanner, MemoryConsolidationRun, MemoryConsolidationWorkerOptions, MemoryConsolidationWorkflow, MemoryDeepRun, } from './consolidation.js';
|
|
16
|
+
export { loadConversationCheckpoint, refreshConversationCheckpoint, } from './conversation-checkpoints.js';
|
|
17
|
+
export type { ConversationCheckpointScope } from './conversation-checkpoints.js';
|
|
18
|
+
export { purgeExpiredMemoryData } from './retention.js';
|
|
19
|
+
export type { MemoryPurgeResult } from './retention.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { PostgresMemoryStore, canonicalStoredMemoryKey, validateStoredMemoryDraft, } from './store.js';
|
|
2
|
+
export { boundedText, scopeArgs, SCOPE_FILTER } from './scope.js';
|
|
3
|
+
export { reserveMemoryEmbeddingBudget, settleMemoryEmbeddingBudget } from './embedding-budget.js';
|
|
4
|
+
export { MemoryIndexGenerationManager } from './index-generation.js';
|
|
5
|
+
export { MemoryIndexWorker } from './index-worker.js';
|
|
6
|
+
export { PostgresMemoryDreamingRunStore } from './dreaming-run-store.js';
|
|
7
|
+
export { enableMemoryVectorIndex, memoryVectorAvailable, migrateMemoryDatabase, } from './migrate.js';
|
|
8
|
+
export { MemoryConsolidationCandidateSchema, MemoryConsolidationConsentService, MemoryConsolidationWorker, } from './consolidation.js';
|
|
9
|
+
export { loadConversationCheckpoint, refreshConversationCheckpoint, } from './conversation-checkpoints.js';
|
|
10
|
+
export { purgeExpiredMemoryData } from './retention.js';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
/** Creates or upgrades the memory tables. Needs nothing but built-in PostgreSQL types. */
|
|
3
|
+
export declare function migrateMemoryDatabase(pool: Pool): Promise<void>;
|
|
4
|
+
/** Whether the vector extension is installed (semantic recall can only work if it is). */
|
|
5
|
+
export declare function memoryVectorAvailable(pool: Pool): Promise<boolean>;
|
|
6
|
+
/**
|
|
7
|
+
* Creates the embeddings table. Requires the `vector` extension to be installed by an operator first;
|
|
8
|
+
* without it nothing else breaks and recall stays exact + lexical.
|
|
9
|
+
*/
|
|
10
|
+
export declare function enableMemoryVectorIndex(pool: Pool): Promise<void>;
|
package/dist/migrate.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
const MIGRATIONS = [
|
|
3
|
+
'0001_memory_foundation.sql',
|
|
4
|
+
'0002_memory_embedding_index.sql',
|
|
5
|
+
'0003_memory_dreaming_runs.sql',
|
|
6
|
+
'0004_memory_consolidation.sql',
|
|
7
|
+
'0005_memory_conversation_checkpoints.sql',
|
|
8
|
+
];
|
|
9
|
+
const VECTOR_MIGRATIONS = ['vector/0001_memory_pgvector.sql'];
|
|
10
|
+
const LOCK_ID = 7192041302;
|
|
11
|
+
async function apply(pool, ids, ledger) {
|
|
12
|
+
const client = await pool.connect();
|
|
13
|
+
try {
|
|
14
|
+
await client.query('BEGIN');
|
|
15
|
+
await client.query('SELECT pg_advisory_xact_lock($1)', [LOCK_ID]);
|
|
16
|
+
await client.query(`CREATE TABLE IF NOT EXISTS agent_memory_schema_migrations (
|
|
17
|
+
migration_id TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
|
|
18
|
+
for (const id of ids) {
|
|
19
|
+
const key = `${ledger}${id}`;
|
|
20
|
+
if ((await client.query('SELECT 1 FROM agent_memory_schema_migrations WHERE migration_id=$1', [
|
|
21
|
+
key,
|
|
22
|
+
])).rowCount)
|
|
23
|
+
continue;
|
|
24
|
+
const sql = await readFile(new URL(`../migrations/${id}`, import.meta.url), 'utf8');
|
|
25
|
+
await client.query(sql);
|
|
26
|
+
await client.query('INSERT INTO agent_memory_schema_migrations(migration_id) VALUES ($1)', [
|
|
27
|
+
key,
|
|
28
|
+
]);
|
|
29
|
+
}
|
|
30
|
+
await client.query('COMMIT');
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
await rollbackQuietly(client);
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
client.release();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function rollbackQuietly(client) {
|
|
41
|
+
try {
|
|
42
|
+
await client.query('ROLLBACK');
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
/* keep the migration error */
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Creates or upgrades the memory tables. Needs nothing but built-in PostgreSQL types. */
|
|
49
|
+
export function migrateMemoryDatabase(pool) {
|
|
50
|
+
return apply(pool, MIGRATIONS, '');
|
|
51
|
+
}
|
|
52
|
+
/** Whether the vector extension is installed (semantic recall can only work if it is). */
|
|
53
|
+
export async function memoryVectorAvailable(pool) {
|
|
54
|
+
const result = await pool.query(`SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname='vector') AS ok`);
|
|
55
|
+
return result.rows[0]?.ok === true;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Creates the embeddings table. Requires the `vector` extension to be installed by an operator first;
|
|
59
|
+
* without it nothing else breaks and recall stays exact + lexical.
|
|
60
|
+
*/
|
|
61
|
+
export function enableMemoryVectorIndex(pool) {
|
|
62
|
+
return apply(pool, VECTOR_MIGRATIONS, 'vector:');
|
|
63
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
export interface MemoryPurgeResult {
|
|
3
|
+
observations: number;
|
|
4
|
+
admissions: number;
|
|
5
|
+
usageSignals: number;
|
|
6
|
+
candidates: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Deletes what has expired: observed utterances (7 days), finished admissions, usage evidence (90 days)
|
|
10
|
+
* and candidates (30 days). Run it with the daily Dreaming pass so personal text never outlives its
|
|
11
|
+
* retention window, whether or not a worker ever read it.
|
|
12
|
+
*/
|
|
13
|
+
export declare function purgeExpiredMemoryData(pool: Pool): Promise<MemoryPurgeResult>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deletes what has expired: observed utterances (7 days), finished admissions, usage evidence (90 days)
|
|
3
|
+
* and candidates (30 days). Run it with the daily Dreaming pass so personal text never outlives its
|
|
4
|
+
* retention window, whether or not a worker ever read it.
|
|
5
|
+
*/
|
|
6
|
+
export async function purgeExpiredMemoryData(pool) {
|
|
7
|
+
const count = async (sql) => (await pool.query(sql)).rowCount ?? 0;
|
|
8
|
+
const admissions = await count(`DELETE FROM agent_memory_consolidation_admissions
|
|
9
|
+
WHERE expires_at<=now() AND status<>'processing'`);
|
|
10
|
+
const observations = await count(`DELETE FROM agent_memory_observations WHERE expires_at<=now()`);
|
|
11
|
+
const usageSignals = await count(`DELETE FROM agent_memory_usage_signals WHERE expires_at<=now()`);
|
|
12
|
+
const candidates = await count(`DELETE FROM agent_memory_consolidation_candidates WHERE expires_at<=now()`);
|
|
13
|
+
return { observations, admissions, usageSignals, candidates };
|
|
14
|
+
}
|
package/dist/scope.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which memories an operation may touch. The host builds this from *authenticated* data (who is asking,
|
|
3
|
+
* which room / space / tenant) after it has authorised the access; this package never derives it from
|
|
4
|
+
* anything a model or a chat wrote. `kind` names the level (for example "user", "room", "space") and
|
|
5
|
+
* `key` identifies it; `namespace` separates agents (Gate's bot account) sharing one database.
|
|
6
|
+
*/
|
|
7
|
+
export interface MemoryScope {
|
|
8
|
+
namespace: string;
|
|
9
|
+
kind: string;
|
|
10
|
+
key: string;
|
|
11
|
+
}
|
|
12
|
+
/** What the host hands over for one trusted request. */
|
|
13
|
+
export interface MemoryAuthorization {
|
|
14
|
+
scope: MemoryScope;
|
|
15
|
+
/** Identifier of the trusted request / event this operation belongs to; stored as provenance. */
|
|
16
|
+
eventId: string;
|
|
17
|
+
/** When that event was received: a tombstone can only be restored by a later event. */
|
|
18
|
+
receivedAt: Date;
|
|
19
|
+
}
|
|
20
|
+
export declare function boundedText(value: string, max: number, emojiSequence?: boolean): string;
|
|
21
|
+
/** The three scope parameters ($1..$3) of every scoped statement. */
|
|
22
|
+
export declare function scopeArgs(scope: MemoryScope): [string, string, string];
|
|
23
|
+
export declare const SCOPE_FILTER = "namespace=$1 AND scope_kind=$2 AND scope_key=$3";
|
package/dist/scope.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export function boundedText(value, max, emojiSequence = false) {
|
|
2
|
+
if (typeof value !== 'string')
|
|
3
|
+
throw new Error('agent_memory_input_invalid');
|
|
4
|
+
const text = value.normalize('NFC').trim();
|
|
5
|
+
if (!text || text.length > max || /[\p{Cc}\p{Cs}]/u.test(text))
|
|
6
|
+
throw new Error('agent_memory_input_invalid');
|
|
7
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
8
|
+
if (!/\p{Cf}/u.test(text[i]))
|
|
9
|
+
continue;
|
|
10
|
+
// ZWJ is legitimate between emoji pictographs, not in keys or words.
|
|
11
|
+
if (!emojiSequence ||
|
|
12
|
+
text[i] !== '' ||
|
|
13
|
+
!/\p{Extended_Pictographic}(?:\p{Emoji_Modifier}|️)?$/u.test(text.slice(0, i)) ||
|
|
14
|
+
!/^\p{Extended_Pictographic}/u.test(text.slice(i + 1)))
|
|
15
|
+
throw new Error('agent_memory_input_invalid');
|
|
16
|
+
}
|
|
17
|
+
return text;
|
|
18
|
+
}
|
|
19
|
+
/** The three scope parameters ($1..$3) of every scoped statement. */
|
|
20
|
+
export function scopeArgs(scope) {
|
|
21
|
+
if (!/^[a-z][a-z0-9_]{0,31}$/u.test(scope.kind))
|
|
22
|
+
throw new Error('agent_memory_scope_invalid');
|
|
23
|
+
return [boundedText(scope.namespace, 128), scope.kind, boundedText(scope.key, 256)];
|
|
24
|
+
}
|
|
25
|
+
export const SCOPE_FILTER = 'namespace=$1 AND scope_kind=$2 AND scope_key=$3';
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
import type { MemoryDraft, MemoryEmbeddingClient, MemoryEntry, MemoryRecallStoragePort, MemorySearchSources, MemoryUsageSignal, MemoryUsageSignalKind, MemoryWriteMetadata, MemoryWriteState, MemoryWriteStoragePort } from '@rine-kit/agent-memory';
|
|
3
|
+
import { type MemoryAuthorization } from './scope.js';
|
|
4
|
+
export interface PostgresMemoryStoreOptions {
|
|
5
|
+
/** Statement timeout for lexical and vector scans. */
|
|
6
|
+
searchTimeoutMs?: number;
|
|
7
|
+
/** Semantic search is off (reason `semantic_unconfigured`) without a provider. */
|
|
8
|
+
embedding?: MemoryEmbeddingClient | null;
|
|
9
|
+
/**
|
|
10
|
+
* Called before every operation on a request's scope. The scope itself is already authorised by the
|
|
11
|
+
* host; this lets a host re-check at the last moment (membership revoked, lease expired) and throw.
|
|
12
|
+
*/
|
|
13
|
+
authorize?: (authorization: MemoryAuthorization) => Promise<void> | void;
|
|
14
|
+
}
|
|
15
|
+
export declare function validateStoredMemoryDraft(input: MemoryDraft): MemoryDraft;
|
|
16
|
+
export declare function canonicalStoredMemoryKey(value: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Scoped memory storage on PostgreSQL. Every statement is filtered by the scope the host authorised for
|
|
19
|
+
* this request; entries carry source trust, freshness and supersession metadata; writes are
|
|
20
|
+
* revision-fenced and queue embedding work in the same statement. Implements the recall and write
|
|
21
|
+
* storage ports of @rine-kit/agent-memory.
|
|
22
|
+
*/
|
|
23
|
+
export declare class PostgresMemoryStore implements MemoryRecallStoragePort<MemoryAuthorization>, MemoryWriteStoragePort<MemoryAuthorization> {
|
|
24
|
+
private readonly pool;
|
|
25
|
+
private readonly searchTimeoutMs;
|
|
26
|
+
private readonly embedding;
|
|
27
|
+
private readonly authorize;
|
|
28
|
+
constructor(pool: Pool, options?: PostgresMemoryStoreOptions);
|
|
29
|
+
private scope;
|
|
30
|
+
/** Authorises once, then exposes only scoped reads. */
|
|
31
|
+
withAuthorizedSearch<T>(authorization: MemoryAuthorization, work: (sources: MemorySearchSources) => Promise<T>): Promise<T>;
|
|
32
|
+
/** Persist only keyed usage evidence; query text and memory content are not copied. */
|
|
33
|
+
recordUsageSignals(authorization: MemoryAuthorization, kind: MemoryUsageSignalKind, signals: readonly MemoryUsageSignal[]): Promise<void>;
|
|
34
|
+
listRecent(authorization: MemoryAuthorization, limit?: number): Promise<MemoryEntry[]>;
|
|
35
|
+
getWriteState(authorization: MemoryAuthorization, key: string): Promise<MemoryWriteState | null>;
|
|
36
|
+
private searchExact;
|
|
37
|
+
private timedQuery;
|
|
38
|
+
private searchLexical;
|
|
39
|
+
private searchVector;
|
|
40
|
+
private searchSemantic;
|
|
41
|
+
/** New key only; a conflicting revision/tombstone is never overwritten. */
|
|
42
|
+
create(authorization: MemoryAuthorization, draft: MemoryDraft, metadata?: MemoryWriteMetadata): Promise<'created' | 'already_exists'>;
|
|
43
|
+
revise(authorization: MemoryAuthorization, draft: MemoryDraft, expectedRevision: number, metadata?: MemoryWriteMetadata): Promise<boolean>;
|
|
44
|
+
/** Only an event received after revocation can restore a tombstone. */
|
|
45
|
+
rememberAgain(authorization: MemoryAuthorization, draft: MemoryDraft, expectedRevision: number, metadata?: MemoryWriteMetadata): Promise<boolean>;
|
|
46
|
+
/** Tombstone removes stored text, usage evidence, and stale episodic candidates. */
|
|
47
|
+
forget(authorization: MemoryAuthorization, key: string, expectedRevision?: number): Promise<boolean>;
|
|
48
|
+
}
|