@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
package/dist/store.js
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { MAX_MEMORY_RESULTS, MemoryPolicyError, canonicalizeMemoryKey, estimateMemoryEmbeddingTokens, memorySearchTokens, validateMemoryDraft, } from '@rine-kit/agent-memory';
|
|
3
|
+
import { reserveMemoryEmbeddingBudget, settleMemoryEmbeddingBudget } from './embedding-budget.js';
|
|
4
|
+
import { boundedText, scopeArgs, SCOPE_FILTER } from './scope.js';
|
|
5
|
+
const DEFAULT_SEARCH_TIMEOUT_MS = 500;
|
|
6
|
+
const ACTIVE = `revoked_at IS NULL AND superseded_at IS NULL
|
|
7
|
+
AND (valid_until IS NULL OR valid_until>now()) AND source_kind<>'unknown'`;
|
|
8
|
+
const ACTIVE_JOINED = `memory.revoked_at IS NULL AND memory.superseded_at IS NULL
|
|
9
|
+
AND (memory.valid_until IS NULL OR memory.valid_until>now()) AND memory.source_kind<>'unknown'`;
|
|
10
|
+
const COLUMNS = `memory_key,content,revision,updated_at,source_event_id,source_kind,
|
|
11
|
+
source_reliability,valid_until`;
|
|
12
|
+
const enqueueUpserts = (source) => `INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation,index_version)
|
|
13
|
+
SELECT ${source}.memory_id,${source}.revision,'upsert',generation.index_version FROM ${source}
|
|
14
|
+
CROSS JOIN LATERAL agent_memory_index_job_versions(${source}.namespace) generation
|
|
15
|
+
ON CONFLICT DO NOTHING RETURNING job_id`;
|
|
16
|
+
function vectorLiteral(values) {
|
|
17
|
+
if (!values.length || values.some((value) => !Number.isFinite(value)))
|
|
18
|
+
throw new Error('agent_memory_embedding_vector_invalid');
|
|
19
|
+
return `[${values.map(String).join(',')}]`;
|
|
20
|
+
}
|
|
21
|
+
function withPolicyErrors(work) {
|
|
22
|
+
try {
|
|
23
|
+
return work();
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error instanceof MemoryPolicyError)
|
|
27
|
+
throw new Error(`agent_memory_${error.code}`, { cause: error });
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function validateStoredMemoryDraft(input) {
|
|
32
|
+
return withPolicyErrors(() => validateMemoryDraft(input));
|
|
33
|
+
}
|
|
34
|
+
export function canonicalStoredMemoryKey(value) {
|
|
35
|
+
return withPolicyErrors(() => canonicalizeMemoryKey(value));
|
|
36
|
+
}
|
|
37
|
+
function validatedWriteMetadata(input = {}) {
|
|
38
|
+
const sourceKind = input.sourceKind ?? 'trusted_ingress';
|
|
39
|
+
if (!['trusted_ingress', 'user_confirmed', 'system_verified', 'unknown'].includes(sourceKind)) {
|
|
40
|
+
throw new Error('agent_memory_source_kind_invalid');
|
|
41
|
+
}
|
|
42
|
+
const sourceReliability = input.sourceReliability ?? (sourceKind === 'user_confirmed' ? 95 : 80);
|
|
43
|
+
if (!Number.isSafeInteger(sourceReliability) ||
|
|
44
|
+
sourceReliability < 0 ||
|
|
45
|
+
sourceReliability > 100) {
|
|
46
|
+
throw new Error('agent_memory_source_reliability_invalid');
|
|
47
|
+
}
|
|
48
|
+
let validUntil = null;
|
|
49
|
+
if (input.validUntil != null) {
|
|
50
|
+
const timestamp = Date.parse(input.validUntil);
|
|
51
|
+
if (!Number.isFinite(timestamp))
|
|
52
|
+
throw new Error('agent_memory_valid_until_invalid');
|
|
53
|
+
validUntil = new Date(timestamp).toISOString();
|
|
54
|
+
}
|
|
55
|
+
return { sourceKind, sourceReliability, validUntil };
|
|
56
|
+
}
|
|
57
|
+
function project(row) {
|
|
58
|
+
return {
|
|
59
|
+
key: String(row.memory_key),
|
|
60
|
+
content: String(row.content),
|
|
61
|
+
revision: Number(row.revision),
|
|
62
|
+
updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : String(row.updated_at),
|
|
63
|
+
sourceEventId: String(row.source_event_id),
|
|
64
|
+
sourceKind: row.source_kind === 'user_confirmed' ||
|
|
65
|
+
row.source_kind === 'system_verified' ||
|
|
66
|
+
row.source_kind === 'unknown'
|
|
67
|
+
? row.source_kind
|
|
68
|
+
: 'trusted_ingress',
|
|
69
|
+
sourceReliability: Number(row.source_reliability),
|
|
70
|
+
validUntil: row.valid_until == null
|
|
71
|
+
? null
|
|
72
|
+
: row.valid_until instanceof Date
|
|
73
|
+
? row.valid_until.toISOString()
|
|
74
|
+
: String(row.valid_until),
|
|
75
|
+
...(row.semantic_similarity == null
|
|
76
|
+
? {}
|
|
77
|
+
: { semanticSimilarity: Number(row.semantic_similarity) }),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function checkLimit(limit) {
|
|
81
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_MEMORY_RESULTS)
|
|
82
|
+
throw new Error('agent_memory_limit_invalid');
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Scoped memory storage on PostgreSQL. Every statement is filtered by the scope the host authorised for
|
|
86
|
+
* this request; entries carry source trust, freshness and supersession metadata; writes are
|
|
87
|
+
* revision-fenced and queue embedding work in the same statement. Implements the recall and write
|
|
88
|
+
* storage ports of @rine-kit/agent-memory.
|
|
89
|
+
*/
|
|
90
|
+
export class PostgresMemoryStore {
|
|
91
|
+
pool;
|
|
92
|
+
searchTimeoutMs;
|
|
93
|
+
embedding;
|
|
94
|
+
authorize;
|
|
95
|
+
constructor(pool, options = {}) {
|
|
96
|
+
this.pool = pool;
|
|
97
|
+
this.searchTimeoutMs = options.searchTimeoutMs ?? DEFAULT_SEARCH_TIMEOUT_MS;
|
|
98
|
+
this.embedding = options.embedding ?? null;
|
|
99
|
+
this.authorize = options.authorize;
|
|
100
|
+
if (!Number.isSafeInteger(this.searchTimeoutMs) ||
|
|
101
|
+
this.searchTimeoutMs < 10 ||
|
|
102
|
+
this.searchTimeoutMs > 10_000) {
|
|
103
|
+
throw new Error('agent_memory_search_timeout_invalid');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async scope(authorization) {
|
|
107
|
+
const scope = scopeArgs(authorization.scope);
|
|
108
|
+
await this.authorize?.(authorization);
|
|
109
|
+
return scope;
|
|
110
|
+
}
|
|
111
|
+
/** Authorises once, then exposes only scoped reads. */
|
|
112
|
+
async withAuthorizedSearch(authorization, work) {
|
|
113
|
+
const scope = await this.scope(authorization);
|
|
114
|
+
return work({
|
|
115
|
+
exact: (query, limit = 8) => this.searchExact(query, limit, scope),
|
|
116
|
+
lexical: (query, limit = 8) => this.searchLexical(query, limit, scope),
|
|
117
|
+
semantic: (query, limit = 8) => this.searchSemantic(query, limit, scope),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/** Persist only keyed usage evidence; query text and memory content are not copied. */
|
|
121
|
+
async recordUsageSignals(authorization, kind, signals) {
|
|
122
|
+
if (!signals.length)
|
|
123
|
+
return;
|
|
124
|
+
if (kind !== 'recalled' && kind !== 'used')
|
|
125
|
+
throw new Error('agent_memory_usage_signal_kind_invalid');
|
|
126
|
+
const valid = signals.filter((signal) => typeof signal.key === 'string' &&
|
|
127
|
+
signal.key.length > 0 &&
|
|
128
|
+
signal.key.length <= 96 &&
|
|
129
|
+
Number.isSafeInteger(signal.revision) &&
|
|
130
|
+
signal.revision > 0 &&
|
|
131
|
+
typeof signal.sourceEventId === 'string' &&
|
|
132
|
+
signal.sourceEventId.length > 0 &&
|
|
133
|
+
signal.sourceEventId.length <= 256 &&
|
|
134
|
+
/^[a-f0-9]{64}$/u.test(signal.queryFingerprint));
|
|
135
|
+
if (!valid.length)
|
|
136
|
+
return;
|
|
137
|
+
const scope = await this.scope(authorization);
|
|
138
|
+
const sql = `WITH requested AS (
|
|
139
|
+
SELECT * FROM unnest($5::TEXT[],$6::BIGINT[],$7::TEXT[],$8::CHAR(64)[])
|
|
140
|
+
AS item(memory_key,memory_revision,memory_source_event_id,query_fingerprint)
|
|
141
|
+
)
|
|
142
|
+
INSERT INTO agent_memory_usage_signals(
|
|
143
|
+
namespace,scope_kind,scope_key,
|
|
144
|
+
memory_key,memory_revision,memory_source_event_id,request_event_id,query_fingerprint,signal_kind
|
|
145
|
+
)
|
|
146
|
+
SELECT $1,$2,$3,item.memory_key,item.memory_revision,item.memory_source_event_id,
|
|
147
|
+
$4,item.query_fingerprint,$9
|
|
148
|
+
FROM requested item
|
|
149
|
+
JOIN agent_memory_entries memory ON memory.namespace=$1 AND memory.scope_kind=$2
|
|
150
|
+
AND memory.scope_key=$3
|
|
151
|
+
AND memory.memory_key=item.memory_key AND memory.revision=item.memory_revision
|
|
152
|
+
AND memory.source_event_id=item.memory_source_event_id
|
|
153
|
+
AND memory.revoked_at IS NULL AND memory.superseded_at IS NULL
|
|
154
|
+
AND (memory.valid_until IS NULL OR memory.valid_until>now()) AND memory.source_kind<>'unknown'
|
|
155
|
+
ON CONFLICT DO NOTHING`;
|
|
156
|
+
await this.pool.query(sql, [
|
|
157
|
+
...scope,
|
|
158
|
+
boundedText(authorization.eventId, 256),
|
|
159
|
+
valid.map((signal) => signal.key),
|
|
160
|
+
valid.map((signal) => signal.revision),
|
|
161
|
+
valid.map((signal) => signal.sourceEventId),
|
|
162
|
+
valid.map((signal) => signal.queryFingerprint),
|
|
163
|
+
kind,
|
|
164
|
+
]);
|
|
165
|
+
}
|
|
166
|
+
async listRecent(authorization, limit = 16) {
|
|
167
|
+
checkLimit(limit);
|
|
168
|
+
const scope = await this.scope(authorization);
|
|
169
|
+
const result = await this.pool.query(`SELECT ${COLUMNS} FROM agent_memory_entries WHERE ${SCOPE_FILTER} AND ${ACTIVE}
|
|
170
|
+
ORDER BY updated_at DESC,memory_id LIMIT $4`, [...scope, limit]);
|
|
171
|
+
return result.rows.map(project);
|
|
172
|
+
}
|
|
173
|
+
async getWriteState(authorization, key) {
|
|
174
|
+
const canonicalKey = canonicalStoredMemoryKey(key);
|
|
175
|
+
const scope = await this.scope(authorization);
|
|
176
|
+
const result = await this.pool.query(`SELECT ${COLUMNS},(revoked_at IS NOT NULL) AS revoked
|
|
177
|
+
FROM agent_memory_entries WHERE ${SCOPE_FILTER} AND memory_key=$4 LIMIT 1`, [...scope, canonicalKey]);
|
|
178
|
+
const row = result.rows[0];
|
|
179
|
+
return row ? { ...project(row), revoked: row.revoked === true } : null;
|
|
180
|
+
}
|
|
181
|
+
async searchExact(rawQuery, limit, scope) {
|
|
182
|
+
checkLimit(limit);
|
|
183
|
+
const search = boundedText(rawQuery, 240, true).toLocaleLowerCase('en-US');
|
|
184
|
+
let canonicalKey = '';
|
|
185
|
+
if (search.length <= 96) {
|
|
186
|
+
try {
|
|
187
|
+
canonicalKey = canonicalStoredMemoryKey(search);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
/* Non-key queries still use exact content matching. */
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const result = await this.pool.query(`SELECT ${COLUMNS} FROM agent_memory_entries WHERE ${SCOPE_FILTER} AND ${ACTIVE}
|
|
194
|
+
AND (memory_key=$4 OR lower(content)=$5)
|
|
195
|
+
ORDER BY (memory_key=$4) DESC,updated_at DESC,memory_key LIMIT $6`, [...scope, canonicalKey, search, limit]);
|
|
196
|
+
return result.rows.map(project);
|
|
197
|
+
}
|
|
198
|
+
async timedQuery(sql, params, timeoutCode) {
|
|
199
|
+
const client = await this.pool.connect();
|
|
200
|
+
try {
|
|
201
|
+
await client.query('BEGIN');
|
|
202
|
+
await client.query("SELECT set_config('statement_timeout',$1,true)", [
|
|
203
|
+
`${this.searchTimeoutMs}ms`,
|
|
204
|
+
]);
|
|
205
|
+
const result = await client.query(sql, params);
|
|
206
|
+
await client.query('COMMIT');
|
|
207
|
+
return result.rows;
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
await client.query('ROLLBACK').catch(() => undefined);
|
|
211
|
+
if (error && typeof error === 'object' && 'code' in error && error.code === '57014') {
|
|
212
|
+
throw new Error(timeoutCode, { cause: error });
|
|
213
|
+
}
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
client.release();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async searchLexical(rawQuery, limit, scope) {
|
|
221
|
+
checkLimit(limit);
|
|
222
|
+
const search = boundedText(rawQuery, 240, true).toLocaleLowerCase('en-US');
|
|
223
|
+
const grams = withPolicyErrors(() => memorySearchTokens(search));
|
|
224
|
+
// Filter candidates before expensive scoring; never discard old matches by age.
|
|
225
|
+
const terms = [...new Set([search, ...grams])].slice(0, 32);
|
|
226
|
+
const patterns = terms.map((term) => '%' + term.replace(/[#%_]/gu, (char) => '#' + char) + '%');
|
|
227
|
+
const candidates = terms
|
|
228
|
+
.map((_, i) => '(lower(memory_key) LIKE $' +
|
|
229
|
+
(7 + i) +
|
|
230
|
+
" ESCAPE '#' OR lower(content) LIKE $" +
|
|
231
|
+
(7 + i) +
|
|
232
|
+
" ESCAPE '#')")
|
|
233
|
+
.join(' OR ');
|
|
234
|
+
const sql = `WITH candidates AS (
|
|
235
|
+
SELECT ${COLUMNS},
|
|
236
|
+
CASE WHEN position($4 in lower(memory_key))>0 OR position($4 in lower(content))>0
|
|
237
|
+
THEN 1000 ELSE (
|
|
238
|
+
SELECT COUNT(*)::INTEGER FROM unnest($5::TEXT[]) AS gram(token)
|
|
239
|
+
WHERE position(gram.token in lower(memory_key))>0
|
|
240
|
+
OR position(gram.token in lower(content))>0
|
|
241
|
+
) END AS score
|
|
242
|
+
FROM agent_memory_entries WHERE ${SCOPE_FILTER} AND ${ACTIVE} AND (${candidates})
|
|
243
|
+
)
|
|
244
|
+
SELECT ${COLUMNS} FROM candidates WHERE score>0
|
|
245
|
+
ORDER BY score DESC,updated_at DESC,memory_key LIMIT $6`;
|
|
246
|
+
const rows = await this.timedQuery(sql, [...scope, search, grams, limit, ...patterns], 'agent_memory_lexical_timeout');
|
|
247
|
+
return rows.map(project);
|
|
248
|
+
}
|
|
249
|
+
async searchVector(vector, contract, limit, scope) {
|
|
250
|
+
if (!Number.isSafeInteger(limit) ||
|
|
251
|
+
limit < 1 ||
|
|
252
|
+
limit > MAX_MEMORY_RESULTS ||
|
|
253
|
+
vector.length !== contract.dimensions ||
|
|
254
|
+
!Number.isSafeInteger(contract.indexVersion) ||
|
|
255
|
+
contract.indexVersion < 1 ||
|
|
256
|
+
contract.indexVersion > 1_000_000 ||
|
|
257
|
+
contract.normalization !== 'l2_unit') {
|
|
258
|
+
throw new Error('agent_memory_embedding_contract_invalid');
|
|
259
|
+
}
|
|
260
|
+
const sql = `SELECT memory.memory_key,memory.content,memory.revision,memory.updated_at,
|
|
261
|
+
memory.source_event_id,memory.source_kind,memory.source_reliability,memory.valid_until,
|
|
262
|
+
1-(embedded.embedding <=> $5::vector) AS semantic_similarity
|
|
263
|
+
FROM agent_memory_embeddings embedded
|
|
264
|
+
JOIN agent_memory_entries memory ON memory.memory_id=embedded.memory_id
|
|
265
|
+
WHERE memory.namespace=$1 AND memory.scope_kind=$2 AND memory.scope_key=$3 AND ${ACTIVE_JOINED}
|
|
266
|
+
AND memory.revision=embedded.source_revision
|
|
267
|
+
AND embedded.namespace=$1 AND embedded.scope_kind=$2 AND embedded.scope_key=$3
|
|
268
|
+
AND embedded.provider_id=$6 AND embedded.model_id=$7
|
|
269
|
+
AND embedded.dimensions=$8 AND embedded.index_version=$9 AND embedded.normalization='l2_unit'
|
|
270
|
+
AND EXISTS (SELECT 1 FROM agent_memory_index_generation_state generation
|
|
271
|
+
WHERE generation.namespace=$1 AND generation.active_provider_id=$6
|
|
272
|
+
AND generation.active_model_id=$7 AND generation.active_dimensions=$8
|
|
273
|
+
AND generation.active_index_version=$9)
|
|
274
|
+
ORDER BY embedded.embedding <=> $5::vector,memory.updated_at DESC,memory.memory_key LIMIT $4`;
|
|
275
|
+
const rows = await this.timedQuery(sql, [
|
|
276
|
+
...scope,
|
|
277
|
+
limit,
|
|
278
|
+
vectorLiteral(vector),
|
|
279
|
+
contract.providerId,
|
|
280
|
+
contract.modelId,
|
|
281
|
+
contract.dimensions,
|
|
282
|
+
contract.indexVersion,
|
|
283
|
+
], 'agent_memory_semantic_timeout');
|
|
284
|
+
return rows.map(project);
|
|
285
|
+
}
|
|
286
|
+
async searchSemantic(rawQuery, limit, scope) {
|
|
287
|
+
const search = boundedText(rawQuery, 240, true);
|
|
288
|
+
checkLimit(limit);
|
|
289
|
+
const provider = this.embedding;
|
|
290
|
+
if (!provider)
|
|
291
|
+
return { matches: [], reason: 'semantic_unconfigured' };
|
|
292
|
+
try {
|
|
293
|
+
const available = await this.pool.query(`SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname='vector')
|
|
294
|
+
AND to_regclass('agent_memory_embeddings') IS NOT NULL AS available`);
|
|
295
|
+
if (available.rows[0]?.available !== true)
|
|
296
|
+
return { matches: [], reason: 'vector_index_unavailable' };
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return { matches: [], reason: 'vector_index_unavailable' };
|
|
300
|
+
}
|
|
301
|
+
try {
|
|
302
|
+
const active = await this.pool.query(`SELECT EXISTS (SELECT 1 FROM agent_memory_index_generation_state generation
|
|
303
|
+
WHERE generation.namespace=$1 AND generation.active_provider_id=$2
|
|
304
|
+
AND generation.active_model_id=$3 AND generation.active_dimensions=$4
|
|
305
|
+
AND generation.active_index_version=$5) AS active`, [
|
|
306
|
+
scope[0],
|
|
307
|
+
provider.contract.providerId,
|
|
308
|
+
provider.contract.modelId,
|
|
309
|
+
provider.contract.dimensions,
|
|
310
|
+
provider.contract.indexVersion,
|
|
311
|
+
]);
|
|
312
|
+
if (active.rows[0]?.active !== true)
|
|
313
|
+
return { matches: [], reason: 'semantic_unavailable' };
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return { matches: [], reason: 'semantic_unavailable' };
|
|
317
|
+
}
|
|
318
|
+
const estimatedTokens = estimateMemoryEmbeddingTokens([search]);
|
|
319
|
+
let budgetDay;
|
|
320
|
+
try {
|
|
321
|
+
budgetDay = await reserveMemoryEmbeddingBudget(this.pool, scope[0], estimatedTokens, provider);
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return { matches: [], reason: 'embedding_budget_unavailable' };
|
|
325
|
+
}
|
|
326
|
+
if (!budgetDay)
|
|
327
|
+
return { matches: [], reason: 'embedding_budget_exhausted' };
|
|
328
|
+
let budgetSettled = false;
|
|
329
|
+
try {
|
|
330
|
+
const batch = await provider.embedMany([search]);
|
|
331
|
+
await settleMemoryEmbeddingBudget(this.pool, scope[0], budgetDay, estimatedTokens, batch.inputTokens);
|
|
332
|
+
budgetSettled = true;
|
|
333
|
+
const vector = batch.vectors[0];
|
|
334
|
+
const norm = vector?.reduce((sum, value) => sum + value * value, 0) ?? 0;
|
|
335
|
+
if (!vector ||
|
|
336
|
+
batch.vectors.length !== 1 ||
|
|
337
|
+
vector.length !== provider.contract.dimensions ||
|
|
338
|
+
vector.some((value) => !Number.isFinite(value)) ||
|
|
339
|
+
!Number.isFinite(norm) ||
|
|
340
|
+
Math.abs(Math.sqrt(norm) - 1) > 1e-3 ||
|
|
341
|
+
batch.contract.providerId !== provider.contract.providerId ||
|
|
342
|
+
batch.contract.modelId !== provider.contract.modelId ||
|
|
343
|
+
batch.contract.dimensions !== provider.contract.dimensions ||
|
|
344
|
+
batch.contract.normalization !== 'l2_unit' ||
|
|
345
|
+
batch.contract.indexVersion !== provider.contract.indexVersion) {
|
|
346
|
+
throw new Error('agent_memory_embedding_contract_invalid');
|
|
347
|
+
}
|
|
348
|
+
return {
|
|
349
|
+
matches: await this.searchVector(vector, provider.contract, limit, scope),
|
|
350
|
+
reason: null,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
if (!budgetSettled) {
|
|
355
|
+
await settleMemoryEmbeddingBudget(this.pool, scope[0], budgetDay, estimatedTokens, null).catch(() => undefined);
|
|
356
|
+
}
|
|
357
|
+
const reason = error instanceof Error &&
|
|
358
|
+
(error.message === 'agent_memory_embedding_timeout' ||
|
|
359
|
+
error.message === 'agent_memory_semantic_timeout')
|
|
360
|
+
? 'semantic_timeout'
|
|
361
|
+
: 'semantic_unavailable';
|
|
362
|
+
return { matches: [], reason };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/** New key only; a conflicting revision/tombstone is never overwritten. */
|
|
366
|
+
async create(authorization, draft, metadata = {}) {
|
|
367
|
+
const value = validateStoredMemoryDraft(draft);
|
|
368
|
+
const source = validatedWriteMetadata(metadata);
|
|
369
|
+
const scope = await this.scope(authorization);
|
|
370
|
+
const sql = `WITH inserted AS (
|
|
371
|
+
INSERT INTO agent_memory_entries
|
|
372
|
+
(namespace,scope_kind,scope_key,memory_key,content,source_event_id,source_kind,source_reliability,valid_until)
|
|
373
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
|
374
|
+
ON CONFLICT DO NOTHING RETURNING memory_id,namespace
|
|
375
|
+
), queued AS (
|
|
376
|
+
INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation,index_version)
|
|
377
|
+
SELECT inserted.memory_id,1,'upsert',generation.index_version FROM inserted
|
|
378
|
+
CROSS JOIN LATERAL agent_memory_index_job_versions(inserted.namespace) generation
|
|
379
|
+
ON CONFLICT DO NOTHING RETURNING job_id
|
|
380
|
+
)
|
|
381
|
+
SELECT EXISTS(SELECT 1 FROM inserted) AS inserted, EXISTS(SELECT 1 FROM queued) AS queued`;
|
|
382
|
+
const result = await this.pool.query(sql, [
|
|
383
|
+
...scope,
|
|
384
|
+
value.key,
|
|
385
|
+
value.content,
|
|
386
|
+
boundedText(authorization.eventId, 256),
|
|
387
|
+
source.sourceKind,
|
|
388
|
+
source.sourceReliability,
|
|
389
|
+
source.validUntil,
|
|
390
|
+
]);
|
|
391
|
+
return result.rows[0]?.inserted === true ? 'created' : 'already_exists';
|
|
392
|
+
}
|
|
393
|
+
async revise(authorization, draft, expectedRevision, metadata = {}) {
|
|
394
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1)
|
|
395
|
+
throw new Error('agent_memory_revision_invalid');
|
|
396
|
+
const value = validateStoredMemoryDraft(draft);
|
|
397
|
+
const source = validatedWriteMetadata(metadata);
|
|
398
|
+
const scope = await this.scope(authorization);
|
|
399
|
+
const sql = `WITH updated AS (
|
|
400
|
+
UPDATE agent_memory_entries SET content=$5,source_event_id=$6,source_kind=$7,source_reliability=$8,
|
|
401
|
+
valid_until=$9,revision=revision+1,updated_at=now() WHERE ${SCOPE_FILTER}
|
|
402
|
+
AND memory_key=$4 AND revision=$10 AND revoked_at IS NULL
|
|
403
|
+
RETURNING memory_id,revision,namespace
|
|
404
|
+
), queued AS (
|
|
405
|
+
${enqueueUpserts('updated')}
|
|
406
|
+
) SELECT EXISTS(SELECT 1 FROM updated) AS updated,EXISTS(SELECT 1 FROM queued) AS queued`;
|
|
407
|
+
const result = await this.pool.query(sql, [
|
|
408
|
+
...scope,
|
|
409
|
+
value.key,
|
|
410
|
+
value.content,
|
|
411
|
+
boundedText(authorization.eventId, 256),
|
|
412
|
+
source.sourceKind,
|
|
413
|
+
source.sourceReliability,
|
|
414
|
+
source.validUntil,
|
|
415
|
+
expectedRevision,
|
|
416
|
+
]);
|
|
417
|
+
return result.rows[0]?.updated === true;
|
|
418
|
+
}
|
|
419
|
+
/** Only an event received after revocation can restore a tombstone. */
|
|
420
|
+
async rememberAgain(authorization, draft, expectedRevision, metadata = {}) {
|
|
421
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1)
|
|
422
|
+
throw new Error('agent_memory_revision_invalid');
|
|
423
|
+
const value = validateStoredMemoryDraft(draft);
|
|
424
|
+
const source = validatedWriteMetadata(metadata);
|
|
425
|
+
const scope = await this.scope(authorization);
|
|
426
|
+
const sql = `WITH updated AS (UPDATE agent_memory_entries
|
|
427
|
+
SET content=$5,source_event_id=$6,source_kind=$7,source_reliability=$8,valid_until=$9,
|
|
428
|
+
revoked_at=NULL,revision=revision+1,updated_at=now()
|
|
429
|
+
WHERE ${SCOPE_FILTER} AND memory_key=$4 AND revision=$10
|
|
430
|
+
AND revoked_at IS NOT NULL AND source_event_id<>$6 AND revoked_at < $11::TIMESTAMPTZ
|
|
431
|
+
RETURNING memory_id,revision,namespace), queued AS (
|
|
432
|
+
${enqueueUpserts('updated')}
|
|
433
|
+
) SELECT EXISTS(SELECT 1 FROM updated) AS updated,EXISTS(SELECT 1 FROM queued) AS queued`;
|
|
434
|
+
const result = await this.pool.query(sql, [
|
|
435
|
+
...scope,
|
|
436
|
+
value.key,
|
|
437
|
+
value.content,
|
|
438
|
+
boundedText(authorization.eventId, 256),
|
|
439
|
+
source.sourceKind,
|
|
440
|
+
source.sourceReliability,
|
|
441
|
+
source.validUntil,
|
|
442
|
+
expectedRevision,
|
|
443
|
+
authorization.receivedAt,
|
|
444
|
+
]);
|
|
445
|
+
return result.rows[0]?.updated === true;
|
|
446
|
+
}
|
|
447
|
+
/** Tombstone removes stored text, usage evidence, and stale episodic candidates. */
|
|
448
|
+
async forget(authorization, key, expectedRevision) {
|
|
449
|
+
if (expectedRevision !== undefined &&
|
|
450
|
+
(!Number.isSafeInteger(expectedRevision) || expectedRevision < 1)) {
|
|
451
|
+
throw new Error('agent_memory_revision_invalid');
|
|
452
|
+
}
|
|
453
|
+
const scope = await this.scope(authorization);
|
|
454
|
+
const canonicalKey = canonicalStoredMemoryKey(key);
|
|
455
|
+
const memoryLockKey = createHash('sha256')
|
|
456
|
+
.update([...scope, canonicalKey].join('\0'))
|
|
457
|
+
.digest('hex');
|
|
458
|
+
const sql = `WITH key_lock AS MATERIALIZED (
|
|
459
|
+
SELECT pg_advisory_xact_lock(hashtextextended($7,0))
|
|
460
|
+
), updated AS (UPDATE agent_memory_entries SET content='',revoked_at=now(),source_event_id=$5,
|
|
461
|
+
revision=revision+1,updated_at=now() WHERE ${SCOPE_FILTER} AND memory_key=$4 AND revoked_at IS NULL
|
|
462
|
+
AND ($6::BIGINT IS NULL OR revision=$6)
|
|
463
|
+
AND EXISTS (SELECT 1 FROM key_lock)
|
|
464
|
+
RETURNING memory_id,revision), usage_deleted AS (
|
|
465
|
+
DELETE FROM agent_memory_usage_signals WHERE ${SCOPE_FILTER} AND memory_key=$4
|
|
466
|
+
AND EXISTS (SELECT 1 FROM key_lock)
|
|
467
|
+
AND EXISTS (SELECT 1 FROM updated) RETURNING signal_id
|
|
468
|
+
), candidates_deleted AS (
|
|
469
|
+
UPDATE agent_memory_consolidation_candidates SET status='rejected',result_reason=NULL,
|
|
470
|
+
memory_key='rejected',content='[rejected]',source_event_ids=ARRAY[]::TEXT[],
|
|
471
|
+
expected_revision=NULL,confirmed_by_event_id=NULL,updated_at=now()
|
|
472
|
+
WHERE ${SCOPE_FILTER} AND memory_key=$4
|
|
473
|
+
AND status IN ('pending_confirmation','conflict','duplicate','promoted')
|
|
474
|
+
AND (EXISTS (SELECT 1 FROM updated) OR $6::BIGINT IS NULL)
|
|
475
|
+
AND EXISTS (SELECT 1 FROM key_lock) RETURNING candidate_id
|
|
476
|
+
), queued AS (
|
|
477
|
+
INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation)
|
|
478
|
+
SELECT memory_id,revision,'delete' FROM updated ON CONFLICT DO NOTHING RETURNING job_id
|
|
479
|
+
) SELECT EXISTS(SELECT 1 FROM updated) AS updated,EXISTS(SELECT 1 FROM queued) AS queued,
|
|
480
|
+
EXISTS(SELECT 1 FROM candidates_deleted) AS candidate_deleted`;
|
|
481
|
+
const result = await this.pool.query(sql, [
|
|
482
|
+
...scope,
|
|
483
|
+
canonicalKey,
|
|
484
|
+
boundedText(authorization.eventId, 256),
|
|
485
|
+
expectedRevision ?? null,
|
|
486
|
+
memoryLockKey,
|
|
487
|
+
]);
|
|
488
|
+
return result.rows[0]?.updated === true || result.rows[0]?.candidate_deleted === true;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
-- Agent memory in PostgreSQL. Extracted from Gate's gate_memory_* migrations 0021, 0026, 0027, 0030 and
|
|
2
|
+
-- generalised: the KOOK scope tuple (bot/dm|channel/actor/channel/tenant/team/binding revision) becomes
|
|
3
|
+
-- an opaque host-authorised scope (namespace, scope_kind, scope_key). Built-in PostgreSQL types only.
|
|
4
|
+
CREATE TABLE agent_memory_entries (
|
|
5
|
+
memory_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
6
|
+
namespace TEXT NOT NULL CHECK (length(namespace) BETWEEN 1 AND 128),
|
|
7
|
+
scope_kind TEXT NOT NULL CHECK (scope_kind ~ '^[a-z][a-z0-9_]{0,31}$'),
|
|
8
|
+
scope_key TEXT NOT NULL CHECK (length(scope_key) BETWEEN 1 AND 256),
|
|
9
|
+
memory_key TEXT NOT NULL CHECK (length(memory_key) BETWEEN 1 AND 96),
|
|
10
|
+
content TEXT NOT NULL CHECK (length(content) <= 800),
|
|
11
|
+
source_event_id TEXT NOT NULL CHECK (length(source_event_id) BETWEEN 1 AND 256),
|
|
12
|
+
revision BIGINT NOT NULL DEFAULT 1 CHECK (revision >= 1),
|
|
13
|
+
source_kind TEXT NOT NULL DEFAULT 'trusted_ingress'
|
|
14
|
+
CHECK (source_kind IN ('trusted_ingress','user_confirmed','system_verified','unknown')),
|
|
15
|
+
source_reliability SMALLINT NOT NULL DEFAULT 80 CHECK (source_reliability BETWEEN 0 AND 100),
|
|
16
|
+
valid_until TIMESTAMPTZ,
|
|
17
|
+
superseded_at TIMESTAMPTZ,
|
|
18
|
+
revoked_at TIMESTAMPTZ,
|
|
19
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
20
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
21
|
+
CONSTRAINT agent_memory_revoked_blank CHECK (revoked_at IS NULL OR content=''),
|
|
22
|
+
UNIQUE (namespace,scope_kind,scope_key,memory_key)
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX idx_agent_memory_scope_recent
|
|
25
|
+
ON agent_memory_entries(namespace,scope_kind,scope_key,updated_at DESC,memory_id)
|
|
26
|
+
WHERE revoked_at IS NULL;
|
|
27
|
+
CREATE INDEX idx_agent_memory_active_scope
|
|
28
|
+
ON agent_memory_entries(namespace,scope_kind,scope_key,memory_key,updated_at DESC,memory_id)
|
|
29
|
+
WHERE revoked_at IS NULL AND superseded_at IS NULL AND source_kind <> 'unknown';
|
|
30
|
+
|
|
31
|
+
-- Mutation idempotency without retaining candidate text or credentials.
|
|
32
|
+
CREATE TABLE agent_memory_write_receipts (
|
|
33
|
+
idempotency_key CHAR(64) PRIMARY KEY CHECK (idempotency_key ~ '^[a-f0-9]{64}$'),
|
|
34
|
+
namespace TEXT NOT NULL CHECK (length(namespace) BETWEEN 1 AND 128),
|
|
35
|
+
scope_kind TEXT NOT NULL CHECK (scope_kind ~ '^[a-z][a-z0-9_]{0,31}$'),
|
|
36
|
+
scope_key TEXT NOT NULL CHECK (length(scope_key) BETWEEN 1 AND 256),
|
|
37
|
+
source_event_id TEXT NOT NULL CHECK (length(source_event_id) BETWEEN 1 AND 256),
|
|
38
|
+
intent TEXT NOT NULL CHECK (intent IN ('remember','correct','forget')),
|
|
39
|
+
memory_key TEXT NOT NULL CHECK (length(memory_key) BETWEEN 1 AND 96),
|
|
40
|
+
outcome TEXT NOT NULL CHECK (outcome IN ('created','revised','forgotten','already_present','not_found')),
|
|
41
|
+
memory_revision BIGINT CHECK (memory_revision IS NULL OR memory_revision>=1),
|
|
42
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
43
|
+
UNIQUE (namespace,scope_kind,scope_key,source_event_id)
|
|
44
|
+
);
|
|
45
|
+
CREATE INDEX idx_agent_memory_write_receipts_scope_recent
|
|
46
|
+
ON agent_memory_write_receipts(namespace,scope_kind,scope_key,created_at DESC);
|
|
47
|
+
|
|
48
|
+
-- Content-free recall/use evidence for Dreaming promotion decisions.
|
|
49
|
+
-- Query text is never stored; fingerprints and event identifiers expire after 90 days.
|
|
50
|
+
CREATE TABLE agent_memory_usage_signals (
|
|
51
|
+
signal_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
52
|
+
namespace TEXT NOT NULL CHECK (length(namespace) BETWEEN 1 AND 128),
|
|
53
|
+
scope_kind TEXT NOT NULL CHECK (scope_kind ~ '^[a-z][a-z0-9_]{0,31}$'),
|
|
54
|
+
scope_key TEXT NOT NULL CHECK (length(scope_key) BETWEEN 1 AND 256),
|
|
55
|
+
memory_key TEXT NOT NULL CHECK (length(memory_key) BETWEEN 1 AND 96),
|
|
56
|
+
memory_revision BIGINT NOT NULL CHECK (memory_revision >= 1),
|
|
57
|
+
memory_source_event_id TEXT NOT NULL CHECK (length(memory_source_event_id) BETWEEN 1 AND 256),
|
|
58
|
+
request_event_id TEXT NOT NULL CHECK (length(request_event_id) BETWEEN 1 AND 256),
|
|
59
|
+
query_fingerprint CHAR(64) NOT NULL CHECK (query_fingerprint ~ '^[a-f0-9]{64}$'),
|
|
60
|
+
signal_kind TEXT NOT NULL CHECK (signal_kind IN ('recalled','used')),
|
|
61
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
62
|
+
expires_at TIMESTAMPTZ NOT NULL DEFAULT (now()+interval '90 days'),
|
|
63
|
+
UNIQUE (namespace,scope_kind,scope_key,request_event_id,memory_key,memory_revision,signal_kind)
|
|
64
|
+
);
|
|
65
|
+
CREATE INDEX idx_agent_memory_usage_evidence
|
|
66
|
+
ON agent_memory_usage_signals(namespace,scope_kind,scope_key,memory_key,memory_revision,signal_kind,created_at DESC);
|
|
67
|
+
CREATE INDEX idx_agent_memory_usage_expiry ON agent_memory_usage_signals(expires_at);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
-- Durable, additive embedding work, daily usage accounting and versioned index generations.
|
|
2
|
+
-- Extracted from Gate migrations 0024 and 0029. Does not require pgvector.
|
|
3
|
+
CREATE TABLE agent_memory_embedding_jobs (
|
|
4
|
+
job_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
5
|
+
memory_id UUID NOT NULL REFERENCES agent_memory_entries(memory_id) ON DELETE CASCADE,
|
|
6
|
+
source_revision BIGINT NOT NULL CHECK (source_revision > 0),
|
|
7
|
+
index_version INTEGER NOT NULL DEFAULT 1 CHECK (index_version > 0),
|
|
8
|
+
operation TEXT NOT NULL CHECK (operation IN ('upsert','delete')),
|
|
9
|
+
status TEXT NOT NULL DEFAULT 'pending'
|
|
10
|
+
CHECK (status IN ('pending','processing','retry','done','dead')),
|
|
11
|
+
attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
|
|
12
|
+
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
13
|
+
lease_token UUID,
|
|
14
|
+
lease_until TIMESTAMPTZ,
|
|
15
|
+
last_error_code TEXT CHECK (last_error_code IS NULL OR last_error_code ~ '^[a-z0-9_]{1,64}$'),
|
|
16
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
17
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
18
|
+
finished_at TIMESTAMPTZ,
|
|
19
|
+
CONSTRAINT agent_memory_embedding_jobs_memory_revision_version_key
|
|
20
|
+
UNIQUE (memory_id,source_revision,index_version),
|
|
21
|
+
CHECK ((status='processing') = (lease_token IS NOT NULL AND lease_until IS NOT NULL))
|
|
22
|
+
);
|
|
23
|
+
CREATE INDEX idx_agent_memory_embedding_jobs_ready
|
|
24
|
+
ON agent_memory_embedding_jobs(status,next_attempt_at,created_at,job_id)
|
|
25
|
+
WHERE status IN ('pending','retry','processing');
|
|
26
|
+
|
|
27
|
+
CREATE TABLE agent_memory_embedding_usage_daily (
|
|
28
|
+
namespace TEXT NOT NULL CHECK (length(namespace) BETWEEN 1 AND 128),
|
|
29
|
+
budget_day DATE NOT NULL,
|
|
30
|
+
actual_tokens BIGINT NOT NULL DEFAULT 0 CHECK (actual_tokens >= 0),
|
|
31
|
+
reserved_tokens BIGINT NOT NULL DEFAULT 0 CHECK (reserved_tokens >= 0),
|
|
32
|
+
request_count INTEGER NOT NULL DEFAULT 0 CHECK (request_count >= 0),
|
|
33
|
+
reserved_updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
34
|
+
PRIMARY KEY (namespace,budget_day)
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
CREATE TABLE agent_memory_index_generation_state (
|
|
38
|
+
namespace TEXT PRIMARY KEY CHECK (length(namespace) BETWEEN 1 AND 128),
|
|
39
|
+
active_provider_id TEXT NOT NULL CHECK (length(active_provider_id) BETWEEN 1 AND 96),
|
|
40
|
+
active_model_id TEXT NOT NULL CHECK (length(active_model_id) BETWEEN 1 AND 200),
|
|
41
|
+
active_dimensions INTEGER NOT NULL CHECK (active_dimensions BETWEEN 1 AND 16000),
|
|
42
|
+
active_index_version INTEGER NOT NULL CHECK (active_index_version > 0),
|
|
43
|
+
latest_index_version INTEGER NOT NULL DEFAULT 1 CHECK (latest_index_version > 0),
|
|
44
|
+
building_provider_id TEXT CHECK (building_provider_id IS NULL OR length(building_provider_id) BETWEEN 1 AND 96),
|
|
45
|
+
building_model_id TEXT CHECK (building_model_id IS NULL OR length(building_model_id) BETWEEN 1 AND 200),
|
|
46
|
+
building_dimensions INTEGER CHECK (building_dimensions IS NULL OR building_dimensions BETWEEN 1 AND 16000),
|
|
47
|
+
building_index_version INTEGER CHECK (building_index_version IS NULL OR building_index_version > 0),
|
|
48
|
+
reindex_status TEXT NOT NULL DEFAULT 'idle' CHECK (reindex_status IN ('idle','building','paused','failed')),
|
|
49
|
+
scan_cursor_memory_id UUID,
|
|
50
|
+
scan_complete BOOLEAN NOT NULL DEFAULT FALSE,
|
|
51
|
+
last_error_code TEXT CHECK (last_error_code IS NULL OR last_error_code ~ '^[a-z0-9_]{1,64}$'),
|
|
52
|
+
started_at TIMESTAMPTZ,
|
|
53
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
54
|
+
CHECK ((building_index_version IS NULL) = (building_provider_id IS NULL)),
|
|
55
|
+
CHECK ((building_index_version IS NULL) = (building_model_id IS NULL)),
|
|
56
|
+
CHECK ((building_index_version IS NULL) = (building_dimensions IS NULL)),
|
|
57
|
+
CHECK (active_index_version<=latest_index_version),
|
|
58
|
+
CHECK ((reindex_status='idle') = (building_index_version IS NULL))
|
|
59
|
+
);
|
|
60
|
+
CREATE INDEX idx_agent_memory_index_rebuild_scan
|
|
61
|
+
ON agent_memory_entries(namespace,memory_id) WHERE revoked_at IS NULL;
|
|
62
|
+
|
|
63
|
+
-- Mutations enqueue the active index and any in-progress shadow index. If the per-namespace state has
|
|
64
|
+
-- not yet been bootstrapped, the legacy generation is v1.
|
|
65
|
+
CREATE FUNCTION agent_memory_index_job_versions(target_namespace TEXT)
|
|
66
|
+
RETURNS TABLE(index_version INTEGER)
|
|
67
|
+
LANGUAGE SQL STABLE
|
|
68
|
+
AS $agent_memory_index_job_versions$
|
|
69
|
+
SELECT COALESCE(state.active_index_version, 1) AS index_version
|
|
70
|
+
FROM (SELECT 1) seed
|
|
71
|
+
LEFT JOIN agent_memory_index_generation_state state ON state.namespace=target_namespace
|
|
72
|
+
UNION
|
|
73
|
+
SELECT state.building_index_version
|
|
74
|
+
FROM agent_memory_index_generation_state state
|
|
75
|
+
WHERE state.namespace=target_namespace AND state.building_index_version IS NOT NULL
|
|
76
|
+
$agent_memory_index_job_versions$;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- Content-free, durable idempotency records for one scheduled Dreaming run per namespace and local
|
|
2
|
+
-- calendar date. Failed runs are not retried until the next date. From Gate migration 0031.
|
|
3
|
+
CREATE TABLE agent_memory_dreaming_runs (
|
|
4
|
+
run_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
5
|
+
namespace TEXT NOT NULL CHECK (length(namespace) BETWEEN 1 AND 128),
|
|
6
|
+
timezone TEXT NOT NULL CHECK (length(timezone) BETWEEN 1 AND 128),
|
|
7
|
+
scheduled_date DATE NOT NULL,
|
|
8
|
+
scheduled_at TIMESTAMPTZ NOT NULL,
|
|
9
|
+
status TEXT NOT NULL DEFAULT 'running' CHECK (status IN ('running','succeeded','failed')),
|
|
10
|
+
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
11
|
+
completed_at TIMESTAMPTZ,
|
|
12
|
+
error_code TEXT,
|
|
13
|
+
UNIQUE (namespace,timezone,scheduled_date),
|
|
14
|
+
CHECK (
|
|
15
|
+
(status='running' AND completed_at IS NULL AND error_code IS NULL)
|
|
16
|
+
OR (status='succeeded' AND completed_at IS NOT NULL AND error_code IS NULL)
|
|
17
|
+
OR (status='failed' AND completed_at IS NOT NULL AND error_code='dreaming_run_failed')
|
|
18
|
+
)
|
|
19
|
+
);
|