@rine-kit/agent-memory-postgres 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +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,1072 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { evaluateDeepPromotion, normalizeMemoryCandidates } from '@rine-kit/agent-memory';
|
|
4
|
+
import { boundedText } from './scope.js';
|
|
5
|
+
import { canonicalStoredMemoryKey } from './store.js';
|
|
6
|
+
export const MemoryConsolidationCandidateSchema = z
|
|
7
|
+
.object({
|
|
8
|
+
confidence: z.enum(['high', 'medium']),
|
|
9
|
+
subject: z.enum(['self', 'third_party', 'unknown']),
|
|
10
|
+
kind: z.enum(['stable_preference', 'verifiable_fact', 'episodic_checkpoint']),
|
|
11
|
+
key: z.string().trim().min(1).max(96),
|
|
12
|
+
content: z.string().trim().min(1).max(800),
|
|
13
|
+
evidence: z.string().trim().min(1).max(800),
|
|
14
|
+
validity: z.enum(['stable', '7_days', '30_days', '90_days', 'unknown']),
|
|
15
|
+
})
|
|
16
|
+
.strict();
|
|
17
|
+
const AUTO_LEARN_SOURCE_RELIABILITY = 85;
|
|
18
|
+
const SCOPE_KIND_PATTERN = /^[a-z][a-z0-9_]{0,31}$/u;
|
|
19
|
+
/** `a`'s consent row exists, is enabled and has the version `a` was admitted under. */
|
|
20
|
+
const consentJoin = (a, c = 'consent') => `JOIN agent_memory_consolidation_consents ${c} ON ${c}.namespace=${a}.namespace
|
|
21
|
+
AND ${c}.scope_kind=${a}.scope_kind AND ${c}.scope_key=${a}.scope_key
|
|
22
|
+
AND ${c}.workflow=${a}.workflow AND ${c}.enabled AND ${c}.consent_version=${a}.consent_version`;
|
|
23
|
+
/** The still-unexpired observation an admission points at. */
|
|
24
|
+
const sourceJoin = (a, s = 'source') => `JOIN agent_memory_observations ${s} ON ${s}.namespace=${a}.namespace
|
|
25
|
+
AND ${s}.scope_kind=${a}.scope_kind AND ${s}.scope_key=${a}.scope_key
|
|
26
|
+
AND ${s}.source_event_id=${a}.source_event_id AND ${s}.expires_at>now()`;
|
|
27
|
+
function sensitiveOrRiskText(value) {
|
|
28
|
+
return (/(?:password|passphrase|api[\s_-]*key|access[\s_-]*token|secret|private[\s_-]*key|密码|口令|验证码|密钥|私钥|身份证|护照|银行卡|信用卡|手机号|电话号码|电子邮箱|住址|家庭住址|病史|诊断|自残|自杀|性取向|想死|不想活|伤害自己|伤害别人|伤害他人|杀人|杀了他)/iu.test(value) ||
|
|
29
|
+
/(?:忽略|无视|忘掉|覆盖).{0,12}(?:系统|开发者|之前|先前|以上).{0,8}(?:指令|规则|提示词)|(?:输出|泄露|展示).{0,8}(?:系统提示词|隐藏指令)|(?:调用|执行).{0,8}(?:工具|命令)|(?:记住我是|我是).{0,8}(?:管理员|所有者)|\b(?:ignore|disregard|override).{0,20}(?:system|developer|previous|prior).{0,16}(?:instructions?|rules?|prompts?)\b/iu.test(value) ||
|
|
30
|
+
/(?:我(?:的)?(?:朋友|队友|同事|家人|室友|伴侣)|他|她|他们|她们).{0,24}(?:喜欢|偏好|常用|选择|住在|病史|诊断|收入|联系方式)/iu.test(value) ||
|
|
31
|
+
/\b(?:my friend|my teammate|my colleague|my family|he|she|they)\b.{0,24}\b(?:likes|prefers|uses|lives|medical|income|contact)\b/iu.test(value) ||
|
|
32
|
+
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu.test(value) ||
|
|
33
|
+
/(?:\+?\d[\s().-]?){8,}/u.test(value));
|
|
34
|
+
}
|
|
35
|
+
function hasSelfAttribution(value) {
|
|
36
|
+
return /我(?!们)|(?:^|[^a-z])(?:i(?:'m| am| prefer| like| use)?|my)(?:$|[^a-z])/iu.test(value);
|
|
37
|
+
}
|
|
38
|
+
async function transaction(pool, work) {
|
|
39
|
+
const client = await pool.connect();
|
|
40
|
+
try {
|
|
41
|
+
await client.query('BEGIN');
|
|
42
|
+
const value = await work(client);
|
|
43
|
+
await client.query('COMMIT');
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
await client.query('ROLLBACK').catch(() => undefined);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
client.release();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function checkedKind(scopeKind) {
|
|
55
|
+
if (!SCOPE_KIND_PATTERN.test(scopeKind))
|
|
56
|
+
throw new Error('agent_memory_scope_invalid');
|
|
57
|
+
return scopeKind;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Default-on per-scope learning controls and source admission. Consent is checked again at every step
|
|
61
|
+
* a worker takes; revoking it skips queued work and deletes candidates that have not been confirmed.
|
|
62
|
+
*/
|
|
63
|
+
export class MemoryConsolidationConsentService {
|
|
64
|
+
pool;
|
|
65
|
+
namespace;
|
|
66
|
+
kind;
|
|
67
|
+
constructor(pool, namespace, scopeKind = 'user') {
|
|
68
|
+
this.pool = pool;
|
|
69
|
+
this.namespace = namespace;
|
|
70
|
+
this.kind = checkedKind(scopeKind);
|
|
71
|
+
}
|
|
72
|
+
/** The authorised scope of this service, or null when the request is for something else. */
|
|
73
|
+
identity(authorization) {
|
|
74
|
+
const { scope } = authorization;
|
|
75
|
+
if (scope.namespace !== this.namespace || scope.kind !== this.kind)
|
|
76
|
+
return null;
|
|
77
|
+
return {
|
|
78
|
+
scopeKey: boundedText(scope.key, 256),
|
|
79
|
+
eventId: boundedText(authorization.eventId, 256),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
async setConsent(authorization, workflow, enabled) {
|
|
83
|
+
const identity = this.identity(authorization);
|
|
84
|
+
if (!identity)
|
|
85
|
+
throw new Error('agent_memory_consent_scope_required');
|
|
86
|
+
return transaction(this.pool, async (client) => {
|
|
87
|
+
const result = await client.query(`INSERT INTO agent_memory_consolidation_consents(
|
|
88
|
+
namespace,scope_kind,scope_key,workflow,enabled,consent_version,changed_by_event_id
|
|
89
|
+
) VALUES ($1,$2,$3,$4,$5,1,$6)
|
|
90
|
+
ON CONFLICT (namespace,scope_kind,scope_key,workflow) DO UPDATE SET
|
|
91
|
+
enabled=EXCLUDED.enabled,
|
|
92
|
+
consent_version=agent_memory_consolidation_consents.consent_version
|
|
93
|
+
+ CASE WHEN agent_memory_consolidation_consents.enabled IS DISTINCT FROM EXCLUDED.enabled THEN 1 ELSE 0 END,
|
|
94
|
+
changed_by_event_id=EXCLUDED.changed_by_event_id,updated_at=now()
|
|
95
|
+
RETURNING enabled,consent_version::TEXT AS consent_version`, [this.namespace, this.kind, identity.scopeKey, workflow, enabled, identity.eventId]);
|
|
96
|
+
const row = result.rows[0];
|
|
97
|
+
if (!row.enabled) {
|
|
98
|
+
await client.query(`UPDATE agent_memory_consolidation_admissions SET status='skipped',skip_reason='consent_revoked',
|
|
99
|
+
lease_token=NULL,lease_until=NULL,updated_at=now()
|
|
100
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND workflow=$4
|
|
101
|
+
AND status IN ('pending','retry','processing')`, [this.namespace, this.kind, identity.scopeKey, workflow]);
|
|
102
|
+
await client.query(`DELETE FROM agent_memory_consolidation_candidates
|
|
103
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND workflow=$4
|
|
104
|
+
AND status IN ('pending_confirmation','conflict','duplicate')`, [this.namespace, this.kind, identity.scopeKey, workflow]);
|
|
105
|
+
}
|
|
106
|
+
return { enabled: row.enabled, version: Number(row.consent_version) };
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
async getConsent(authorization) {
|
|
110
|
+
const identity = this.identity(authorization);
|
|
111
|
+
if (!identity)
|
|
112
|
+
throw new Error('agent_memory_consent_scope_required');
|
|
113
|
+
const result = await this.pool.query(`SELECT workflow,enabled,consent_version::TEXT AS consent_version
|
|
114
|
+
FROM agent_memory_consolidation_consents
|
|
115
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3`, [this.namespace, this.kind, identity.scopeKey]);
|
|
116
|
+
const value = {
|
|
117
|
+
light: { enabled: true, version: 0 },
|
|
118
|
+
rem: { enabled: true, version: 0 },
|
|
119
|
+
};
|
|
120
|
+
for (const row of result.rows)
|
|
121
|
+
value[row.workflow] = { enabled: row.enabled, version: Number(row.consent_version) };
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Admit one utterance of the authorised scope for learning. The host must pass the member's own
|
|
126
|
+
* words from the current trusted request: the observation has to carry this request as its evidence.
|
|
127
|
+
* Returns how many workflows queued it (0 when learning is off for this scope).
|
|
128
|
+
*/
|
|
129
|
+
async observe(authorization, observation) {
|
|
130
|
+
const identity = this.identity(authorization);
|
|
131
|
+
if (!identity)
|
|
132
|
+
return 0;
|
|
133
|
+
if (!observation.evidence.some((evidence) => evidence.id === identity.eventId &&
|
|
134
|
+
evidence.source === 'conversation' &&
|
|
135
|
+
evidence.observedAt === observation.observedAt))
|
|
136
|
+
return 0;
|
|
137
|
+
const content = boundedText(observation.content, 1200, true);
|
|
138
|
+
const observedAt = new Date(observation.observedAt);
|
|
139
|
+
if (!Number.isFinite(observedAt.getTime()))
|
|
140
|
+
return 0;
|
|
141
|
+
return transaction(this.pool, async (client) => {
|
|
142
|
+
await client.query(`INSERT INTO agent_memory_consolidation_consents(
|
|
143
|
+
namespace,scope_kind,scope_key,workflow,enabled,consent_version,changed_by_event_id
|
|
144
|
+
) SELECT $1,$2,$3,workflow,true,1,$4
|
|
145
|
+
FROM (VALUES ('light'::TEXT),('rem'::TEXT)) AS defaults(workflow)
|
|
146
|
+
ON CONFLICT (namespace,scope_kind,scope_key,workflow) DO NOTHING`, [this.namespace, this.kind, identity.scopeKey, identity.eventId]);
|
|
147
|
+
const enabled = await client.query(`SELECT 1 FROM agent_memory_consolidation_consents
|
|
148
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND enabled LIMIT 1`, [this.namespace, this.kind, identity.scopeKey]);
|
|
149
|
+
if (!enabled.rowCount)
|
|
150
|
+
return 0;
|
|
151
|
+
await client.query(`INSERT INTO agent_memory_observations(namespace,scope_kind,scope_key,source_event_id,content,observed_at)
|
|
152
|
+
VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING`, [this.namespace, this.kind, identity.scopeKey, identity.eventId, content, observedAt]);
|
|
153
|
+
const result = await client.query(`INSERT INTO agent_memory_consolidation_admissions(
|
|
154
|
+
namespace,scope_kind,scope_key,workflow,source_event_id,consent_version
|
|
155
|
+
) SELECT consent.namespace,consent.scope_kind,consent.scope_key,consent.workflow,$4,consent.consent_version
|
|
156
|
+
FROM agent_memory_consolidation_consents consent
|
|
157
|
+
WHERE consent.namespace=$1 AND consent.scope_kind=$2 AND consent.scope_key=$3 AND consent.enabled
|
|
158
|
+
ON CONFLICT (namespace,scope_kind,scope_key,workflow,source_event_id) DO NOTHING`, [this.namespace, this.kind, identity.scopeKey, identity.eventId]);
|
|
159
|
+
return result.rowCount ?? 0;
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
async pendingCandidates(authorization) {
|
|
163
|
+
const identity = this.identity(authorization);
|
|
164
|
+
if (!identity)
|
|
165
|
+
throw new Error('agent_memory_candidate_scope_required');
|
|
166
|
+
const result = await this.pool.query(`SELECT candidate.candidate_id,candidate.memory_key,candidate.content,candidate.candidate_kind,
|
|
167
|
+
candidate.valid_until,candidate.status
|
|
168
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
169
|
+
WHERE candidate.namespace=$1 AND candidate.scope_kind=$2 AND candidate.scope_key=$3
|
|
170
|
+
AND candidate.status IN ('pending_confirmation','conflict') AND candidate.expires_at>now()
|
|
171
|
+
AND EXISTS (SELECT 1 FROM agent_memory_consolidation_consents consent
|
|
172
|
+
WHERE consent.namespace=candidate.namespace AND consent.scope_kind=candidate.scope_kind
|
|
173
|
+
AND consent.scope_key=candidate.scope_key
|
|
174
|
+
AND consent.workflow=candidate.workflow AND consent.enabled
|
|
175
|
+
AND consent.consent_version=candidate.consent_version)
|
|
176
|
+
AND NOT EXISTS (
|
|
177
|
+
SELECT 1 FROM unnest(candidate.source_event_ids) AS source(event_id)
|
|
178
|
+
WHERE NOT EXISTS (SELECT 1 FROM agent_memory_consolidation_admissions admission
|
|
179
|
+
${sourceJoin('admission', 'obs')}
|
|
180
|
+
WHERE admission.namespace=candidate.namespace AND admission.scope_kind=candidate.scope_kind
|
|
181
|
+
AND admission.scope_key=candidate.scope_key
|
|
182
|
+
AND admission.workflow=candidate.workflow AND admission.consent_version=candidate.consent_version
|
|
183
|
+
AND admission.source_event_id=source.event_id AND admission.status='done' AND admission.expires_at>now())
|
|
184
|
+
)
|
|
185
|
+
ORDER BY candidate.created_at DESC,candidate.candidate_id LIMIT 12`, [this.namespace, this.kind, identity.scopeKey]);
|
|
186
|
+
return result.rows.map((row) => ({
|
|
187
|
+
candidateId: row.candidate_id,
|
|
188
|
+
key: row.memory_key,
|
|
189
|
+
content: row.content,
|
|
190
|
+
kind: row.candidate_kind,
|
|
191
|
+
validUntil: row.valid_until?.toISOString() ?? null,
|
|
192
|
+
status: row.status,
|
|
193
|
+
}));
|
|
194
|
+
}
|
|
195
|
+
async confirmCandidate(authorization, candidateId) {
|
|
196
|
+
const identity = this.identity(authorization);
|
|
197
|
+
if (!identity || !/^[0-9a-f-]{36}$/iu.test(candidateId))
|
|
198
|
+
return 'unavailable';
|
|
199
|
+
const base = [this.namespace, this.kind, identity.scopeKey];
|
|
200
|
+
return transaction(this.pool, async (client) => {
|
|
201
|
+
const candidateScope = await client.query(`SELECT candidate.workflow,candidate.consent_version::TEXT AS consent_version,candidate.memory_key
|
|
202
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
203
|
+
${consentJoin('candidate')}
|
|
204
|
+
WHERE candidate.candidate_id=$4 AND candidate.namespace=$1 AND candidate.scope_kind=$2
|
|
205
|
+
AND candidate.scope_key=$3
|
|
206
|
+
AND candidate.expires_at>now() AND candidate.status IN ('pending_confirmation','conflict','promoted')`, [...base, candidateId]);
|
|
207
|
+
const scope = candidateScope.rows[0];
|
|
208
|
+
if (!scope)
|
|
209
|
+
return 'unavailable';
|
|
210
|
+
const memoryLockKey = createHash('sha256')
|
|
211
|
+
.update([...base, scope.memory_key].join('\0'))
|
|
212
|
+
.digest('hex');
|
|
213
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [memoryLockKey]);
|
|
214
|
+
const memory = await client.query(`SELECT memory_id,revision::TEXT AS revision,revoked_at,content FROM agent_memory_entries
|
|
215
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND memory_key=$4 FOR UPDATE`, [...base, scope.memory_key]);
|
|
216
|
+
const current = memory.rows[0];
|
|
217
|
+
const consent = await client.query(`SELECT 1 FROM agent_memory_consolidation_consents
|
|
218
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND workflow=$4 AND consent_version=$5::BIGINT
|
|
219
|
+
AND enabled FOR SHARE`, [...base, scope.workflow, scope.consent_version]);
|
|
220
|
+
if (!consent.rowCount)
|
|
221
|
+
return 'unavailable';
|
|
222
|
+
const candidate = await client.query(`SELECT candidate.candidate_id,candidate.workflow,candidate.consent_version::TEXT AS consent_version,
|
|
223
|
+
candidate.memory_key,candidate.content,candidate.valid_until,
|
|
224
|
+
candidate.expected_revision::TEXT AS expected_revision,candidate.status,
|
|
225
|
+
candidate.confirmed_by_event_id,candidate.source_event_ids
|
|
226
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
227
|
+
${consentJoin('candidate')}
|
|
228
|
+
WHERE candidate.candidate_id=$4 AND candidate.namespace=$1 AND candidate.scope_kind=$2
|
|
229
|
+
AND candidate.scope_key=$3
|
|
230
|
+
AND candidate.expires_at>now() AND candidate.status IN ('pending_confirmation','conflict','promoted')
|
|
231
|
+
FOR UPDATE OF candidate`, [...base, candidateId]);
|
|
232
|
+
const row = candidate.rows[0];
|
|
233
|
+
if (!row)
|
|
234
|
+
return 'unavailable';
|
|
235
|
+
if (row.status === 'promoted' && row.confirmed_by_event_id === identity.eventId)
|
|
236
|
+
return 'already_promoted';
|
|
237
|
+
if (!['pending_confirmation', 'conflict'].includes(row.status))
|
|
238
|
+
return 'unavailable';
|
|
239
|
+
const sources = await client.query(`SELECT COUNT(*)::INTEGER AS count FROM unnest($5::TEXT[]) AS source(event_id)
|
|
240
|
+
WHERE EXISTS (SELECT 1 FROM agent_memory_consolidation_admissions admission
|
|
241
|
+
${consentJoin('admission')}
|
|
242
|
+
${sourceJoin('admission', 'message')}
|
|
243
|
+
WHERE admission.namespace=$1 AND admission.scope_kind=$2 AND admission.scope_key=$3
|
|
244
|
+
AND admission.workflow=$4 AND admission.consent_version=$6
|
|
245
|
+
AND admission.source_event_id=source.event_id
|
|
246
|
+
AND admission.status='done' AND admission.expires_at>now())`, [...base, row.workflow, row.source_event_ids, row.consent_version]);
|
|
247
|
+
if (sources.rows[0]?.count !== row.source_event_ids.length) {
|
|
248
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='expired',result_reason='source_expired',
|
|
249
|
+
content='[expired]',memory_key='expired',source_event_ids=ARRAY[]::TEXT[],updated_at=now()
|
|
250
|
+
WHERE candidate_id=$1`, [candidateId]);
|
|
251
|
+
return 'unavailable';
|
|
252
|
+
}
|
|
253
|
+
const expected = row.expected_revision === null ? null : Number(row.expected_revision);
|
|
254
|
+
if ((!current && expected !== null) || (current && Number(current.revision) !== expected)) {
|
|
255
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='conflict',result_reason='cas_conflict',updated_at=now()
|
|
256
|
+
WHERE candidate_id=$1`, [candidateId]);
|
|
257
|
+
return 'conflict';
|
|
258
|
+
}
|
|
259
|
+
let memoryId;
|
|
260
|
+
let revision;
|
|
261
|
+
if (current) {
|
|
262
|
+
if (current.revoked_at && current.revoked_at >= authorization.receivedAt)
|
|
263
|
+
return 'conflict';
|
|
264
|
+
const update = await client.query(`UPDATE agent_memory_entries SET content=$1,source_event_id=$2,source_kind='user_confirmed',
|
|
265
|
+
source_reliability=95,valid_until=$3,revoked_at=NULL,superseded_at=NULL,
|
|
266
|
+
revision=revision+1,updated_at=now()
|
|
267
|
+
WHERE memory_id=$4 AND revision=$5::BIGINT
|
|
268
|
+
AND (revoked_at IS NULL OR revoked_at<$6::TIMESTAMPTZ)
|
|
269
|
+
RETURNING memory_id,revision::TEXT AS revision`, [
|
|
270
|
+
row.content,
|
|
271
|
+
identity.eventId,
|
|
272
|
+
row.valid_until,
|
|
273
|
+
current.memory_id,
|
|
274
|
+
row.expected_revision,
|
|
275
|
+
authorization.receivedAt,
|
|
276
|
+
]);
|
|
277
|
+
memoryId = update.rows[0]?.memory_id ?? null;
|
|
278
|
+
revision = update.rows[0] ? Number(update.rows[0].revision) : null;
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
const insert = await client.query(`INSERT INTO agent_memory_entries(
|
|
282
|
+
namespace,scope_kind,scope_key,memory_key,content,source_event_id,source_kind,source_reliability,valid_until
|
|
283
|
+
) VALUES ($1,$2,$3,$4,$5,$6,'user_confirmed',95,$7)
|
|
284
|
+
ON CONFLICT DO NOTHING RETURNING memory_id,revision::TEXT AS revision`, [...base, row.memory_key, row.content, identity.eventId, row.valid_until]);
|
|
285
|
+
memoryId = insert.rows[0]?.memory_id ?? null;
|
|
286
|
+
revision = insert.rows[0] ? Number(insert.rows[0].revision) : null;
|
|
287
|
+
}
|
|
288
|
+
if (!memoryId || !revision) {
|
|
289
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='conflict',result_reason='cas_conflict',updated_at=now()
|
|
290
|
+
WHERE candidate_id=$1`, [candidateId]);
|
|
291
|
+
return 'conflict';
|
|
292
|
+
}
|
|
293
|
+
await client.query(`INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation,index_version)
|
|
294
|
+
SELECT $1,$2,'upsert',generation.index_version
|
|
295
|
+
FROM agent_memory_index_job_versions($3) generation ON CONFLICT DO NOTHING`, [memoryId, revision, this.namespace]);
|
|
296
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='promoted',confirmed_by_event_id=$2,
|
|
297
|
+
expected_revision=$3,result_reason=NULL,updated_at=now()
|
|
298
|
+
WHERE candidate_id=$1`, [candidateId, identity.eventId, revision]);
|
|
299
|
+
return 'promoted';
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
async rejectCandidate(authorization, candidateId) {
|
|
303
|
+
const identity = this.identity(authorization);
|
|
304
|
+
if (!identity || !/^[0-9a-f-]{36}$/iu.test(candidateId))
|
|
305
|
+
return false;
|
|
306
|
+
const result = await this.pool.query(`UPDATE agent_memory_consolidation_candidates candidate SET status='rejected',result_reason=NULL,
|
|
307
|
+
memory_key='rejected',content='[rejected]',source_event_ids=ARRAY[]::TEXT[],updated_at=now()
|
|
308
|
+
WHERE candidate.candidate_id=$4 AND candidate.namespace=$1 AND candidate.scope_kind=$2
|
|
309
|
+
AND candidate.scope_key=$3 AND candidate.status IN ('pending_confirmation','conflict')
|
|
310
|
+
AND EXISTS (SELECT 1 FROM agent_memory_consolidation_consents consent
|
|
311
|
+
WHERE consent.namespace=candidate.namespace AND consent.scope_kind=candidate.scope_kind
|
|
312
|
+
AND consent.scope_key=candidate.scope_key
|
|
313
|
+
AND consent.workflow=candidate.workflow AND consent.enabled
|
|
314
|
+
AND consent.consent_version=candidate.consent_version)`, [this.namespace, this.kind, identity.scopeKey, candidateId]);
|
|
315
|
+
return result.rowCount === 1;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/** Background-capable worker; callers provide scheduling and the inference planner. */
|
|
319
|
+
export class MemoryConsolidationWorker {
|
|
320
|
+
pool;
|
|
321
|
+
namespace;
|
|
322
|
+
planner;
|
|
323
|
+
kind;
|
|
324
|
+
maxRemBatch;
|
|
325
|
+
maxDeepCandidates;
|
|
326
|
+
maxInputCharacters;
|
|
327
|
+
maxCandidates;
|
|
328
|
+
leaseMs;
|
|
329
|
+
timeoutMs;
|
|
330
|
+
maxAttempts;
|
|
331
|
+
now;
|
|
332
|
+
constructor(pool, namespace, planner, options = {}) {
|
|
333
|
+
this.pool = pool;
|
|
334
|
+
this.namespace = namespace;
|
|
335
|
+
this.planner = planner;
|
|
336
|
+
this.kind = checkedKind(options.scopeKind ?? 'user');
|
|
337
|
+
this.maxRemBatch = options.maxRemBatch ?? 8;
|
|
338
|
+
this.maxDeepCandidates = options.maxDeepCandidates ?? 64;
|
|
339
|
+
this.maxInputCharacters = options.maxInputCharacters ?? 6_000;
|
|
340
|
+
this.maxCandidates = options.maxCandidates ?? 4;
|
|
341
|
+
this.leaseMs = options.leaseMs ?? 30_000;
|
|
342
|
+
this.timeoutMs = options.timeoutMs ?? 10_000;
|
|
343
|
+
this.maxAttempts = options.maxAttempts ?? 5;
|
|
344
|
+
this.now = options.now ?? Date.now;
|
|
345
|
+
if (!Number.isSafeInteger(this.maxRemBatch) ||
|
|
346
|
+
this.maxRemBatch < 1 ||
|
|
347
|
+
this.maxRemBatch > 8 ||
|
|
348
|
+
!Number.isSafeInteger(this.maxDeepCandidates) ||
|
|
349
|
+
this.maxDeepCandidates < 1 ||
|
|
350
|
+
this.maxDeepCandidates > 128 ||
|
|
351
|
+
!Number.isSafeInteger(this.maxInputCharacters) ||
|
|
352
|
+
this.maxInputCharacters < 100 ||
|
|
353
|
+
this.maxInputCharacters > 12_000 ||
|
|
354
|
+
!Number.isSafeInteger(this.maxCandidates) ||
|
|
355
|
+
this.maxCandidates < 1 ||
|
|
356
|
+
this.maxCandidates > 8 ||
|
|
357
|
+
!Number.isSafeInteger(this.leaseMs) ||
|
|
358
|
+
this.leaseMs < 1_000 ||
|
|
359
|
+
this.leaseMs > 60_000 ||
|
|
360
|
+
!Number.isSafeInteger(this.timeoutMs) ||
|
|
361
|
+
this.timeoutMs < 100 ||
|
|
362
|
+
this.timeoutMs > 30_000 ||
|
|
363
|
+
!Number.isSafeInteger(this.maxAttempts) ||
|
|
364
|
+
this.maxAttempts < 1 ||
|
|
365
|
+
this.maxAttempts > 8) {
|
|
366
|
+
throw new Error('agent_memory_consolidation_limits_invalid');
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
async claim(workflow) {
|
|
370
|
+
// Revoke stale queue rows from metadata alone, before any observation is read.
|
|
371
|
+
await this.pool.query(`UPDATE agent_memory_consolidation_admissions admission SET status='skipped',lease_token=NULL,lease_until=NULL,
|
|
372
|
+
skip_reason=CASE WHEN admission.expires_at<=now() THEN 'source_expired' ELSE 'consent_revoked' END,updated_at=now()
|
|
373
|
+
WHERE admission.namespace=$1 AND admission.scope_kind=$3 AND admission.workflow=$2
|
|
374
|
+
AND admission.status IN ('pending','retry')
|
|
375
|
+
AND (admission.expires_at<=now() OR NOT EXISTS (
|
|
376
|
+
SELECT 1 FROM agent_memory_consolidation_consents consent
|
|
377
|
+
WHERE consent.namespace=admission.namespace AND consent.scope_kind=admission.scope_kind
|
|
378
|
+
AND consent.scope_key=admission.scope_key
|
|
379
|
+
AND consent.workflow=admission.workflow
|
|
380
|
+
AND consent.enabled AND consent.consent_version=admission.consent_version))`, [this.namespace, workflow, this.kind]);
|
|
381
|
+
const leaseToken = randomUUID();
|
|
382
|
+
return transaction(this.pool, async (client) => {
|
|
383
|
+
const anchor = await client.query(`SELECT admission.scope_key,admission.consent_version::TEXT AS consent_version
|
|
384
|
+
FROM agent_memory_consolidation_admissions admission
|
|
385
|
+
${consentJoin('admission')}
|
|
386
|
+
WHERE admission.namespace=$1 AND admission.scope_kind=$3 AND admission.workflow=$2
|
|
387
|
+
AND admission.expires_at>now()
|
|
388
|
+
AND ((admission.status IN ('pending','retry') AND admission.next_attempt_at<=now())
|
|
389
|
+
OR (admission.status='processing' AND admission.lease_until<=now()))
|
|
390
|
+
ORDER BY admission.admitted_at,admission.source_event_id
|
|
391
|
+
FOR UPDATE OF admission SKIP LOCKED LIMIT 1`, [this.namespace, workflow, this.kind]);
|
|
392
|
+
if (!anchor.rows[0])
|
|
393
|
+
return null;
|
|
394
|
+
const batchSize = workflow === 'light' ? 1 : this.maxRemBatch;
|
|
395
|
+
const rows = await client.query(`SELECT admission.admission_id FROM agent_memory_consolidation_admissions admission
|
|
396
|
+
${consentJoin('admission')}
|
|
397
|
+
WHERE admission.namespace=$1 AND admission.scope_kind=$6 AND admission.scope_key=$3
|
|
398
|
+
AND admission.workflow=$2
|
|
399
|
+
AND admission.consent_version=$4 AND admission.expires_at>now()
|
|
400
|
+
AND ((admission.status IN ('pending','retry') AND admission.next_attempt_at<=now())
|
|
401
|
+
OR (admission.status='processing' AND admission.lease_until<=now()))
|
|
402
|
+
ORDER BY admission.admitted_at,admission.source_event_id
|
|
403
|
+
FOR UPDATE OF admission SKIP LOCKED LIMIT $5`, [
|
|
404
|
+
this.namespace,
|
|
405
|
+
workflow,
|
|
406
|
+
anchor.rows[0].scope_key,
|
|
407
|
+
anchor.rows[0].consent_version,
|
|
408
|
+
batchSize,
|
|
409
|
+
this.kind,
|
|
410
|
+
]);
|
|
411
|
+
const ids = rows.rows.map((row) => row.admission_id);
|
|
412
|
+
if (!ids.length)
|
|
413
|
+
return null;
|
|
414
|
+
const claimed = await client.query(`UPDATE agent_memory_consolidation_admissions admission SET status='processing',
|
|
415
|
+
attempt_count=attempt_count+1,lease_token=$2::uuid,lease_until=now()+($3::BIGINT*interval '1 millisecond'),
|
|
416
|
+
skip_reason=NULL,updated_at=now()
|
|
417
|
+
WHERE admission.admission_id=ANY($1::uuid[])
|
|
418
|
+
RETURNING admission_id,namespace,scope_key,workflow,source_event_id,
|
|
419
|
+
consent_version::TEXT AS consent_version,admitted_at,attempt_count,lease_token::TEXT AS lease_token`, [ids, leaseToken, this.leaseMs]);
|
|
420
|
+
return claimed.rows;
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
async authorizeMetadata(batch) {
|
|
424
|
+
const ids = batch.map((row) => row.admission_id);
|
|
425
|
+
const result = await this.pool.query(`SELECT admission.admission_id,
|
|
426
|
+
EXISTS (SELECT 1 FROM agent_memory_consolidation_consents consent
|
|
427
|
+
WHERE consent.namespace=admission.namespace AND consent.scope_kind=admission.scope_kind
|
|
428
|
+
AND consent.scope_key=admission.scope_key
|
|
429
|
+
AND consent.workflow=admission.workflow AND consent.enabled
|
|
430
|
+
AND consent.consent_version=admission.consent_version) AS consent_valid,
|
|
431
|
+
EXISTS (SELECT 1 FROM agent_memory_observations source
|
|
432
|
+
WHERE source.namespace=admission.namespace AND source.scope_kind=admission.scope_kind
|
|
433
|
+
AND source.scope_key=admission.scope_key AND source.source_event_id=admission.source_event_id
|
|
434
|
+
AND source.expires_at>now()) AS message_valid,
|
|
435
|
+
EXISTS (SELECT 1 FROM agent_memory_observations source
|
|
436
|
+
WHERE source.namespace=admission.namespace AND source.scope_kind=admission.scope_kind
|
|
437
|
+
AND source.scope_key=admission.scope_key AND source.source_event_id=admission.source_event_id) AS message_exists
|
|
438
|
+
FROM agent_memory_consolidation_admissions admission
|
|
439
|
+
WHERE admission.admission_id=ANY($1::uuid[]) AND admission.status='processing'
|
|
440
|
+
AND admission.lease_token=$2::uuid`, [ids, batch[0].lease_token]);
|
|
441
|
+
const states = new Map(result.rows.map((row) => [row.admission_id, row]));
|
|
442
|
+
const valid = [];
|
|
443
|
+
let skipped = 0;
|
|
444
|
+
for (const admission of batch) {
|
|
445
|
+
const state = states.get(admission.admission_id);
|
|
446
|
+
const reason = !state?.consent_valid
|
|
447
|
+
? 'consent_revoked'
|
|
448
|
+
: !state.message_valid
|
|
449
|
+
? state.message_exists
|
|
450
|
+
? 'source_expired'
|
|
451
|
+
: 'source_provenance_missing'
|
|
452
|
+
: null;
|
|
453
|
+
if (!reason)
|
|
454
|
+
valid.push(admission);
|
|
455
|
+
else {
|
|
456
|
+
await this.skip([admission], reason);
|
|
457
|
+
skipped += 1;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return { valid, skipped };
|
|
461
|
+
}
|
|
462
|
+
async skip(batch, reason) {
|
|
463
|
+
if (!batch.length)
|
|
464
|
+
return;
|
|
465
|
+
await this.pool.query(`UPDATE agent_memory_consolidation_admissions SET status='skipped',skip_reason=$3,
|
|
466
|
+
lease_token=NULL,lease_until=NULL,updated_at=now()
|
|
467
|
+
WHERE admission_id=ANY($1::uuid[]) AND status='processing' AND lease_token=$2::uuid`, [batch.map((row) => row.admission_id), batch[0].lease_token, reason]);
|
|
468
|
+
}
|
|
469
|
+
async readMessages(batch) {
|
|
470
|
+
return transaction(this.pool, async (client) => {
|
|
471
|
+
// This first read validates the server-issued capability and current consent again without
|
|
472
|
+
// selecting content.
|
|
473
|
+
const capability = await client.query(`SELECT admission.admission_id FROM agent_memory_consolidation_admissions admission
|
|
474
|
+
${consentJoin('admission')}
|
|
475
|
+
WHERE admission.admission_id=ANY($1::uuid[]) AND admission.status='processing'
|
|
476
|
+
AND admission.lease_token=$2::uuid AND admission.expires_at>now()
|
|
477
|
+
FOR SHARE OF admission,consent`, [batch.map((row) => row.admission_id), batch[0].lease_token]);
|
|
478
|
+
if (capability.rows.length !== batch.length)
|
|
479
|
+
return [];
|
|
480
|
+
// Observation text is selected only after the consent, expiry and lease checks above passed.
|
|
481
|
+
const result = await client.query(`SELECT admission.admission_id,admission.source_event_id,admission.admitted_at,
|
|
482
|
+
source.content,source.observed_at AS created_at
|
|
483
|
+
FROM agent_memory_consolidation_admissions admission
|
|
484
|
+
${consentJoin('admission')}
|
|
485
|
+
${sourceJoin('admission')}
|
|
486
|
+
WHERE admission.admission_id=ANY($1::uuid[]) AND admission.status='processing'
|
|
487
|
+
AND admission.lease_token=$2::uuid AND admission.expires_at>now()
|
|
488
|
+
ORDER BY admission.admitted_at,admission.source_event_id`, [batch.map((row) => row.admission_id), batch[0].lease_token]);
|
|
489
|
+
return result.rows;
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
validateCandidates(raw, messages, workflow) {
|
|
493
|
+
const drafts = [];
|
|
494
|
+
for (const item of raw.slice(0, this.maxCandidates)) {
|
|
495
|
+
const parsed = MemoryConsolidationCandidateSchema.safeParse(item);
|
|
496
|
+
if (parsed.success)
|
|
497
|
+
drafts.push(parsed.data);
|
|
498
|
+
}
|
|
499
|
+
return normalizeMemoryCandidates(drafts, messages.map((source) => ({
|
|
500
|
+
content: source.content,
|
|
501
|
+
sourceEventId: source.source_event_id,
|
|
502
|
+
})), {
|
|
503
|
+
maxCandidates: this.maxCandidates,
|
|
504
|
+
now: this.now,
|
|
505
|
+
canonicalizeKey: canonicalStoredMemoryKey,
|
|
506
|
+
isProhibited: sensitiveOrRiskText,
|
|
507
|
+
createIdempotencyKey: ({ key, content, evidenceEventIds }) => createHash('sha256')
|
|
508
|
+
.update([
|
|
509
|
+
this.namespace,
|
|
510
|
+
messages[0].source_event_id,
|
|
511
|
+
workflow,
|
|
512
|
+
messages[0].admission_id, // a new consent version receives a new admission capability
|
|
513
|
+
...evidenceEventIds,
|
|
514
|
+
key,
|
|
515
|
+
content,
|
|
516
|
+
].join('\0'))
|
|
517
|
+
.digest('hex'),
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
async complete(batch, messages, candidates) {
|
|
521
|
+
return transaction(this.pool, async (client) => {
|
|
522
|
+
const leaseToken = batch[0].lease_token;
|
|
523
|
+
const ids = batch.map((row) => row.admission_id);
|
|
524
|
+
const authority = await client.query(`SELECT admission.admission_id FROM agent_memory_consolidation_admissions admission
|
|
525
|
+
${consentJoin('admission')}
|
|
526
|
+
${sourceJoin('admission')}
|
|
527
|
+
WHERE admission.admission_id=ANY($1::uuid[]) AND admission.status='processing'
|
|
528
|
+
AND admission.lease_token=$2::uuid AND admission.expires_at>now()
|
|
529
|
+
FOR SHARE OF admission,consent,source`, [ids, leaseToken]);
|
|
530
|
+
if (authority.rows.length !== batch.length) {
|
|
531
|
+
await client.query(`UPDATE agent_memory_consolidation_admissions admission SET status='skipped',skip_reason=
|
|
532
|
+
CASE WHEN NOT EXISTS (SELECT 1 FROM agent_memory_consolidation_consents consent
|
|
533
|
+
WHERE consent.namespace=admission.namespace AND consent.scope_kind=admission.scope_kind
|
|
534
|
+
AND consent.scope_key=admission.scope_key
|
|
535
|
+
AND consent.workflow=admission.workflow AND consent.enabled
|
|
536
|
+
AND consent.consent_version=admission.consent_version)
|
|
537
|
+
THEN 'consent_revoked' ELSE 'source_provenance_missing' END,
|
|
538
|
+
lease_token=NULL,lease_until=NULL,updated_at=now()
|
|
539
|
+
WHERE admission.admission_id=ANY($1::uuid[]) AND admission.status='processing' AND admission.lease_token=$2::uuid`, [ids, leaseToken]);
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
const first = batch[0];
|
|
543
|
+
const base = [first.namespace, this.kind, first.scope_key];
|
|
544
|
+
for (const candidate of candidates) {
|
|
545
|
+
const consolidated = await client.query(`UPDATE agent_memory_consolidation_candidates existing SET
|
|
546
|
+
source_event_ids=ARRAY(
|
|
547
|
+
SELECT live.event_id FROM (
|
|
548
|
+
SELECT requested.event_id,MAX(admission.admitted_at) AS admitted_at
|
|
549
|
+
FROM unnest(existing.source_event_ids || $10::TEXT[]) AS requested(event_id)
|
|
550
|
+
JOIN agent_memory_consolidation_admissions admission
|
|
551
|
+
ON admission.namespace=$1 AND admission.scope_kind=$2 AND admission.scope_key=$3
|
|
552
|
+
AND admission.workflow=$4
|
|
553
|
+
AND admission.consent_version=$5::BIGINT AND admission.source_event_id=requested.event_id
|
|
554
|
+
AND admission.expires_at>now()
|
|
555
|
+
AND (admission.status='done' OR (admission.status='processing'
|
|
556
|
+
AND admission.admission_id=ANY($11::uuid[]) AND admission.lease_token=$12::uuid))
|
|
557
|
+
${sourceJoin('admission')}
|
|
558
|
+
GROUP BY requested.event_id
|
|
559
|
+
ORDER BY MAX(admission.admitted_at) DESC,requested.event_id DESC
|
|
560
|
+
LIMIT 8
|
|
561
|
+
) live ORDER BY live.admitted_at,live.event_id
|
|
562
|
+
),
|
|
563
|
+
valid_until=$9,updated_at=now()
|
|
564
|
+
FROM agent_memory_consolidation_consents consent
|
|
565
|
+
WHERE existing.namespace=$1 AND existing.scope_kind=$2 AND existing.scope_key=$3
|
|
566
|
+
AND existing.workflow=$4
|
|
567
|
+
AND existing.consent_version=$5::BIGINT AND existing.memory_key=$6 AND existing.content=$7
|
|
568
|
+
AND existing.candidate_kind=$8 AND existing.status IN ('pending_confirmation','conflict')
|
|
569
|
+
AND existing.expires_at>now() AND consent.namespace=existing.namespace
|
|
570
|
+
AND consent.scope_kind=existing.scope_kind AND consent.scope_key=existing.scope_key
|
|
571
|
+
AND consent.workflow=existing.workflow
|
|
572
|
+
AND consent.enabled AND consent.consent_version=existing.consent_version
|
|
573
|
+
AND EXISTS (SELECT 1 FROM agent_memory_consolidation_admissions admission
|
|
574
|
+
WHERE admission.admission_id=ANY($11::uuid[]) AND admission.status='processing'
|
|
575
|
+
AND admission.lease_token=$12::uuid)
|
|
576
|
+
RETURNING existing.candidate_id::TEXT AS candidate_id`, [
|
|
577
|
+
...base,
|
|
578
|
+
first.workflow,
|
|
579
|
+
first.consent_version,
|
|
580
|
+
candidate.key,
|
|
581
|
+
candidate.content,
|
|
582
|
+
candidate.kind,
|
|
583
|
+
candidate.validUntil,
|
|
584
|
+
candidate.evidenceEventIds,
|
|
585
|
+
ids,
|
|
586
|
+
leaseToken,
|
|
587
|
+
]);
|
|
588
|
+
if (consolidated.rows[0])
|
|
589
|
+
continue;
|
|
590
|
+
const inserted = await client.query(`INSERT INTO agent_memory_consolidation_candidates(
|
|
591
|
+
idempotency_key,namespace,scope_kind,scope_key,workflow,consent_version,memory_key,content,
|
|
592
|
+
candidate_kind,valid_until,source_event_ids,expected_revision,status,result_reason
|
|
593
|
+
) SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::TEXT[],NULL,'pending_confirmation',NULL
|
|
594
|
+
WHERE EXISTS (SELECT 1 FROM agent_memory_consolidation_admissions admission
|
|
595
|
+
${consentJoin('admission')}
|
|
596
|
+
WHERE admission.admission_id=ANY($12::uuid[]) AND admission.status='processing'
|
|
597
|
+
AND admission.lease_token=$13::uuid)
|
|
598
|
+
AND $11::TEXT[] <@ (SELECT array_agg(admission.source_event_id)
|
|
599
|
+
FROM agent_memory_consolidation_admissions admission
|
|
600
|
+
WHERE admission.admission_id=ANY($12::uuid[]) AND admission.status='processing'
|
|
601
|
+
AND admission.lease_token=$13::uuid)
|
|
602
|
+
ON CONFLICT (idempotency_key) DO NOTHING RETURNING candidate_id::TEXT AS candidate_id`, [
|
|
603
|
+
candidate.idempotencyKey,
|
|
604
|
+
...base,
|
|
605
|
+
first.workflow,
|
|
606
|
+
first.consent_version,
|
|
607
|
+
candidate.key,
|
|
608
|
+
candidate.content,
|
|
609
|
+
candidate.kind,
|
|
610
|
+
candidate.validUntil,
|
|
611
|
+
candidate.evidenceEventIds,
|
|
612
|
+
ids,
|
|
613
|
+
leaseToken,
|
|
614
|
+
]);
|
|
615
|
+
const candidateId = inserted.rows[0]?.candidate_id;
|
|
616
|
+
if (!candidateId)
|
|
617
|
+
continue;
|
|
618
|
+
const existing = await client.query(`SELECT memory_id,revision::TEXT AS revision,content,revoked_at
|
|
619
|
+
FROM agent_memory_entries WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND memory_key=$4
|
|
620
|
+
FOR UPDATE`, [...base, candidate.key]);
|
|
621
|
+
const current = existing.rows[0];
|
|
622
|
+
if (current?.revoked_at) {
|
|
623
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates
|
|
624
|
+
SET status='conflict',result_reason='existing_memory_conflict',expected_revision=$2,updated_at=now()
|
|
625
|
+
WHERE candidate_id=$1`, [candidateId, Number(current.revision)]);
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
if (current?.content === candidate.content) {
|
|
629
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates
|
|
630
|
+
SET status='duplicate',result_reason='already_present',expected_revision=$2,updated_at=now()
|
|
631
|
+
WHERE candidate_id=$1`, [candidateId, Number(current.revision)]);
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
if (current) {
|
|
635
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates
|
|
636
|
+
SET status='conflict',result_reason='cas_conflict',expected_revision=$2,updated_at=now()
|
|
637
|
+
WHERE candidate_id=$1`, [candidateId, Number(current.revision)]);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
const latest = messages.reduce((left, right) => left.admitted_at > right.admitted_at ||
|
|
641
|
+
(left.admitted_at.getTime() === right.admitted_at.getTime() &&
|
|
642
|
+
left.source_event_id > right.source_event_id)
|
|
643
|
+
? left
|
|
644
|
+
: right);
|
|
645
|
+
await client.query(`INSERT INTO agent_memory_consolidation_checkpoints(
|
|
646
|
+
namespace,scope_kind,scope_key,workflow,consent_version,last_admitted_at,last_event_id
|
|
647
|
+
) VALUES ($1,$2,$3,$4,$5,$6,$7)
|
|
648
|
+
ON CONFLICT (namespace,scope_kind,scope_key,workflow,consent_version) DO UPDATE SET
|
|
649
|
+
last_admitted_at=EXCLUDED.last_admitted_at,last_event_id=EXCLUDED.last_event_id,updated_at=now()
|
|
650
|
+
WHERE (agent_memory_consolidation_checkpoints.last_admitted_at,agent_memory_consolidation_checkpoints.last_event_id)
|
|
651
|
+
< (EXCLUDED.last_admitted_at,EXCLUDED.last_event_id)`, [
|
|
652
|
+
...base,
|
|
653
|
+
first.workflow,
|
|
654
|
+
first.consent_version,
|
|
655
|
+
latest.admitted_at,
|
|
656
|
+
latest.source_event_id,
|
|
657
|
+
]);
|
|
658
|
+
await client.query(`UPDATE agent_memory_consolidation_admissions SET status='done',lease_token=NULL,lease_until=NULL,
|
|
659
|
+
skip_reason=NULL,updated_at=now()
|
|
660
|
+
WHERE admission_id=ANY($1::uuid[]) AND status='processing' AND lease_token=$2::uuid`, [ids, leaseToken]);
|
|
661
|
+
return true;
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
/** Consolidate eligible episodic candidates into long-term memory using evidence, not planner confidence. */
|
|
665
|
+
async processDeep(limit = this.maxDeepCandidates) {
|
|
666
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > this.maxDeepCandidates) {
|
|
667
|
+
throw new Error('agent_memory_deep_limit_invalid');
|
|
668
|
+
}
|
|
669
|
+
const result = await this.pool.query(`SELECT candidate.candidate_id::TEXT AS candidate_id,candidate.scope_key,candidate.memory_key,
|
|
670
|
+
candidate.workflow,candidate.consent_version::TEXT AS consent_version
|
|
671
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
672
|
+
${consentJoin('candidate')}
|
|
673
|
+
WHERE candidate.namespace=$1 AND candidate.scope_kind=$3
|
|
674
|
+
AND candidate.status IN ('pending_confirmation','conflict')
|
|
675
|
+
AND candidate.expires_at>now()
|
|
676
|
+
ORDER BY candidate.created_at,candidate.candidate_id LIMIT $2`, [this.namespace, limit, this.kind]);
|
|
677
|
+
if (!result.rows.length)
|
|
678
|
+
return { status: 'SKIPPED_NO_ELIGIBLE_CORPUS' };
|
|
679
|
+
const groups = new Map();
|
|
680
|
+
for (const row of result.rows) {
|
|
681
|
+
const key = `${row.scope_key}\0${row.memory_key}`;
|
|
682
|
+
const group = groups.get(key) ?? [];
|
|
683
|
+
group.push(row);
|
|
684
|
+
groups.set(key, group);
|
|
685
|
+
}
|
|
686
|
+
const totals = { inspected: 0, promoted: 0, rejected: 0, deferred: 0 };
|
|
687
|
+
for (const handles of groups.values()) {
|
|
688
|
+
const outcome = await this.processDeepGroup(handles[0].scope_key, handles[0].memory_key, handles);
|
|
689
|
+
totals.inspected += outcome.inspected;
|
|
690
|
+
totals.promoted += outcome.promoted;
|
|
691
|
+
totals.rejected += outcome.rejected;
|
|
692
|
+
totals.deferred += outcome.deferred;
|
|
693
|
+
}
|
|
694
|
+
return { status: 'processed', ...totals };
|
|
695
|
+
}
|
|
696
|
+
async processDeepGroup(scopeKey, memoryKey, handles) {
|
|
697
|
+
const base = [this.namespace, this.kind, scopeKey];
|
|
698
|
+
return transaction(this.pool, async (client) => {
|
|
699
|
+
// Coordinate missing-row tombstones, then use memory -> consent -> candidate lock order.
|
|
700
|
+
const memoryLockKey = createHash('sha256')
|
|
701
|
+
.update([...base, memoryKey].join('\0'))
|
|
702
|
+
.digest('hex');
|
|
703
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [memoryLockKey]);
|
|
704
|
+
const memoryResult = await client.query(`SELECT memory_id::TEXT AS memory_id,revision::TEXT AS revision,content,source_event_id,valid_until,
|
|
705
|
+
revoked_at,superseded_at
|
|
706
|
+
FROM agent_memory_entries WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND memory_key=$4
|
|
707
|
+
FOR UPDATE`, [...base, memoryKey]);
|
|
708
|
+
const current = memoryResult.rows[0] ?? null;
|
|
709
|
+
await client.query(`SELECT workflow,consent_version FROM agent_memory_consolidation_consents
|
|
710
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 FOR SHARE`, base);
|
|
711
|
+
const locked = await client.query(`SELECT candidate.candidate_id::TEXT AS candidate_id,candidate.workflow,
|
|
712
|
+
candidate.consent_version::TEXT AS consent_version,candidate.memory_key,candidate.content,
|
|
713
|
+
candidate.candidate_kind,candidate.valid_until,candidate.source_event_ids,
|
|
714
|
+
candidate.expected_revision::TEXT AS expected_revision,candidate.status,candidate.created_at
|
|
715
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
716
|
+
${consentJoin('candidate')}
|
|
717
|
+
WHERE candidate.candidate_id=ANY($5::UUID[]) AND candidate.namespace=$1 AND candidate.scope_kind=$2
|
|
718
|
+
AND candidate.scope_key=$3 AND candidate.memory_key=$4
|
|
719
|
+
AND candidate.status IN ('pending_confirmation','conflict') AND candidate.expires_at>now()
|
|
720
|
+
ORDER BY candidate.created_at,candidate.candidate_id
|
|
721
|
+
FOR UPDATE OF candidate SKIP LOCKED`, [...base, memoryKey, handles.map((row) => row.candidate_id)]);
|
|
722
|
+
const candidates = locked.rows;
|
|
723
|
+
if (!candidates.length)
|
|
724
|
+
return { inspected: 0, promoted: 0, rejected: 0, deferred: handles.length };
|
|
725
|
+
// Validate authority and provenance without selecting observation text.
|
|
726
|
+
const metadata = await client.query(`SELECT candidate.candidate_id::TEXT AS candidate_id,admission.source_event_id,
|
|
727
|
+
source.observed_at AS created_at
|
|
728
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
729
|
+
CROSS JOIN LATERAL unnest(candidate.source_event_ids) requested(event_id)
|
|
730
|
+
JOIN agent_memory_consolidation_admissions admission
|
|
731
|
+
ON admission.namespace=candidate.namespace AND admission.scope_kind=candidate.scope_kind
|
|
732
|
+
AND admission.scope_key=candidate.scope_key
|
|
733
|
+
AND admission.workflow=candidate.workflow AND admission.consent_version=candidate.consent_version
|
|
734
|
+
AND admission.source_event_id=requested.event_id AND admission.status='done'
|
|
735
|
+
AND admission.expires_at>now()
|
|
736
|
+
${sourceJoin('admission')}
|
|
737
|
+
WHERE candidate.candidate_id=ANY($1::UUID[])
|
|
738
|
+
FOR SHARE OF admission,source`, [candidates.map((row) => row.candidate_id)]);
|
|
739
|
+
const metadataByCandidate = new Map();
|
|
740
|
+
for (const row of metadata.rows) {
|
|
741
|
+
const sources = metadataByCandidate.get(row.candidate_id) ?? new Set();
|
|
742
|
+
sources.add(row.source_event_id);
|
|
743
|
+
metadataByCandidate.set(row.candidate_id, sources);
|
|
744
|
+
}
|
|
745
|
+
const invalidSourceIds = candidates
|
|
746
|
+
.filter((candidate) => new Set(candidate.source_event_ids).size === 0 ||
|
|
747
|
+
(metadataByCandidate.get(candidate.candidate_id)?.size ?? 0) !==
|
|
748
|
+
new Set(candidate.source_event_ids).size)
|
|
749
|
+
.map((candidate) => candidate.candidate_id);
|
|
750
|
+
if (invalidSourceIds.length) {
|
|
751
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='expired',result_reason='source_expired',
|
|
752
|
+
content='[expired]',memory_key='expired',source_event_ids=ARRAY[]::TEXT[],
|
|
753
|
+
expected_revision=NULL,confirmed_by_event_id=NULL,updated_at=now()
|
|
754
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [invalidSourceIds]);
|
|
755
|
+
}
|
|
756
|
+
const validCandidates = candidates.filter((candidate) => !invalidSourceIds.includes(candidate.candidate_id));
|
|
757
|
+
if (!validCandidates.length) {
|
|
758
|
+
return { inspected: candidates.length, promoted: 0, rejected: 0, deferred: 0 };
|
|
759
|
+
}
|
|
760
|
+
// Observation text is read only after current consent, completed admission and expiry pass.
|
|
761
|
+
const sources = await client.query(`SELECT candidate.candidate_id::TEXT AS candidate_id,admission.source_event_id,
|
|
762
|
+
source.observed_at AS created_at,source.content
|
|
763
|
+
FROM agent_memory_consolidation_candidates candidate
|
|
764
|
+
CROSS JOIN LATERAL unnest(candidate.source_event_ids) requested(event_id)
|
|
765
|
+
JOIN agent_memory_consolidation_admissions admission
|
|
766
|
+
ON admission.namespace=candidate.namespace AND admission.scope_kind=candidate.scope_kind
|
|
767
|
+
AND admission.scope_key=candidate.scope_key
|
|
768
|
+
AND admission.workflow=candidate.workflow AND admission.consent_version=candidate.consent_version
|
|
769
|
+
AND admission.source_event_id=requested.event_id AND admission.status='done'
|
|
770
|
+
AND admission.expires_at>now()
|
|
771
|
+
${sourceJoin('admission')}
|
|
772
|
+
WHERE candidate.candidate_id=ANY($1::UUID[])
|
|
773
|
+
ORDER BY candidate.candidate_id,source.observed_at,admission.source_event_id
|
|
774
|
+
FOR SHARE OF admission,source`, [validCandidates.map((row) => row.candidate_id)]);
|
|
775
|
+
const sourcesByCandidate = new Map();
|
|
776
|
+
for (const row of sources.rows) {
|
|
777
|
+
const values = sourcesByCandidate.get(row.candidate_id) ?? [];
|
|
778
|
+
values.push(row);
|
|
779
|
+
sourcesByCandidate.set(row.candidate_id, values);
|
|
780
|
+
}
|
|
781
|
+
const values = new Map();
|
|
782
|
+
const rejectedIds = [];
|
|
783
|
+
const expiredIds = [];
|
|
784
|
+
for (const candidate of validCandidates) {
|
|
785
|
+
const normalizedContent = candidate.content.normalize('NFKC').trim();
|
|
786
|
+
const candidateSources = sourcesByCandidate.get(candidate.candidate_id) ?? [];
|
|
787
|
+
const sourceTextUnsafe = candidateSources.some((source) => sensitiveOrRiskText(source.content) || !hasSelfAttribution(source.content));
|
|
788
|
+
const candidateUnsafe = !normalizedContent ||
|
|
789
|
+
normalizedContent.length > 800 ||
|
|
790
|
+
sensitiveOrRiskText(normalizedContent);
|
|
791
|
+
const sourceMismatch = candidateSources.length !== new Set(candidate.source_event_ids).size ||
|
|
792
|
+
candidateSources.some((source) => !source.content.normalize('NFKC').includes(normalizedContent));
|
|
793
|
+
if (sourceTextUnsafe || candidateUnsafe || sourceMismatch) {
|
|
794
|
+
rejectedIds.push(candidate.candidate_id);
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
if (candidate.valid_until && candidate.valid_until.getTime() <= this.now()) {
|
|
798
|
+
expiredIds.push(candidate.candidate_id);
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
const value = values.get(normalizedContent) ?? {
|
|
802
|
+
content: normalizedContent,
|
|
803
|
+
candidates: [],
|
|
804
|
+
sources: new Map(),
|
|
805
|
+
};
|
|
806
|
+
value.candidates.push(candidate);
|
|
807
|
+
for (const source of candidateSources) {
|
|
808
|
+
value.sources.set(source.source_event_id, {
|
|
809
|
+
createdAt: source.created_at,
|
|
810
|
+
content: source.content,
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
values.set(normalizedContent, value);
|
|
814
|
+
}
|
|
815
|
+
if (rejectedIds.length) {
|
|
816
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='rejected',result_reason=NULL,
|
|
817
|
+
memory_key='rejected',content='[rejected]',source_event_ids=ARRAY[]::TEXT[],
|
|
818
|
+
expected_revision=NULL,confirmed_by_event_id=NULL,updated_at=now()
|
|
819
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [rejectedIds]);
|
|
820
|
+
}
|
|
821
|
+
if (expiredIds.length) {
|
|
822
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='expired',result_reason=NULL,
|
|
823
|
+
memory_key='expired',content='[expired]',source_event_ids=ARRAY[]::TEXT[],
|
|
824
|
+
expected_revision=NULL,confirmed_by_event_id=NULL,updated_at=now()
|
|
825
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [expiredIds]);
|
|
826
|
+
}
|
|
827
|
+
const rejected = rejectedIds.length;
|
|
828
|
+
const deferredCandidates = validCandidates.length - rejectedIds.length - expiredIds.length;
|
|
829
|
+
if (!values.size) {
|
|
830
|
+
return {
|
|
831
|
+
inspected: candidates.length,
|
|
832
|
+
promoted: 0,
|
|
833
|
+
rejected,
|
|
834
|
+
deferred: Math.max(0, deferredCandidates),
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
// A tombstone is an explicit boundary: Deep has no path that can restore it.
|
|
838
|
+
if (current?.revoked_at || current?.superseded_at) {
|
|
839
|
+
return {
|
|
840
|
+
inspected: candidates.length,
|
|
841
|
+
promoted: 0,
|
|
842
|
+
rejected,
|
|
843
|
+
deferred: deferredCandidates,
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
let usage = { recallCount: 0, distinctQueries: 0, usedCount: 0 };
|
|
847
|
+
if (current && (!current.valid_until || current.valid_until.getTime() > this.now())) {
|
|
848
|
+
const result = await client.query(`SELECT COUNT(*) FILTER (WHERE signal_kind='recalled')::INTEGER AS recall_count,
|
|
849
|
+
COUNT(DISTINCT query_fingerprint) FILTER (WHERE signal_kind='recalled')::INTEGER AS distinct_queries,
|
|
850
|
+
COUNT(*) FILTER (WHERE signal_kind='used')::INTEGER AS used_count
|
|
851
|
+
FROM agent_memory_usage_signals
|
|
852
|
+
WHERE namespace=$1 AND scope_kind=$2 AND scope_key=$3 AND memory_key=$4
|
|
853
|
+
AND memory_revision=$5::BIGINT AND memory_source_event_id=$6 AND expires_at>now()`, [...base, memoryKey, current.revision, current.source_event_id]);
|
|
854
|
+
usage = {
|
|
855
|
+
recallCount: result.rows[0]?.recall_count ?? 0,
|
|
856
|
+
distinctQueries: result.rows[0]?.distinct_queries ?? 0,
|
|
857
|
+
usedCount: result.rows[0]?.used_count ?? 0,
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
const summarized = [...values.values()].map((value) => {
|
|
861
|
+
const sourceRows = [...value.sources.entries()].map(([eventId, source]) => ({
|
|
862
|
+
eventId,
|
|
863
|
+
...source,
|
|
864
|
+
}));
|
|
865
|
+
const latestSource = sourceRows.reduce((latest, source) => source.createdAt > latest.createdAt ||
|
|
866
|
+
(source.createdAt.getTime() === latest.createdAt.getTime() &&
|
|
867
|
+
source.eventId > latest.eventId)
|
|
868
|
+
? source
|
|
869
|
+
: latest);
|
|
870
|
+
const latestCandidate = value.candidates.reduce((latest, candidate) => candidate.created_at > latest.created_at ? candidate : latest);
|
|
871
|
+
const days = new Set(sourceRows.map((source) => source.createdAt.toISOString().slice(0, 10)));
|
|
872
|
+
return { ...value, sourceRows, latestSource, latestCandidate, days };
|
|
873
|
+
});
|
|
874
|
+
const evaluated = summarized.map((value) => {
|
|
875
|
+
const competingValues = summarized.filter((other) => other !== value && other.sources.size >= value.sources.size).length;
|
|
876
|
+
const ageDays = Math.max(0, (this.now() - value.latestSource.createdAt.getTime()) / 86_400_000);
|
|
877
|
+
const decision = evaluateDeepPromotion({
|
|
878
|
+
candidateKind: value.latestCandidate.candidate_kind,
|
|
879
|
+
sourceReliability: AUTO_LEARN_SOURCE_RELIABILITY,
|
|
880
|
+
supportingObservations: value.sources.size,
|
|
881
|
+
distinctObservationDays: value.days.size,
|
|
882
|
+
recallCount: usage.recallCount,
|
|
883
|
+
distinctQueries: usage.distinctQueries,
|
|
884
|
+
usedCount: usage.usedCount,
|
|
885
|
+
ageDays,
|
|
886
|
+
conflictsWithCurrent: Boolean(current && current.content.normalize('NFKC').trim() !== value.content),
|
|
887
|
+
competingValues,
|
|
888
|
+
prohibited: false,
|
|
889
|
+
});
|
|
890
|
+
return { ...value, decision };
|
|
891
|
+
});
|
|
892
|
+
const promotable = evaluated.filter((value) => value.decision.promote);
|
|
893
|
+
if (promotable.length !== 1) {
|
|
894
|
+
return {
|
|
895
|
+
inspected: candidates.length,
|
|
896
|
+
promoted: 0,
|
|
897
|
+
rejected,
|
|
898
|
+
deferred: deferredCandidates,
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
const winner = promotable[0];
|
|
902
|
+
if (current &&
|
|
903
|
+
(!current.valid_until || current.valid_until.getTime() > this.now()) &&
|
|
904
|
+
current.content.normalize('NFKC').trim() === winner.content) {
|
|
905
|
+
const winnerIds = winner.candidates.map((candidate) => candidate.candidate_id);
|
|
906
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='duplicate',result_reason='already_present',
|
|
907
|
+
expected_revision=$2::BIGINT,updated_at=now()
|
|
908
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [winnerIds, current.revision]);
|
|
909
|
+
return {
|
|
910
|
+
inspected: candidates.length,
|
|
911
|
+
promoted: 0,
|
|
912
|
+
rejected,
|
|
913
|
+
deferred: Math.max(0, deferredCandidates - winnerIds.length),
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
const expectedRevision = current?.revision ?? null;
|
|
917
|
+
if (winner.candidates.some((candidate) => candidate.expected_revision !== expectedRevision)) {
|
|
918
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='conflict',result_reason='cas_conflict',updated_at=now()
|
|
919
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [winner.candidates.map((candidate) => candidate.candidate_id)]);
|
|
920
|
+
return {
|
|
921
|
+
inspected: candidates.length,
|
|
922
|
+
promoted: 0,
|
|
923
|
+
rejected,
|
|
924
|
+
deferred: deferredCandidates,
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
let written;
|
|
928
|
+
if (current) {
|
|
929
|
+
const result = await client.query(`UPDATE agent_memory_entries SET content=$1,source_event_id=$2,source_kind='trusted_ingress',
|
|
930
|
+
source_reliability=$3,valid_until=$4,revision=revision+1,updated_at=now(),superseded_at=NULL
|
|
931
|
+
WHERE memory_id=$5::UUID AND revision=$6::BIGINT AND revoked_at IS NULL AND superseded_at IS NULL
|
|
932
|
+
RETURNING memory_id::TEXT AS memory_id,revision::TEXT AS revision`, [
|
|
933
|
+
winner.content,
|
|
934
|
+
winner.latestSource.eventId,
|
|
935
|
+
AUTO_LEARN_SOURCE_RELIABILITY,
|
|
936
|
+
winner.latestCandidate.valid_until,
|
|
937
|
+
current.memory_id,
|
|
938
|
+
current.revision,
|
|
939
|
+
]);
|
|
940
|
+
written = result.rows[0];
|
|
941
|
+
}
|
|
942
|
+
else {
|
|
943
|
+
const result = await client.query(`INSERT INTO agent_memory_entries(
|
|
944
|
+
namespace,scope_kind,scope_key,memory_key,content,source_event_id,source_kind,source_reliability,valid_until
|
|
945
|
+
) VALUES ($1,$2,$3,$4,$5,$6,'trusted_ingress',$7,$8)
|
|
946
|
+
ON CONFLICT DO NOTHING RETURNING memory_id::TEXT AS memory_id,revision::TEXT AS revision`, [
|
|
947
|
+
...base,
|
|
948
|
+
memoryKey,
|
|
949
|
+
winner.content,
|
|
950
|
+
winner.latestSource.eventId,
|
|
951
|
+
AUTO_LEARN_SOURCE_RELIABILITY,
|
|
952
|
+
winner.latestCandidate.valid_until,
|
|
953
|
+
]);
|
|
954
|
+
written = result.rows[0];
|
|
955
|
+
}
|
|
956
|
+
if (!written) {
|
|
957
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='conflict',result_reason='cas_conflict',updated_at=now()
|
|
958
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [winner.candidates.map((candidate) => candidate.candidate_id)]);
|
|
959
|
+
return {
|
|
960
|
+
inspected: candidates.length,
|
|
961
|
+
promoted: 0,
|
|
962
|
+
rejected,
|
|
963
|
+
deferred: deferredCandidates,
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
await client.query(`INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation,index_version)
|
|
967
|
+
SELECT $1::UUID,$2::BIGINT,'upsert',generation.index_version
|
|
968
|
+
FROM agent_memory_index_job_versions($3) generation ON CONFLICT DO NOTHING`, [written.memory_id, written.revision, this.namespace]);
|
|
969
|
+
const winnerIds = winner.candidates.map((candidate) => candidate.candidate_id);
|
|
970
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='promoted',confirmed_by_event_id=NULL,
|
|
971
|
+
expected_revision=$2::BIGINT,result_reason=NULL,updated_at=now()
|
|
972
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [winnerIds, written.revision]);
|
|
973
|
+
const losingIds = candidates
|
|
974
|
+
.filter((candidate) => !winnerIds.includes(candidate.candidate_id))
|
|
975
|
+
.map((candidate) => candidate.candidate_id);
|
|
976
|
+
if (losingIds.length) {
|
|
977
|
+
await client.query(`UPDATE agent_memory_consolidation_candidates SET status='rejected',result_reason=NULL,
|
|
978
|
+
memory_key='rejected',content='[rejected]',source_event_ids=ARRAY[]::TEXT[],
|
|
979
|
+
expected_revision=NULL,confirmed_by_event_id=NULL,updated_at=now()
|
|
980
|
+
WHERE candidate_id=ANY($1::UUID[]) AND status IN ('pending_confirmation','conflict')`, [losingIds]);
|
|
981
|
+
}
|
|
982
|
+
return {
|
|
983
|
+
inspected: candidates.length,
|
|
984
|
+
promoted: 1,
|
|
985
|
+
rejected: rejected + losingIds.length,
|
|
986
|
+
deferred: Math.max(0, deferredCandidates - winnerIds.length - losingIds.length),
|
|
987
|
+
};
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
async failed(batch, reason) {
|
|
991
|
+
const dead = batch.some((row) => row.attempt_count >= this.maxAttempts);
|
|
992
|
+
const waitSeconds = Math.min(3600, 5 * 2 ** Math.min(batch[0].attempt_count, 9));
|
|
993
|
+
await this.pool.query(`UPDATE agent_memory_consolidation_admissions SET status=$3,
|
|
994
|
+
next_attempt_at=now()+($4::INTEGER*interval '1 second'),
|
|
995
|
+
skip_reason=CASE WHEN $3='dead' THEN 'system_work_unavailable' ELSE NULL END,
|
|
996
|
+
lease_token=NULL,lease_until=NULL,updated_at=now()
|
|
997
|
+
WHERE admission_id=ANY($1::uuid[]) AND status='processing' AND lease_token=$2::uuid`, [
|
|
998
|
+
batch.map((row) => row.admission_id),
|
|
999
|
+
batch[0].lease_token,
|
|
1000
|
+
dead ? 'dead' : 'retry',
|
|
1001
|
+
waitSeconds,
|
|
1002
|
+
]);
|
|
1003
|
+
void reason; // Provider detail is deliberately never stored or logged.
|
|
1004
|
+
return dead ? 'dead' : 'retry';
|
|
1005
|
+
}
|
|
1006
|
+
async processNext(workflow, signal) {
|
|
1007
|
+
const batch = await this.claim(workflow);
|
|
1008
|
+
if (!batch?.length)
|
|
1009
|
+
return { status: 'SKIPPED_NO_ELIGIBLE_CORPUS', workflow };
|
|
1010
|
+
const metadata = await this.authorizeMetadata(batch);
|
|
1011
|
+
if (!metadata.valid.length)
|
|
1012
|
+
return {
|
|
1013
|
+
status: 'skipped',
|
|
1014
|
+
workflow,
|
|
1015
|
+
reason: 'no_authorized_source',
|
|
1016
|
+
admitted: batch.length,
|
|
1017
|
+
};
|
|
1018
|
+
const controller = new AbortController();
|
|
1019
|
+
const timeout = setTimeout(() => controller.abort(new Error('agent_memory_consolidation_timeout')), this.timeoutMs);
|
|
1020
|
+
const abort = () => controller.abort(signal?.reason);
|
|
1021
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
1022
|
+
try {
|
|
1023
|
+
const messages = await this.readMessages(metadata.valid);
|
|
1024
|
+
const messageIds = new Set(messages.map((item) => item.admission_id));
|
|
1025
|
+
const missingMessages = metadata.valid.filter((item) => !messageIds.has(item.admission_id));
|
|
1026
|
+
if (missingMessages.length)
|
|
1027
|
+
await this.skip(missingMessages, 'source_provenance_missing');
|
|
1028
|
+
const readable = metadata.valid.filter((item) => messageIds.has(item.admission_id));
|
|
1029
|
+
if (!messages.length) {
|
|
1030
|
+
return {
|
|
1031
|
+
status: 'skipped',
|
|
1032
|
+
workflow,
|
|
1033
|
+
reason: 'source_provenance_missing',
|
|
1034
|
+
admitted: batch.length,
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
const totalCharacters = messages.reduce((total, item) => total + item.content.length, 0);
|
|
1038
|
+
if (totalCharacters > this.maxInputCharacters) {
|
|
1039
|
+
await this.skip(readable, 'input_over_budget');
|
|
1040
|
+
return { status: 'skipped', workflow, reason: 'input_over_budget', admitted: batch.length };
|
|
1041
|
+
}
|
|
1042
|
+
const raw = await this.planner.plan({
|
|
1043
|
+
workflow,
|
|
1044
|
+
messages: messages.map((item) => ({
|
|
1045
|
+
content: item.content,
|
|
1046
|
+
createdAt: item.created_at.toISOString(),
|
|
1047
|
+
})),
|
|
1048
|
+
}, controller.signal);
|
|
1049
|
+
if (controller.signal.aborted)
|
|
1050
|
+
throw new Error('agent_memory_consolidation_timeout');
|
|
1051
|
+
const candidates = this.validateCandidates(raw, messages, workflow);
|
|
1052
|
+
const completed = await this.complete(readable, messages, candidates);
|
|
1053
|
+
if (!completed)
|
|
1054
|
+
return { status: 'skipped', workflow, reason: 'consent_revoked', admitted: batch.length };
|
|
1055
|
+
return {
|
|
1056
|
+
status: 'processed',
|
|
1057
|
+
workflow,
|
|
1058
|
+
admitted: metadata.valid.length,
|
|
1059
|
+
candidates: candidates.length,
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
catch {
|
|
1063
|
+
const timedOut = controller.signal.aborted;
|
|
1064
|
+
const status = await this.failed(metadata.valid.filter((item) => !item.lease_token || item.lease_token === batch[0].lease_token), timedOut ? 'worker_timeout' : 'planner_failed');
|
|
1065
|
+
return { status: timedOut ? 'timed_out' : status, workflow, admitted: metadata.valid.length };
|
|
1066
|
+
}
|
|
1067
|
+
finally {
|
|
1068
|
+
clearTimeout(timeout);
|
|
1069
|
+
signal?.removeEventListener('abort', abort);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
}
|