@rine-kit/agent-memory-postgres 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/consolidation.d.ts +150 -0
- package/dist/consolidation.js +1072 -0
- package/dist/conversation-checkpoints.d.ts +15 -0
- package/dist/conversation-checkpoints.js +72 -0
- package/dist/dreaming-run-store.d.ts +15 -0
- package/dist/dreaming-run-store.js +22 -0
- package/dist/embedding-budget.d.ts +9 -0
- package/dist/embedding-budget.js +45 -0
- package/dist/index-generation.d.ts +39 -0
- package/dist/index-generation.js +229 -0
- package/dist/index-worker.d.ts +17 -0
- package/dist/index-worker.js +266 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +10 -0
- package/dist/migrate.d.ts +10 -0
- package/dist/migrate.js +63 -0
- package/dist/retention.d.ts +13 -0
- package/dist/retention.js +14 -0
- package/dist/scope.d.ts +23 -0
- package/dist/scope.js +25 -0
- package/dist/store.d.ts +48 -0
- package/dist/store.js +490 -0
- package/migrations/0001_memory_foundation.sql +67 -0
- package/migrations/0002_memory_embedding_index.sql +76 -0
- package/migrations/0003_memory_dreaming_runs.sql +19 -0
- package/migrations/0004_memory_consolidation.sql +101 -0
- package/migrations/0005_memory_conversation_checkpoints.sql +18 -0
- package/migrations/vector/0001_memory_pgvector.sql +34 -0
- package/package.json +40 -3
- package/README.md +0 -3
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
import type { CheckpointSourceRow, ConversationCheckpointView } from '@rine-kit/agent-memory';
|
|
3
|
+
export interface ConversationCheckpointScope {
|
|
4
|
+
namespace: string;
|
|
5
|
+
/** Names one conversation in the host (a room, a channel, a DM pair). Opaque to this package. */
|
|
6
|
+
conversationKey: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Rebuilds the stored checkpoint of one conversation from the rows the host says are older than the
|
|
10
|
+
* live window (newest first, at most 100). The generation only moves when the covered rows changed.
|
|
11
|
+
* No model is involved; running it again is harmless.
|
|
12
|
+
*/
|
|
13
|
+
export declare function refreshConversationCheckpoint(pool: Pool, scope: ConversationCheckpointScope, olderRowsNewestFirst: readonly CheckpointSourceRow[]): Promise<void>;
|
|
14
|
+
/** The stored checkpoint in the shape the context budget builder takes, or null. */
|
|
15
|
+
export declare function loadConversationCheckpoint(pool: Pool, scope: ConversationCheckpointScope): Promise<ConversationCheckpointView | null>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { buildExtractiveCheckpoint } from '@rine-kit/agent-memory';
|
|
3
|
+
import { boundedText } from './scope.js';
|
|
4
|
+
function args(scope) {
|
|
5
|
+
return [boundedText(scope.namespace, 128), boundedText(scope.conversationKey, 256)];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Rebuilds the stored checkpoint of one conversation from the rows the host says are older than the
|
|
9
|
+
* live window (newest first, at most 100). The generation only moves when the covered rows changed.
|
|
10
|
+
* No model is involved; running it again is harmless.
|
|
11
|
+
*/
|
|
12
|
+
export async function refreshConversationCheckpoint(pool, scope, olderRowsNewestFirst) {
|
|
13
|
+
const checkpoint = buildExtractiveCheckpoint(olderRowsNewestFirst);
|
|
14
|
+
if (!checkpoint || !checkpoint.text)
|
|
15
|
+
return;
|
|
16
|
+
const [namespace, key] = args(scope);
|
|
17
|
+
const client = await pool.connect();
|
|
18
|
+
try {
|
|
19
|
+
await client.query('BEGIN');
|
|
20
|
+
const lock = createHash('sha256').update(`${namespace}\0${key}`).digest('hex');
|
|
21
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
|
22
|
+
`memory-checkpoint:${lock}`,
|
|
23
|
+
]);
|
|
24
|
+
await client.query(`INSERT INTO agent_memory_conversation_checkpoints(
|
|
25
|
+
namespace,conversation_key,generation,coverage_from,coverage_through,covered_message_count,
|
|
26
|
+
source_event_ids,checkpoint_text,source_digest,rebuildable,updated_at
|
|
27
|
+
) VALUES ($1,$2,1,$3::TIMESTAMPTZ,$4::TIMESTAMPTZ,$5,$6::TEXT[],$7,$8,true,now())
|
|
28
|
+
ON CONFLICT (namespace,conversation_key) DO UPDATE SET
|
|
29
|
+
generation=CASE WHEN agent_memory_conversation_checkpoints.source_digest IS DISTINCT FROM EXCLUDED.source_digest
|
|
30
|
+
THEN agent_memory_conversation_checkpoints.generation+1 ELSE agent_memory_conversation_checkpoints.generation END,
|
|
31
|
+
coverage_from=EXCLUDED.coverage_from,coverage_through=EXCLUDED.coverage_through,
|
|
32
|
+
covered_message_count=EXCLUDED.covered_message_count,source_event_ids=EXCLUDED.source_event_ids,
|
|
33
|
+
checkpoint_text=EXCLUDED.checkpoint_text,source_digest=EXCLUDED.source_digest,
|
|
34
|
+
rebuildable=true,updated_at=CASE WHEN agent_memory_conversation_checkpoints.source_digest IS DISTINCT FROM EXCLUDED.source_digest
|
|
35
|
+
THEN now() ELSE agent_memory_conversation_checkpoints.updated_at END`, [
|
|
36
|
+
namespace,
|
|
37
|
+
key,
|
|
38
|
+
checkpoint.coverageFrom,
|
|
39
|
+
checkpoint.coverageThrough,
|
|
40
|
+
checkpoint.coveredMessageCount,
|
|
41
|
+
checkpoint.sourceEventIds,
|
|
42
|
+
checkpoint.text,
|
|
43
|
+
checkpoint.sourceDigest,
|
|
44
|
+
]);
|
|
45
|
+
await client.query('COMMIT');
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
await client.query('ROLLBACK').catch(() => undefined);
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
client.release();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** The stored checkpoint in the shape the context budget builder takes, or null. */
|
|
56
|
+
export async function loadConversationCheckpoint(pool, scope) {
|
|
57
|
+
const [namespace, key] = args(scope);
|
|
58
|
+
const result = await pool.query(`SELECT checkpoint_text,generation::TEXT AS generation,coverage_from,coverage_through,
|
|
59
|
+
covered_message_count,source_event_ids
|
|
60
|
+
FROM agent_memory_conversation_checkpoints WHERE namespace=$1 AND conversation_key=$2`, [namespace, key]);
|
|
61
|
+
const row = result.rows[0];
|
|
62
|
+
return row
|
|
63
|
+
? {
|
|
64
|
+
text: row.checkpoint_text,
|
|
65
|
+
generation: Number(row.generation),
|
|
66
|
+
coverageFrom: row.coverage_from.toISOString(),
|
|
67
|
+
coverageThrough: row.coverage_through.toISOString(),
|
|
68
|
+
coveredMessageCount: row.covered_message_count,
|
|
69
|
+
sourceEventIds: row.source_event_ids,
|
|
70
|
+
}
|
|
71
|
+
: null;
|
|
72
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
import type { MemoryDreamingRunStore } from '@rine-kit/agent-memory';
|
|
3
|
+
export interface MemoryDreamingRunIdentity {
|
|
4
|
+
namespace: string;
|
|
5
|
+
timezone: string;
|
|
6
|
+
localDate: string;
|
|
7
|
+
scheduledAt: Date;
|
|
8
|
+
}
|
|
9
|
+
/** Durable claim so a scheduled Dreaming run happens once per namespace and local date (Gate's run store). */
|
|
10
|
+
export declare class PostgresMemoryDreamingRunStore implements MemoryDreamingRunStore<MemoryDreamingRunIdentity> {
|
|
11
|
+
private readonly pool;
|
|
12
|
+
constructor(pool: Pool);
|
|
13
|
+
claim(identity: MemoryDreamingRunIdentity): Promise<string | null>;
|
|
14
|
+
finish(identity: MemoryDreamingRunIdentity, runId: string, status: 'succeeded' | 'failed'): Promise<void>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Durable claim so a scheduled Dreaming run happens once per namespace and local date (Gate's run store). */
|
|
2
|
+
export class PostgresMemoryDreamingRunStore {
|
|
3
|
+
pool;
|
|
4
|
+
constructor(pool) {
|
|
5
|
+
this.pool = pool;
|
|
6
|
+
}
|
|
7
|
+
async claim(identity) {
|
|
8
|
+
const result = await this.pool.query(`INSERT INTO agent_memory_dreaming_runs(namespace,timezone,scheduled_date,scheduled_at)
|
|
9
|
+
VALUES ($1,$2,$3::DATE,$4::TIMESTAMPTZ)
|
|
10
|
+
ON CONFLICT (namespace,timezone,scheduled_date) DO NOTHING
|
|
11
|
+
RETURNING run_id::TEXT`, [identity.namespace, identity.timezone, identity.localDate, identity.scheduledAt]);
|
|
12
|
+
return result.rows[0]?.run_id ?? null;
|
|
13
|
+
}
|
|
14
|
+
async finish(identity, runId, status) {
|
|
15
|
+
const result = await this.pool.query(`UPDATE agent_memory_dreaming_runs SET status=$5,completed_at=now(),
|
|
16
|
+
error_code=CASE WHEN $5='failed' THEN 'dreaming_run_failed' ELSE NULL END
|
|
17
|
+
WHERE namespace=$1 AND timezone=$2 AND scheduled_date=$3::DATE
|
|
18
|
+
AND run_id=$4::UUID AND status='running'`, [identity.namespace, identity.timezone, identity.localDate, runId, status]);
|
|
19
|
+
if (result.rowCount !== 1)
|
|
20
|
+
throw new Error('agent_memory_dreaming_run_state_lost');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
export interface MemoryEmbeddingBudgetLimits {
|
|
3
|
+
dailyTokenBudget: number;
|
|
4
|
+
dailyRequestBudget: number;
|
|
5
|
+
}
|
|
6
|
+
/** Atomically reserves estimated request cost across workers. Unknown responses are settled at the
|
|
7
|
+
* estimate so provider failures cannot refund a request that may already have been billed. */
|
|
8
|
+
export declare function reserveMemoryEmbeddingBudget(pool: Pool, namespace: string, estimatedTokens: number, limits: MemoryEmbeddingBudgetLimits): Promise<string | null>;
|
|
9
|
+
export declare function settleMemoryEmbeddingBudget(pool: Pool, namespace: string, budgetDay: string, reservedTokens: number, actualTokens: number | null): Promise<void>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Atomically reserves estimated request cost across workers. Unknown responses are settled at the
|
|
2
|
+
* estimate so provider failures cannot refund a request that may already have been billed. */
|
|
3
|
+
export async function reserveMemoryEmbeddingBudget(pool, namespace, estimatedTokens, limits) {
|
|
4
|
+
if (!Number.isSafeInteger(estimatedTokens) ||
|
|
5
|
+
estimatedTokens < 1 ||
|
|
6
|
+
!Number.isSafeInteger(limits.dailyTokenBudget) ||
|
|
7
|
+
limits.dailyTokenBudget < 1 ||
|
|
8
|
+
!Number.isSafeInteger(limits.dailyRequestBudget) ||
|
|
9
|
+
limits.dailyRequestBudget < 1) {
|
|
10
|
+
throw new Error('agent_memory_embedding_budget_invalid');
|
|
11
|
+
}
|
|
12
|
+
if (estimatedTokens > limits.dailyTokenBudget || limits.dailyRequestBudget < 1)
|
|
13
|
+
return null;
|
|
14
|
+
const result = await pool.query(`INSERT INTO agent_memory_embedding_usage_daily(
|
|
15
|
+
namespace,budget_day,actual_tokens,reserved_tokens,request_count,reserved_updated_at
|
|
16
|
+
) VALUES ($1,(now() AT TIME ZONE 'UTC')::DATE,0,$2,1,now())
|
|
17
|
+
ON CONFLICT (namespace,budget_day) DO UPDATE SET
|
|
18
|
+
reserved_tokens=CASE
|
|
19
|
+
WHEN agent_memory_embedding_usage_daily.reserved_updated_at < now()-interval '15 minutes' THEN $2
|
|
20
|
+
ELSE agent_memory_embedding_usage_daily.reserved_tokens+$2 END,
|
|
21
|
+
request_count=agent_memory_embedding_usage_daily.request_count+1,
|
|
22
|
+
reserved_updated_at=now()
|
|
23
|
+
WHERE agent_memory_embedding_usage_daily.actual_tokens
|
|
24
|
+
+ CASE WHEN agent_memory_embedding_usage_daily.reserved_updated_at < now()-interval '15 minutes'
|
|
25
|
+
THEN 0 ELSE agent_memory_embedding_usage_daily.reserved_tokens END + $2 <= $3
|
|
26
|
+
AND agent_memory_embedding_usage_daily.request_count+1 <= $4
|
|
27
|
+
RETURNING budget_day::TEXT`, [namespace, estimatedTokens, limits.dailyTokenBudget, limits.dailyRequestBudget]);
|
|
28
|
+
return result.rows[0]?.budget_day ?? null;
|
|
29
|
+
}
|
|
30
|
+
export async function settleMemoryEmbeddingBudget(pool, namespace, budgetDay, reservedTokens, actualTokens) {
|
|
31
|
+
if (!Number.isSafeInteger(reservedTokens) ||
|
|
32
|
+
reservedTokens < 1 ||
|
|
33
|
+
(actualTokens !== null && (!Number.isFinite(actualTokens) || actualTokens < 0))) {
|
|
34
|
+
throw new Error('agent_memory_embedding_budget_invalid');
|
|
35
|
+
}
|
|
36
|
+
await pool.query(`UPDATE agent_memory_embedding_usage_daily SET
|
|
37
|
+
reserved_tokens=GREATEST(0,reserved_tokens-$3),
|
|
38
|
+
actual_tokens=actual_tokens+$4,reserved_updated_at=now()
|
|
39
|
+
WHERE namespace=$1 AND budget_day=$2::DATE`, [
|
|
40
|
+
namespace,
|
|
41
|
+
budgetDay,
|
|
42
|
+
reservedTokens,
|
|
43
|
+
actualTokens === null ? reservedTokens : Math.max(reservedTokens, Math.floor(actualTokens)),
|
|
44
|
+
]);
|
|
45
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Pool, QueryResultRow } from 'pg';
|
|
2
|
+
import type { MemoryEmbeddingContract } from '@rine-kit/agent-memory';
|
|
3
|
+
export interface MemoryIndexGenerationState extends QueryResultRow {
|
|
4
|
+
namespace: string;
|
|
5
|
+
active_provider_id: string;
|
|
6
|
+
active_model_id: string;
|
|
7
|
+
active_dimensions: number;
|
|
8
|
+
active_index_version: number;
|
|
9
|
+
latest_index_version: number;
|
|
10
|
+
building_provider_id: string | null;
|
|
11
|
+
building_model_id: string | null;
|
|
12
|
+
building_dimensions: number | null;
|
|
13
|
+
building_index_version: number | null;
|
|
14
|
+
reindex_status: 'idle' | 'building' | 'paused' | 'failed';
|
|
15
|
+
scan_cursor_memory_id: string | null;
|
|
16
|
+
scan_complete: boolean;
|
|
17
|
+
last_error_code: string | null;
|
|
18
|
+
}
|
|
19
|
+
export interface MemoryIndexScanResult {
|
|
20
|
+
scanned: number;
|
|
21
|
+
queued: number;
|
|
22
|
+
complete: boolean;
|
|
23
|
+
cursor: string | null;
|
|
24
|
+
}
|
|
25
|
+
export declare class MemoryIndexGenerationManager {
|
|
26
|
+
private readonly pool;
|
|
27
|
+
constructor(pool: Pool);
|
|
28
|
+
private requireVectorSchema;
|
|
29
|
+
/** Bootstrap is intentionally limited to the legacy v1 generation. */
|
|
30
|
+
initialize(namespace: string, contract: MemoryEmbeddingContract): Promise<MemoryIndexGenerationState>;
|
|
31
|
+
status(namespace: string): Promise<MemoryIndexGenerationState | null>;
|
|
32
|
+
beginShadowReindex(namespace: string, target: MemoryEmbeddingContract): Promise<void>;
|
|
33
|
+
scanNextPage(namespace: string, limit?: number): Promise<MemoryIndexScanResult>;
|
|
34
|
+
pause(namespace: string): Promise<void>;
|
|
35
|
+
markFailed(namespace: string, errorCode: string): Promise<void>;
|
|
36
|
+
resume(namespace: string): Promise<number>;
|
|
37
|
+
cancel(namespace: string): Promise<boolean>;
|
|
38
|
+
activate(namespace: string): Promise<void>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
const REINDEX_STATEMENT_TIMEOUT = '3000ms';
|
|
2
|
+
function validContract(contract) {
|
|
3
|
+
if (typeof contract.providerId !== 'string' ||
|
|
4
|
+
contract.providerId.length < 1 ||
|
|
5
|
+
contract.providerId.length > 96 ||
|
|
6
|
+
typeof contract.modelId !== 'string' ||
|
|
7
|
+
contract.modelId.length < 1 ||
|
|
8
|
+
contract.modelId.length > 200 ||
|
|
9
|
+
!Number.isSafeInteger(contract.dimensions) ||
|
|
10
|
+
contract.dimensions < 1 ||
|
|
11
|
+
contract.dimensions > 16_000 ||
|
|
12
|
+
contract.normalization !== 'l2_unit' ||
|
|
13
|
+
!Number.isSafeInteger(contract.indexVersion) ||
|
|
14
|
+
contract.indexVersion < 1 ||
|
|
15
|
+
contract.indexVersion > 1_000_000) {
|
|
16
|
+
throw new Error('agent_memory_index_contract_invalid');
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
async function transaction(pool, work) {
|
|
20
|
+
const client = await pool.connect();
|
|
21
|
+
try {
|
|
22
|
+
await client.query('BEGIN');
|
|
23
|
+
const result = await work(client);
|
|
24
|
+
await client.query('COMMIT');
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
await client.query('ROLLBACK').catch(() => undefined);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
client.release();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class MemoryIndexGenerationManager {
|
|
36
|
+
pool;
|
|
37
|
+
constructor(pool) {
|
|
38
|
+
this.pool = pool;
|
|
39
|
+
}
|
|
40
|
+
async requireVectorSchema(client) {
|
|
41
|
+
const result = await client.query(`SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname='vector')
|
|
42
|
+
AND to_regclass('agent_memory_embeddings') IS NOT NULL AS available`);
|
|
43
|
+
if (result.rows[0]?.available !== true)
|
|
44
|
+
throw new Error('agent_memory_vector_index_unavailable');
|
|
45
|
+
}
|
|
46
|
+
/** Bootstrap is intentionally limited to the legacy v1 generation. */
|
|
47
|
+
async initialize(namespace, contract) {
|
|
48
|
+
validContract(contract);
|
|
49
|
+
if (!namespace || namespace.length > 128 || contract.indexVersion !== 1) {
|
|
50
|
+
throw new Error('agent_memory_index_initialization_invalid');
|
|
51
|
+
}
|
|
52
|
+
await this.pool.query(`INSERT INTO agent_memory_index_generation_state(
|
|
53
|
+
namespace,active_provider_id,active_model_id,active_dimensions,active_index_version
|
|
54
|
+
) VALUES ($1,$2,$3,$4,1) ON CONFLICT (namespace) DO NOTHING`, [namespace, contract.providerId, contract.modelId, contract.dimensions]);
|
|
55
|
+
const state = await this.status(namespace);
|
|
56
|
+
if (!state)
|
|
57
|
+
throw new Error('agent_memory_index_state_unavailable');
|
|
58
|
+
return state;
|
|
59
|
+
}
|
|
60
|
+
async status(namespace) {
|
|
61
|
+
const result = await this.pool.query('SELECT * FROM agent_memory_index_generation_state WHERE namespace=$1', [namespace]);
|
|
62
|
+
return result.rows[0] ?? null;
|
|
63
|
+
}
|
|
64
|
+
async beginShadowReindex(namespace, target) {
|
|
65
|
+
validContract(target);
|
|
66
|
+
if (!namespace || namespace.length > 128)
|
|
67
|
+
throw new Error('agent_memory_index_bot_invalid');
|
|
68
|
+
await this.requireVectorSchema(this.pool);
|
|
69
|
+
await transaction(this.pool, async (client) => {
|
|
70
|
+
const result = await client.query('SELECT * FROM agent_memory_index_generation_state WHERE namespace=$1 FOR UPDATE', [namespace]);
|
|
71
|
+
const state = result.rows[0];
|
|
72
|
+
if (!state)
|
|
73
|
+
throw new Error('agent_memory_index_state_unavailable');
|
|
74
|
+
if (state.reindex_status !== 'idle' || state.building_index_version !== null) {
|
|
75
|
+
throw new Error('agent_memory_index_generation_busy');
|
|
76
|
+
}
|
|
77
|
+
if (target.indexVersion <= state.latest_index_version)
|
|
78
|
+
throw new Error('agent_memory_index_version_not_monotonic');
|
|
79
|
+
await client.query(`UPDATE agent_memory_index_generation_state SET building_provider_id=$2,building_model_id=$3,
|
|
80
|
+
building_dimensions=$4,building_index_version=$5,latest_index_version=$5,reindex_status='building',
|
|
81
|
+
scan_cursor_memory_id=NULL,scan_complete=FALSE,last_error_code=NULL,
|
|
82
|
+
started_at=now(),updated_at=now() WHERE namespace=$1`, [namespace, target.providerId, target.modelId, target.dimensions, target.indexVersion]);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async scanNextPage(namespace, limit = 50) {
|
|
86
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)
|
|
87
|
+
throw new Error('agent_memory_index_scan_limit_invalid');
|
|
88
|
+
return transaction(this.pool, async (client) => {
|
|
89
|
+
await client.query("SELECT set_config('statement_timeout',$1,true)", [
|
|
90
|
+
REINDEX_STATEMENT_TIMEOUT,
|
|
91
|
+
]);
|
|
92
|
+
const stateResult = await client.query('SELECT * FROM agent_memory_index_generation_state WHERE namespace=$1 FOR UPDATE', [namespace]);
|
|
93
|
+
const state = stateResult.rows[0];
|
|
94
|
+
if (!state || state.building_index_version === null)
|
|
95
|
+
throw new Error('agent_memory_index_generation_missing');
|
|
96
|
+
if (state.reindex_status === 'paused')
|
|
97
|
+
throw new Error('agent_memory_index_generation_paused');
|
|
98
|
+
if (state.reindex_status !== 'building')
|
|
99
|
+
throw new Error('agent_memory_index_generation_not_building');
|
|
100
|
+
if (state.scan_complete)
|
|
101
|
+
return { scanned: 0, queued: 0, complete: true, cursor: state.scan_cursor_memory_id };
|
|
102
|
+
const memories = await client.query(`SELECT memory.memory_id,memory.revision::TEXT AS revision
|
|
103
|
+
FROM agent_memory_entries memory
|
|
104
|
+
WHERE memory.namespace=$1 AND memory.revoked_at IS NULL
|
|
105
|
+
AND (memory.valid_until IS NULL OR memory.valid_until>now())
|
|
106
|
+
AND ($2::UUID IS NULL OR memory.memory_id>$2::UUID)
|
|
107
|
+
ORDER BY memory.memory_id LIMIT $3`, [namespace, state.scan_cursor_memory_id, limit]);
|
|
108
|
+
let queued = 0;
|
|
109
|
+
for (const memory of memories.rows) {
|
|
110
|
+
const inserted = await client.query(`INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation,index_version)
|
|
111
|
+
VALUES ($1,$2,'upsert',$3) ON CONFLICT DO NOTHING`, [memory.memory_id, memory.revision, state.building_index_version]);
|
|
112
|
+
queued += inserted.rowCount ?? 0;
|
|
113
|
+
}
|
|
114
|
+
const cursor = memories.rows.at(-1)?.memory_id ?? state.scan_cursor_memory_id;
|
|
115
|
+
const complete = memories.rows.length < limit;
|
|
116
|
+
await client.query(`UPDATE agent_memory_index_generation_state SET scan_cursor_memory_id=$2,
|
|
117
|
+
scan_complete=$3,updated_at=now() WHERE namespace=$1`, [namespace, cursor, complete]);
|
|
118
|
+
return { scanned: memories.rows.length, queued, complete, cursor };
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
async pause(namespace) {
|
|
122
|
+
const result = await this.pool.query(`UPDATE agent_memory_index_generation_state SET reindex_status='paused',updated_at=now()
|
|
123
|
+
WHERE namespace=$1 AND reindex_status='building' AND building_index_version IS NOT NULL`, [namespace]);
|
|
124
|
+
if (result.rowCount !== 1)
|
|
125
|
+
throw new Error('agent_memory_index_generation_not_building');
|
|
126
|
+
}
|
|
127
|
+
async markFailed(namespace, errorCode) {
|
|
128
|
+
if (!/^[a-z0-9_]{1,64}$/u.test(errorCode))
|
|
129
|
+
throw new Error('agent_memory_index_error_code_invalid');
|
|
130
|
+
const result = await this.pool.query(`UPDATE agent_memory_index_generation_state SET reindex_status='failed',last_error_code=$2,updated_at=now()
|
|
131
|
+
WHERE namespace=$1 AND building_index_version IS NOT NULL
|
|
132
|
+
AND reindex_status IN ('building','paused')`, [namespace, errorCode]);
|
|
133
|
+
if (result.rowCount !== 1)
|
|
134
|
+
throw new Error('agent_memory_index_generation_not_active');
|
|
135
|
+
}
|
|
136
|
+
async resume(namespace) {
|
|
137
|
+
await this.requireVectorSchema(this.pool);
|
|
138
|
+
return transaction(this.pool, async (client) => {
|
|
139
|
+
await client.query("SELECT set_config('statement_timeout',$1,true)", [
|
|
140
|
+
REINDEX_STATEMENT_TIMEOUT,
|
|
141
|
+
]);
|
|
142
|
+
const result = await client.query(`UPDATE agent_memory_index_generation_state SET reindex_status='building',last_error_code=NULL,updated_at=now()
|
|
143
|
+
WHERE namespace=$1 AND reindex_status IN ('paused','failed') AND building_index_version IS NOT NULL
|
|
144
|
+
RETURNING *`, [namespace]);
|
|
145
|
+
const state = result.rows[0];
|
|
146
|
+
if (!state || state.building_index_version === null)
|
|
147
|
+
throw new Error('agent_memory_index_generation_not_paused');
|
|
148
|
+
const queued = await client.query(`INSERT INTO agent_memory_embedding_jobs(memory_id,source_revision,operation,index_version)
|
|
149
|
+
SELECT memory.memory_id,memory.revision,'upsert',$2
|
|
150
|
+
FROM agent_memory_entries memory
|
|
151
|
+
WHERE memory.namespace=$1 AND memory.revoked_at IS NULL
|
|
152
|
+
AND (memory.valid_until IS NULL OR memory.valid_until>now())
|
|
153
|
+
AND NOT EXISTS (
|
|
154
|
+
SELECT 1 FROM agent_memory_embeddings embedded
|
|
155
|
+
WHERE embedded.memory_id=memory.memory_id AND embedded.source_revision=memory.revision
|
|
156
|
+
AND embedded.provider_id=$3 AND embedded.model_id=$4 AND embedded.dimensions=$5
|
|
157
|
+
AND embedded.index_version=$2 AND embedded.normalization='l2_unit'
|
|
158
|
+
)
|
|
159
|
+
ON CONFLICT (memory_id,source_revision,index_version) DO UPDATE SET
|
|
160
|
+
status='pending',attempt_count=0,next_attempt_at=now(),lease_token=NULL,lease_until=NULL,
|
|
161
|
+
last_error_code=NULL,finished_at=NULL,updated_at=now()
|
|
162
|
+
WHERE agent_memory_embedding_jobs.status IN ('done','dead')`, [
|
|
163
|
+
namespace,
|
|
164
|
+
state.building_index_version,
|
|
165
|
+
state.building_provider_id,
|
|
166
|
+
state.building_model_id,
|
|
167
|
+
state.building_dimensions,
|
|
168
|
+
]);
|
|
169
|
+
return queued.rowCount ?? 0;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async cancel(namespace) {
|
|
173
|
+
return transaction(this.pool, async (client) => {
|
|
174
|
+
const result = await client.query('SELECT * FROM agent_memory_index_generation_state WHERE namespace=$1 FOR UPDATE', [namespace]);
|
|
175
|
+
const state = result.rows[0];
|
|
176
|
+
if (!state || state.building_index_version === null)
|
|
177
|
+
return false;
|
|
178
|
+
await client.query(`UPDATE agent_memory_embedding_jobs job SET status='done',lease_token=NULL,lease_until=NULL,
|
|
179
|
+
last_error_code='index_generation_cancelled',finished_at=now(),updated_at=now()
|
|
180
|
+
FROM agent_memory_entries memory
|
|
181
|
+
WHERE memory.memory_id=job.memory_id AND memory.namespace=$1
|
|
182
|
+
AND job.index_version=$2 AND job.operation='upsert'
|
|
183
|
+
AND job.status IN ('pending','retry','processing')`, [namespace, state.building_index_version]);
|
|
184
|
+
await client.query(`UPDATE agent_memory_index_generation_state SET building_provider_id=NULL,building_model_id=NULL,
|
|
185
|
+
building_dimensions=NULL,building_index_version=NULL,reindex_status='idle',scan_cursor_memory_id=NULL,
|
|
186
|
+
scan_complete=FALSE,last_error_code=NULL,started_at=NULL,updated_at=now()
|
|
187
|
+
WHERE namespace=$1`, [namespace]);
|
|
188
|
+
return true;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
async activate(namespace) {
|
|
192
|
+
await this.requireVectorSchema(this.pool);
|
|
193
|
+
await transaction(this.pool, async (client) => {
|
|
194
|
+
await client.query("SELECT set_config('statement_timeout',$1,true)", [
|
|
195
|
+
REINDEX_STATEMENT_TIMEOUT,
|
|
196
|
+
]);
|
|
197
|
+
const stateResult = await client.query('SELECT * FROM agent_memory_index_generation_state WHERE namespace=$1 FOR UPDATE', [namespace]);
|
|
198
|
+
const state = stateResult.rows[0];
|
|
199
|
+
if (!state || state.building_index_version === null)
|
|
200
|
+
throw new Error('agent_memory_index_generation_missing');
|
|
201
|
+
if (state.reindex_status !== 'building' || !state.scan_complete) {
|
|
202
|
+
throw new Error('agent_memory_index_generation_incomplete');
|
|
203
|
+
}
|
|
204
|
+
const missing = await client.query(`SELECT 1 FROM agent_memory_entries memory
|
|
205
|
+
WHERE memory.namespace=$1 AND memory.revoked_at IS NULL
|
|
206
|
+
AND (memory.valid_until IS NULL OR memory.valid_until>now())
|
|
207
|
+
AND NOT EXISTS (
|
|
208
|
+
SELECT 1 FROM agent_memory_embeddings embedded
|
|
209
|
+
WHERE embedded.memory_id=memory.memory_id AND embedded.source_revision=memory.revision
|
|
210
|
+
AND embedded.provider_id=$2 AND embedded.model_id=$3 AND embedded.dimensions=$4
|
|
211
|
+
AND embedded.index_version=$5 AND embedded.normalization='l2_unit'
|
|
212
|
+
) LIMIT 1`, [
|
|
213
|
+
namespace,
|
|
214
|
+
state.building_provider_id,
|
|
215
|
+
state.building_model_id,
|
|
216
|
+
state.building_dimensions,
|
|
217
|
+
state.building_index_version,
|
|
218
|
+
]);
|
|
219
|
+
if (missing.rowCount)
|
|
220
|
+
throw new Error('agent_memory_index_generation_has_missing_vectors');
|
|
221
|
+
await client.query(`UPDATE agent_memory_index_generation_state SET
|
|
222
|
+
active_provider_id=building_provider_id,active_model_id=building_model_id,
|
|
223
|
+
active_dimensions=building_dimensions,active_index_version=building_index_version,
|
|
224
|
+
building_provider_id=NULL,building_model_id=NULL,building_dimensions=NULL,building_index_version=NULL,
|
|
225
|
+
reindex_status='idle',scan_cursor_memory_id=NULL,scan_complete=FALSE,last_error_code=NULL,
|
|
226
|
+
started_at=NULL,updated_at=now() WHERE namespace=$1`, [namespace]);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
import { type MemoryEmbeddingClient } from '@rine-kit/agent-memory';
|
|
3
|
+
export type MemoryIndexWorkerResult = 'empty' | 'indexed' | 'deleted' | 'obsolete' | 'semantic_unconfigured' | 'budget_deferred' | 'retry' | 'dead';
|
|
4
|
+
export declare class MemoryIndexWorker {
|
|
5
|
+
private readonly pool;
|
|
6
|
+
private readonly provider;
|
|
7
|
+
private readonly maxAttempts;
|
|
8
|
+
constructor(pool: Pool, provider: MemoryEmbeddingClient | null, maxAttempts?: number);
|
|
9
|
+
private claim;
|
|
10
|
+
private availability;
|
|
11
|
+
private releaseUnconfigured;
|
|
12
|
+
private finish;
|
|
13
|
+
private failed;
|
|
14
|
+
private memory;
|
|
15
|
+
private writeEmbedding;
|
|
16
|
+
processOne(signal?: AbortSignal): Promise<MemoryIndexWorkerResult>;
|
|
17
|
+
}
|