@danielsimonjr/memoryjs 2.5.0 → 2.7.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/README.md +1048 -1152
- package/dist/cli/index.js +446 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/index.cjs +574 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +167 -4
- package/dist/index.d.ts +167 -4
- package/dist/index.js +571 -1
- package/dist/index.js.map +1 -1
- package/package.json +9 -1
package/dist/index.js
CHANGED
|
@@ -3413,6 +3413,144 @@ var init_WorkerPoolManager = __esm({
|
|
|
3413
3413
|
}
|
|
3414
3414
|
});
|
|
3415
3415
|
|
|
3416
|
+
// src/utils/WorkerTaskManager.ts
|
|
3417
|
+
function getWorkerTaskManager() {
|
|
3418
|
+
if (!DEFAULT_INSTANCE) DEFAULT_INSTANCE = new WorkerTaskManager();
|
|
3419
|
+
return DEFAULT_INSTANCE;
|
|
3420
|
+
}
|
|
3421
|
+
async function batchProcessViaWorkers(items, workerType, methodName, mapArgs, opts = {}) {
|
|
3422
|
+
if (items.length === 0) return [];
|
|
3423
|
+
const wtm = getWorkerTaskManager();
|
|
3424
|
+
const promises = items.map(
|
|
3425
|
+
(item, i) => wtm.submit(workerType, methodName, mapArgs(item, i), opts)
|
|
3426
|
+
);
|
|
3427
|
+
return Promise.all(promises);
|
|
3428
|
+
}
|
|
3429
|
+
var SUBMISSION_COUNTER, WorkerTaskManager, DEFAULT_INSTANCE;
|
|
3430
|
+
var init_WorkerTaskManager = __esm({
|
|
3431
|
+
"src/utils/WorkerTaskManager.ts"() {
|
|
3432
|
+
"use strict";
|
|
3433
|
+
init_esm_shims();
|
|
3434
|
+
init_taskScheduler();
|
|
3435
|
+
init_WorkerPoolManager();
|
|
3436
|
+
init_logger();
|
|
3437
|
+
SUBMISSION_COUNTER = 0;
|
|
3438
|
+
WorkerTaskManager = class {
|
|
3439
|
+
queue;
|
|
3440
|
+
poolManager;
|
|
3441
|
+
touchedPoolIds = /* @__PURE__ */ new Set();
|
|
3442
|
+
cancelledTaskIds = /* @__PURE__ */ new Set();
|
|
3443
|
+
handleStatus = /* @__PURE__ */ new Map();
|
|
3444
|
+
constructor(opts = {}) {
|
|
3445
|
+
this.queue = new TaskQueue({
|
|
3446
|
+
concurrency: opts.concurrency,
|
|
3447
|
+
timeout: opts.defaultTimeout,
|
|
3448
|
+
// We dispatch to WorkerPoolManager ourselves — the queue's
|
|
3449
|
+
// internal-worker-pool path would double-up.
|
|
3450
|
+
useWorkerPool: false
|
|
3451
|
+
});
|
|
3452
|
+
this.poolManager = getWorkerPoolManager();
|
|
3453
|
+
}
|
|
3454
|
+
/**
|
|
3455
|
+
* Submit a task and await its result. Throws on failure / cancellation.
|
|
3456
|
+
*
|
|
3457
|
+
* @param workerType — routing key. Maps to a named `WorkerPoolManager` pool.
|
|
3458
|
+
* @param methodName — function name exposed by the worker module.
|
|
3459
|
+
* @param args — positional arguments passed to the worker function.
|
|
3460
|
+
*/
|
|
3461
|
+
async submit(workerType, methodName, args, opts = {}) {
|
|
3462
|
+
const handle = this.submitWithHandle(workerType, methodName, args, opts);
|
|
3463
|
+
return handle.result;
|
|
3464
|
+
}
|
|
3465
|
+
/**
|
|
3466
|
+
* Submit a task and return a handle for cancellation + status polling.
|
|
3467
|
+
*/
|
|
3468
|
+
submitWithHandle(workerType, methodName, args, opts = {}) {
|
|
3469
|
+
const id = `wtm-${Date.now()}-${++SUBMISSION_COUNTER}`;
|
|
3470
|
+
this.handleStatus.set(id, "pending" /* PENDING */);
|
|
3471
|
+
const task = {
|
|
3472
|
+
id,
|
|
3473
|
+
priority: opts.priority ?? 1 /* NORMAL */,
|
|
3474
|
+
timeout: opts.timeout,
|
|
3475
|
+
input: { workerType, methodName, args },
|
|
3476
|
+
fn: async (input) => {
|
|
3477
|
+
if (this.cancelledTaskIds.has(id)) {
|
|
3478
|
+
throw new Error(`Task ${id} cancelled before dispatch`);
|
|
3479
|
+
}
|
|
3480
|
+
this.handleStatus.set(id, "running" /* RUNNING */);
|
|
3481
|
+
const pool = this.poolManager.getPool(input.workerType, opts.poolConfig);
|
|
3482
|
+
this.touchedPoolIds.add(input.workerType);
|
|
3483
|
+
return await pool.exec(input.methodName, input.args);
|
|
3484
|
+
}
|
|
3485
|
+
};
|
|
3486
|
+
const result = this.queue.enqueue(task).then(async (res) => {
|
|
3487
|
+
this.handleStatus.set(id, res.status);
|
|
3488
|
+
if (res.status === "completed" /* COMPLETED */) {
|
|
3489
|
+
return res.result;
|
|
3490
|
+
}
|
|
3491
|
+
if (res.status === "cancelled" /* CANCELLED */ || this.cancelledTaskIds.has(id)) {
|
|
3492
|
+
throw new Error(`Task ${id} cancelled`);
|
|
3493
|
+
}
|
|
3494
|
+
const err2 = res.error ?? new Error(`Task ${id} failed: ${res.status}`);
|
|
3495
|
+
throw err2;
|
|
3496
|
+
});
|
|
3497
|
+
return {
|
|
3498
|
+
id,
|
|
3499
|
+
result,
|
|
3500
|
+
cancel: () => {
|
|
3501
|
+
this.cancelledTaskIds.add(id);
|
|
3502
|
+
const evicted = this.queue.cancel(id);
|
|
3503
|
+
if (evicted) {
|
|
3504
|
+
this.handleStatus.set(id, "cancelled" /* CANCELLED */);
|
|
3505
|
+
}
|
|
3506
|
+
return evicted;
|
|
3507
|
+
},
|
|
3508
|
+
status: () => this.handleStatus.get(id) ?? "pending" /* PENDING */
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
/**
|
|
3512
|
+
* Aggregated stats across the queue + touched pools.
|
|
3513
|
+
*/
|
|
3514
|
+
getStats() {
|
|
3515
|
+
const pools = [];
|
|
3516
|
+
for (const poolId of this.touchedPoolIds) {
|
|
3517
|
+
const stats = this.poolManager.getPoolStats(poolId);
|
|
3518
|
+
if (stats) {
|
|
3519
|
+
pools.push({
|
|
3520
|
+
poolId,
|
|
3521
|
+
workers: stats.totalWorkers,
|
|
3522
|
+
activeTasks: stats.activeTasks,
|
|
3523
|
+
pendingTasks: stats.pendingTasks,
|
|
3524
|
+
totalTasksExecuted: stats.totalTasksExecuted
|
|
3525
|
+
});
|
|
3526
|
+
}
|
|
3527
|
+
}
|
|
3528
|
+
return { queue: this.queue.getStats(), pools };
|
|
3529
|
+
}
|
|
3530
|
+
/**
|
|
3531
|
+
* Drain the queue (wait for all pending + running tasks) and return their
|
|
3532
|
+
* results in completion order. Pool workers are NOT terminated — call
|
|
3533
|
+
* `shutdown()` for that.
|
|
3534
|
+
*/
|
|
3535
|
+
async drain() {
|
|
3536
|
+
return this.queue.drain();
|
|
3537
|
+
}
|
|
3538
|
+
/**
|
|
3539
|
+
* Shut down the queue + the underlying WorkerPoolManager pools touched by
|
|
3540
|
+
* this instance. Idempotent. Returns after every owned worker has exited.
|
|
3541
|
+
*/
|
|
3542
|
+
async shutdown() {
|
|
3543
|
+
try {
|
|
3544
|
+
await this.queue.shutdown();
|
|
3545
|
+
} catch (e) {
|
|
3546
|
+
logger.warn("[WorkerTaskManager.shutdown] queue.shutdown failed:", e);
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
};
|
|
3550
|
+
DEFAULT_INSTANCE = null;
|
|
3551
|
+
}
|
|
3552
|
+
});
|
|
3553
|
+
|
|
3416
3554
|
// src/utils/BatchProcessor.ts
|
|
3417
3555
|
async function processBatch(items, processor, options = {}) {
|
|
3418
3556
|
const batchProcessor = new BatchProcessor(options);
|
|
@@ -11267,6 +11405,7 @@ var init_utils = __esm({
|
|
|
11267
11405
|
init_taskScheduler();
|
|
11268
11406
|
init_operationUtils();
|
|
11269
11407
|
init_WorkerPoolManager();
|
|
11408
|
+
init_WorkerTaskManager();
|
|
11270
11409
|
init_BatchProcessor();
|
|
11271
11410
|
init_MemoryMonitor();
|
|
11272
11411
|
init_relationHelpers();
|
|
@@ -20623,6 +20762,431 @@ var ObservationStore = class _ObservationStore {
|
|
|
20623
20762
|
|
|
20624
20763
|
// src/core/StorageFactory.ts
|
|
20625
20764
|
init_esm_shims();
|
|
20765
|
+
|
|
20766
|
+
// src/core/PostgreSQLStorage.ts
|
|
20767
|
+
init_esm_shims();
|
|
20768
|
+
init_logger();
|
|
20769
|
+
var ENTITY_COLUMNS = [
|
|
20770
|
+
"name",
|
|
20771
|
+
"entity_type",
|
|
20772
|
+
"observations",
|
|
20773
|
+
"parent_id",
|
|
20774
|
+
"tags",
|
|
20775
|
+
"importance",
|
|
20776
|
+
"created_at",
|
|
20777
|
+
"last_modified",
|
|
20778
|
+
"ttl",
|
|
20779
|
+
"confidence",
|
|
20780
|
+
"project_id",
|
|
20781
|
+
"version",
|
|
20782
|
+
"parent_entity_name",
|
|
20783
|
+
"root_entity_name",
|
|
20784
|
+
"is_latest",
|
|
20785
|
+
"superseded_by",
|
|
20786
|
+
"content_hash",
|
|
20787
|
+
"valid_from",
|
|
20788
|
+
"valid_until",
|
|
20789
|
+
"observation_meta",
|
|
20790
|
+
"lifecycle_status",
|
|
20791
|
+
"extra"
|
|
20792
|
+
];
|
|
20793
|
+
var FIRST_CLASS_ENTITY_KEYS = /* @__PURE__ */ new Set([
|
|
20794
|
+
"name",
|
|
20795
|
+
"entityType",
|
|
20796
|
+
"observations",
|
|
20797
|
+
"parentId",
|
|
20798
|
+
"tags",
|
|
20799
|
+
"importance",
|
|
20800
|
+
"createdAt",
|
|
20801
|
+
"lastModified",
|
|
20802
|
+
"ttl",
|
|
20803
|
+
"confidence",
|
|
20804
|
+
"projectId",
|
|
20805
|
+
"version",
|
|
20806
|
+
"parentEntityName",
|
|
20807
|
+
"rootEntityName",
|
|
20808
|
+
"isLatest",
|
|
20809
|
+
"supersededBy",
|
|
20810
|
+
"contentHash",
|
|
20811
|
+
"validFrom",
|
|
20812
|
+
"validUntil",
|
|
20813
|
+
"observationMeta",
|
|
20814
|
+
"lifecycleStatus"
|
|
20815
|
+
]);
|
|
20816
|
+
var SCHEMA_DDL = `
|
|
20817
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
20818
|
+
name TEXT PRIMARY KEY,
|
|
20819
|
+
entity_type TEXT NOT NULL,
|
|
20820
|
+
observations TEXT[] NOT NULL DEFAULT '{}',
|
|
20821
|
+
parent_id TEXT,
|
|
20822
|
+
tags TEXT[],
|
|
20823
|
+
importance NUMERIC(4, 2),
|
|
20824
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
20825
|
+
last_modified TIMESTAMPTZ DEFAULT NOW(),
|
|
20826
|
+
ttl INTEGER,
|
|
20827
|
+
confidence NUMERIC(4, 3),
|
|
20828
|
+
project_id TEXT,
|
|
20829
|
+
version INTEGER,
|
|
20830
|
+
parent_entity_name TEXT,
|
|
20831
|
+
root_entity_name TEXT,
|
|
20832
|
+
is_latest BOOLEAN,
|
|
20833
|
+
superseded_by TEXT,
|
|
20834
|
+
content_hash TEXT,
|
|
20835
|
+
valid_from TIMESTAMPTZ,
|
|
20836
|
+
valid_until TIMESTAMPTZ,
|
|
20837
|
+
observation_meta JSONB,
|
|
20838
|
+
lifecycle_status TEXT,
|
|
20839
|
+
extra JSONB
|
|
20840
|
+
);
|
|
20841
|
+
|
|
20842
|
+
CREATE INDEX IF NOT EXISTS idx_entities_entity_type ON entities(entity_type);
|
|
20843
|
+
CREATE INDEX IF NOT EXISTS idx_entities_project_id ON entities(project_id);
|
|
20844
|
+
CREATE INDEX IF NOT EXISTS idx_entities_content_hash ON entities(content_hash);
|
|
20845
|
+
CREATE INDEX IF NOT EXISTS idx_entities_tags_gin ON entities USING GIN(tags);
|
|
20846
|
+
|
|
20847
|
+
CREATE TABLE IF NOT EXISTS relations (
|
|
20848
|
+
from_name TEXT NOT NULL,
|
|
20849
|
+
to_name TEXT NOT NULL,
|
|
20850
|
+
relation_type TEXT NOT NULL,
|
|
20851
|
+
metadata JSONB,
|
|
20852
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
20853
|
+
valid_from TIMESTAMPTZ,
|
|
20854
|
+
valid_until TIMESTAMPTZ,
|
|
20855
|
+
PRIMARY KEY (from_name, to_name, relation_type)
|
|
20856
|
+
);
|
|
20857
|
+
|
|
20858
|
+
CREATE INDEX IF NOT EXISTS idx_relations_to ON relations(to_name);
|
|
20859
|
+
CREATE INDEX IF NOT EXISTS idx_relations_type ON relations(relation_type);
|
|
20860
|
+
`;
|
|
20861
|
+
var PostgreSQLStorage = class {
|
|
20862
|
+
connectionString;
|
|
20863
|
+
pool = null;
|
|
20864
|
+
cache = null;
|
|
20865
|
+
nameIndex = /* @__PURE__ */ new Map();
|
|
20866
|
+
outgoingRelations = /* @__PURE__ */ new Map();
|
|
20867
|
+
incomingRelations = /* @__PURE__ */ new Map();
|
|
20868
|
+
pendingAppends = 0;
|
|
20869
|
+
schemaInitPromise = null;
|
|
20870
|
+
constructor(connectionString) {
|
|
20871
|
+
this.connectionString = connectionString;
|
|
20872
|
+
}
|
|
20873
|
+
// ==================== Connection management ====================
|
|
20874
|
+
/**
|
|
20875
|
+
* Get or lazily-construct the `pg.Pool`. Throws a friendly error if
|
|
20876
|
+
* the `pg` package isn't installed.
|
|
20877
|
+
*/
|
|
20878
|
+
async getPool() {
|
|
20879
|
+
if (this.pool) return this.pool;
|
|
20880
|
+
let pgModule;
|
|
20881
|
+
try {
|
|
20882
|
+
pgModule = await import("pg");
|
|
20883
|
+
} catch {
|
|
20884
|
+
throw new Error(
|
|
20885
|
+
"The 'pg' package is required for the PostgreSQL backend but is not installed. Run: npm install pg @types/pg"
|
|
20886
|
+
);
|
|
20887
|
+
}
|
|
20888
|
+
this.pool = new pgModule.Pool({ connectionString: this.connectionString });
|
|
20889
|
+
return this.pool;
|
|
20890
|
+
}
|
|
20891
|
+
/**
|
|
20892
|
+
* Run schema DDL idempotently. Called from `ensureLoaded`.
|
|
20893
|
+
*/
|
|
20894
|
+
async initSchema() {
|
|
20895
|
+
if (this.schemaInitPromise) return this.schemaInitPromise;
|
|
20896
|
+
this.schemaInitPromise = (async () => {
|
|
20897
|
+
const pool = await this.getPool();
|
|
20898
|
+
await pool.query(SCHEMA_DDL);
|
|
20899
|
+
})();
|
|
20900
|
+
return this.schemaInitPromise;
|
|
20901
|
+
}
|
|
20902
|
+
// ==================== Row ⇄ Entity / Relation mapping ====================
|
|
20903
|
+
entityToRow(entity) {
|
|
20904
|
+
const extra = {};
|
|
20905
|
+
for (const key of Object.keys(entity)) {
|
|
20906
|
+
if (!FIRST_CLASS_ENTITY_KEYS.has(key)) {
|
|
20907
|
+
extra[key] = entity[key];
|
|
20908
|
+
}
|
|
20909
|
+
}
|
|
20910
|
+
return {
|
|
20911
|
+
name: entity.name,
|
|
20912
|
+
entity_type: entity.entityType,
|
|
20913
|
+
observations: entity.observations,
|
|
20914
|
+
parent_id: entity.parentId ?? null,
|
|
20915
|
+
tags: entity.tags ?? null,
|
|
20916
|
+
importance: entity.importance ?? null,
|
|
20917
|
+
created_at: entity.createdAt ?? null,
|
|
20918
|
+
last_modified: entity.lastModified ?? null,
|
|
20919
|
+
ttl: entity.ttl ?? null,
|
|
20920
|
+
confidence: entity.confidence ?? null,
|
|
20921
|
+
project_id: entity.projectId ?? null,
|
|
20922
|
+
version: entity.version ?? null,
|
|
20923
|
+
parent_entity_name: entity.parentEntityName ?? null,
|
|
20924
|
+
root_entity_name: entity.rootEntityName ?? null,
|
|
20925
|
+
is_latest: entity.isLatest ?? null,
|
|
20926
|
+
superseded_by: entity.supersededBy ?? null,
|
|
20927
|
+
content_hash: entity.contentHash ?? null,
|
|
20928
|
+
valid_from: entity.validFrom ?? null,
|
|
20929
|
+
valid_until: entity.validUntil ?? null,
|
|
20930
|
+
observation_meta: entity.observationMeta ?? null,
|
|
20931
|
+
lifecycle_status: entity.lifecycleStatus ?? null,
|
|
20932
|
+
extra: Object.keys(extra).length > 0 ? extra : null
|
|
20933
|
+
};
|
|
20934
|
+
}
|
|
20935
|
+
rowToEntity(row) {
|
|
20936
|
+
const entity = {
|
|
20937
|
+
name: String(row.name),
|
|
20938
|
+
entityType: String(row.entity_type),
|
|
20939
|
+
observations: Array.isArray(row.observations) ? row.observations : []
|
|
20940
|
+
};
|
|
20941
|
+
if (row.parent_id != null) entity.parentId = String(row.parent_id);
|
|
20942
|
+
if (Array.isArray(row.tags)) entity.tags = row.tags;
|
|
20943
|
+
if (row.importance != null) entity.importance = Number(row.importance);
|
|
20944
|
+
if (row.created_at != null) entity.createdAt = new Date(String(row.created_at)).toISOString();
|
|
20945
|
+
if (row.last_modified != null) entity.lastModified = new Date(String(row.last_modified)).toISOString();
|
|
20946
|
+
if (row.ttl != null) entity.ttl = Number(row.ttl);
|
|
20947
|
+
if (row.confidence != null) entity.confidence = Number(row.confidence);
|
|
20948
|
+
if (row.project_id != null) entity.projectId = String(row.project_id);
|
|
20949
|
+
if (row.version != null) entity.version = Number(row.version);
|
|
20950
|
+
if (row.parent_entity_name != null) entity.parentEntityName = String(row.parent_entity_name);
|
|
20951
|
+
if (row.root_entity_name != null) entity.rootEntityName = String(row.root_entity_name);
|
|
20952
|
+
if (row.is_latest != null) entity.isLatest = Boolean(row.is_latest);
|
|
20953
|
+
if (row.superseded_by != null) entity.supersededBy = String(row.superseded_by);
|
|
20954
|
+
if (row.content_hash != null) entity.contentHash = String(row.content_hash);
|
|
20955
|
+
if (row.valid_from != null) entity.validFrom = new Date(String(row.valid_from)).toISOString();
|
|
20956
|
+
if (row.valid_until != null) entity.validUntil = new Date(String(row.valid_until)).toISOString();
|
|
20957
|
+
if (row.observation_meta != null) {
|
|
20958
|
+
entity.observationMeta = row.observation_meta;
|
|
20959
|
+
}
|
|
20960
|
+
if (row.lifecycle_status != null) {
|
|
20961
|
+
entity.lifecycleStatus = String(row.lifecycle_status);
|
|
20962
|
+
}
|
|
20963
|
+
if (row.extra != null && typeof row.extra === "object") {
|
|
20964
|
+
Object.assign(entity, row.extra);
|
|
20965
|
+
}
|
|
20966
|
+
return entity;
|
|
20967
|
+
}
|
|
20968
|
+
rowToRelation(row) {
|
|
20969
|
+
const relation = {
|
|
20970
|
+
from: String(row.from_name),
|
|
20971
|
+
to: String(row.to_name),
|
|
20972
|
+
relationType: String(row.relation_type)
|
|
20973
|
+
};
|
|
20974
|
+
return relation;
|
|
20975
|
+
}
|
|
20976
|
+
// ==================== Cache management ====================
|
|
20977
|
+
rebuildIndexes(graph) {
|
|
20978
|
+
this.nameIndex.clear();
|
|
20979
|
+
this.outgoingRelations.clear();
|
|
20980
|
+
this.incomingRelations.clear();
|
|
20981
|
+
for (const e of graph.entities) this.nameIndex.set(e.name, e);
|
|
20982
|
+
for (const r of graph.relations) {
|
|
20983
|
+
const outArr = this.outgoingRelations.get(r.from) ?? [];
|
|
20984
|
+
outArr.push(r);
|
|
20985
|
+
this.outgoingRelations.set(r.from, outArr);
|
|
20986
|
+
const inArr = this.incomingRelations.get(r.to) ?? [];
|
|
20987
|
+
inArr.push(r);
|
|
20988
|
+
this.incomingRelations.set(r.to, inArr);
|
|
20989
|
+
}
|
|
20990
|
+
}
|
|
20991
|
+
// ==================== IGraphStorage — read ====================
|
|
20992
|
+
async loadGraph() {
|
|
20993
|
+
await this.ensureLoaded();
|
|
20994
|
+
return this.cache;
|
|
20995
|
+
}
|
|
20996
|
+
async getGraphForMutation() {
|
|
20997
|
+
await this.ensureLoaded();
|
|
20998
|
+
const cache = this.cache;
|
|
20999
|
+
return {
|
|
21000
|
+
entities: cache.entities.map((e) => ({
|
|
21001
|
+
...e,
|
|
21002
|
+
observations: [...e.observations],
|
|
21003
|
+
tags: e.tags ? [...e.tags] : void 0
|
|
21004
|
+
})),
|
|
21005
|
+
relations: cache.relations.map((r) => ({ ...r }))
|
|
21006
|
+
};
|
|
21007
|
+
}
|
|
21008
|
+
async ensureLoaded() {
|
|
21009
|
+
if (this.cache) return;
|
|
21010
|
+
await this.initSchema();
|
|
21011
|
+
const pool = await this.getPool();
|
|
21012
|
+
const [eRes, rRes] = await Promise.all([
|
|
21013
|
+
pool.query("SELECT * FROM entities"),
|
|
21014
|
+
pool.query("SELECT * FROM relations")
|
|
21015
|
+
]);
|
|
21016
|
+
const graph = {
|
|
21017
|
+
entities: eRes.rows.map((r) => this.rowToEntity(r)),
|
|
21018
|
+
relations: rRes.rows.map((r) => this.rowToRelation(r))
|
|
21019
|
+
};
|
|
21020
|
+
this.cache = graph;
|
|
21021
|
+
this.rebuildIndexes(graph);
|
|
21022
|
+
}
|
|
21023
|
+
get cachedGraph() {
|
|
21024
|
+
return this.cache;
|
|
21025
|
+
}
|
|
21026
|
+
// ==================== IGraphStorage — write ====================
|
|
21027
|
+
async saveGraph(graph) {
|
|
21028
|
+
await this.initSchema();
|
|
21029
|
+
const pool = await this.getPool();
|
|
21030
|
+
await pool.query("TRUNCATE entities, relations");
|
|
21031
|
+
for (const entity of graph.entities) {
|
|
21032
|
+
await this.insertEntityRow(pool, entity);
|
|
21033
|
+
}
|
|
21034
|
+
for (const relation of graph.relations) {
|
|
21035
|
+
await this.insertRelationRow(pool, relation);
|
|
21036
|
+
}
|
|
21037
|
+
this.cache = {
|
|
21038
|
+
entities: graph.entities.map((e) => ({ ...e })),
|
|
21039
|
+
relations: graph.relations.map((r) => ({ ...r }))
|
|
21040
|
+
};
|
|
21041
|
+
this.rebuildIndexes(this.cache);
|
|
21042
|
+
this.pendingAppends = 0;
|
|
21043
|
+
}
|
|
21044
|
+
async insertEntityRow(pool, entity) {
|
|
21045
|
+
const row = this.entityToRow(entity);
|
|
21046
|
+
const cols = ENTITY_COLUMNS.join(", ");
|
|
21047
|
+
const placeholders = ENTITY_COLUMNS.map((_, i) => `$${i + 1}`).join(", ");
|
|
21048
|
+
const values = ENTITY_COLUMNS.map((c) => row[c]);
|
|
21049
|
+
await pool.query(
|
|
21050
|
+
`INSERT INTO entities (${cols}) VALUES (${placeholders})
|
|
21051
|
+
ON CONFLICT (name) DO UPDATE SET ${ENTITY_COLUMNS.filter((c) => c !== "name").map((c) => `${c} = EXCLUDED.${c}`).join(", ")}`,
|
|
21052
|
+
values
|
|
21053
|
+
);
|
|
21054
|
+
}
|
|
21055
|
+
async insertRelationRow(pool, relation) {
|
|
21056
|
+
await pool.query(
|
|
21057
|
+
`INSERT INTO relations (from_name, to_name, relation_type)
|
|
21058
|
+
VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
|
|
21059
|
+
[relation.from, relation.to, relation.relationType]
|
|
21060
|
+
);
|
|
21061
|
+
}
|
|
21062
|
+
async appendEntity(entity) {
|
|
21063
|
+
await this.ensureLoaded();
|
|
21064
|
+
const pool = await this.getPool();
|
|
21065
|
+
await this.insertEntityRow(pool, entity);
|
|
21066
|
+
if (!this.cache) return;
|
|
21067
|
+
const existingIdx = this.cache.entities.findIndex((e) => e.name === entity.name);
|
|
21068
|
+
if (existingIdx >= 0) this.cache.entities[existingIdx] = entity;
|
|
21069
|
+
else this.cache.entities.push(entity);
|
|
21070
|
+
this.nameIndex.set(entity.name, entity);
|
|
21071
|
+
this.pendingAppends += 1;
|
|
21072
|
+
}
|
|
21073
|
+
async appendRelation(relation) {
|
|
21074
|
+
await this.ensureLoaded();
|
|
21075
|
+
const pool = await this.getPool();
|
|
21076
|
+
await this.insertRelationRow(pool, relation);
|
|
21077
|
+
if (!this.cache) return;
|
|
21078
|
+
const duplicate = this.cache.relations.some(
|
|
21079
|
+
(r) => r.from === relation.from && r.to === relation.to && r.relationType === relation.relationType
|
|
21080
|
+
);
|
|
21081
|
+
if (!duplicate) {
|
|
21082
|
+
this.cache.relations.push(relation);
|
|
21083
|
+
const outArr = this.outgoingRelations.get(relation.from) ?? [];
|
|
21084
|
+
outArr.push(relation);
|
|
21085
|
+
this.outgoingRelations.set(relation.from, outArr);
|
|
21086
|
+
const inArr = this.incomingRelations.get(relation.to) ?? [];
|
|
21087
|
+
inArr.push(relation);
|
|
21088
|
+
this.incomingRelations.set(relation.to, inArr);
|
|
21089
|
+
}
|
|
21090
|
+
this.pendingAppends += 1;
|
|
21091
|
+
}
|
|
21092
|
+
async updateEntity(entityName, updates) {
|
|
21093
|
+
await this.ensureLoaded();
|
|
21094
|
+
const existing = this.nameIndex.get(entityName);
|
|
21095
|
+
if (!existing) return false;
|
|
21096
|
+
const merged = {
|
|
21097
|
+
...existing,
|
|
21098
|
+
...updates,
|
|
21099
|
+
name: entityName,
|
|
21100
|
+
lastModified: updates.lastModified ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
21101
|
+
};
|
|
21102
|
+
const pool = await this.getPool();
|
|
21103
|
+
await this.insertEntityRow(pool, merged);
|
|
21104
|
+
if (this.cache) {
|
|
21105
|
+
const idx = this.cache.entities.findIndex((e) => e.name === entityName);
|
|
21106
|
+
if (idx >= 0) this.cache.entities[idx] = merged;
|
|
21107
|
+
}
|
|
21108
|
+
this.nameIndex.set(entityName, merged);
|
|
21109
|
+
this.pendingAppends += 1;
|
|
21110
|
+
return true;
|
|
21111
|
+
}
|
|
21112
|
+
async compact() {
|
|
21113
|
+
if (this.cache) await this.saveGraph(this.cache);
|
|
21114
|
+
}
|
|
21115
|
+
clearCache() {
|
|
21116
|
+
this.cache = null;
|
|
21117
|
+
this.nameIndex.clear();
|
|
21118
|
+
this.outgoingRelations.clear();
|
|
21119
|
+
this.incomingRelations.clear();
|
|
21120
|
+
this.pendingAppends = 0;
|
|
21121
|
+
}
|
|
21122
|
+
// ==================== IGraphStorage — sync getters ====================
|
|
21123
|
+
getEntityByName(name) {
|
|
21124
|
+
return this.nameIndex.get(name);
|
|
21125
|
+
}
|
|
21126
|
+
hasEntity(name) {
|
|
21127
|
+
return this.nameIndex.has(name);
|
|
21128
|
+
}
|
|
21129
|
+
getEntitiesByType(entityType) {
|
|
21130
|
+
const result = [];
|
|
21131
|
+
for (const entity of this.nameIndex.values()) {
|
|
21132
|
+
if (entity.entityType === entityType) result.push(entity);
|
|
21133
|
+
}
|
|
21134
|
+
return result;
|
|
21135
|
+
}
|
|
21136
|
+
getEntityTypes() {
|
|
21137
|
+
const types = /* @__PURE__ */ new Set();
|
|
21138
|
+
for (const entity of this.nameIndex.values()) types.add(entity.entityType);
|
|
21139
|
+
return Array.from(types);
|
|
21140
|
+
}
|
|
21141
|
+
getLowercased(entityName) {
|
|
21142
|
+
const e = this.nameIndex.get(entityName);
|
|
21143
|
+
if (!e) return void 0;
|
|
21144
|
+
return {
|
|
21145
|
+
name: e.name.toLowerCase(),
|
|
21146
|
+
entityType: e.entityType.toLowerCase(),
|
|
21147
|
+
observations: e.observations.map((o) => o.toLowerCase()),
|
|
21148
|
+
tags: e.tags?.map((t) => t.toLowerCase()) ?? []
|
|
21149
|
+
};
|
|
21150
|
+
}
|
|
21151
|
+
getRelationsFrom(entityName) {
|
|
21152
|
+
return this.outgoingRelations.get(entityName) ?? [];
|
|
21153
|
+
}
|
|
21154
|
+
getRelationsTo(entityName) {
|
|
21155
|
+
return this.incomingRelations.get(entityName) ?? [];
|
|
21156
|
+
}
|
|
21157
|
+
getRelationsFor(entityName) {
|
|
21158
|
+
return [
|
|
21159
|
+
...this.outgoingRelations.get(entityName) ?? [],
|
|
21160
|
+
...this.incomingRelations.get(entityName) ?? []
|
|
21161
|
+
];
|
|
21162
|
+
}
|
|
21163
|
+
hasRelations(entityName) {
|
|
21164
|
+
return (this.outgoingRelations.get(entityName)?.length ?? 0) + (this.incomingRelations.get(entityName)?.length ?? 0) > 0;
|
|
21165
|
+
}
|
|
21166
|
+
// ==================== Utility ====================
|
|
21167
|
+
getFilePath() {
|
|
21168
|
+
return this.connectionString;
|
|
21169
|
+
}
|
|
21170
|
+
getPendingAppends() {
|
|
21171
|
+
return this.pendingAppends;
|
|
21172
|
+
}
|
|
21173
|
+
/**
|
|
21174
|
+
* Close the underlying `pg.Pool`. Call from process-shutdown handlers to
|
|
21175
|
+
* avoid keeping the event loop alive on idle connections.
|
|
21176
|
+
*/
|
|
21177
|
+
async close() {
|
|
21178
|
+
if (this.pool) {
|
|
21179
|
+
try {
|
|
21180
|
+
await this.pool.end();
|
|
21181
|
+
} catch (e) {
|
|
21182
|
+
logger.warn("PostgreSQLStorage.close: pool.end failed:", e);
|
|
21183
|
+
}
|
|
21184
|
+
this.pool = null;
|
|
21185
|
+
}
|
|
21186
|
+
}
|
|
21187
|
+
};
|
|
21188
|
+
|
|
21189
|
+
// src/core/StorageFactory.ts
|
|
20626
21190
|
var DEFAULT_STORAGE_TYPE = "jsonl";
|
|
20627
21191
|
function createStorage(config) {
|
|
20628
21192
|
const storageType = process.env.MEMORY_STORAGE_TYPE || config.type || DEFAULT_STORAGE_TYPE;
|
|
@@ -20631,9 +21195,12 @@ function createStorage(config) {
|
|
|
20631
21195
|
return new GraphStorage(config.path);
|
|
20632
21196
|
case "sqlite":
|
|
20633
21197
|
return new SQLiteStorage(config.path);
|
|
21198
|
+
case "postgres":
|
|
21199
|
+
case "postgresql":
|
|
21200
|
+
return new PostgreSQLStorage(config.path);
|
|
20634
21201
|
default:
|
|
20635
21202
|
throw new Error(
|
|
20636
|
-
`Unknown storage type: ${storageType}. Supported types: jsonl, sqlite`
|
|
21203
|
+
`Unknown storage type: ${storageType}. Supported types: jsonl, sqlite, postgres`
|
|
20637
21204
|
);
|
|
20638
21205
|
}
|
|
20639
21206
|
}
|
|
@@ -51333,6 +51900,7 @@ export {
|
|
|
51333
51900
|
VisibilityResolver,
|
|
51334
51901
|
WorkThreadManager,
|
|
51335
51902
|
WorkerPoolManager,
|
|
51903
|
+
WorkerTaskManager,
|
|
51336
51904
|
WorkingMemoryManager,
|
|
51337
51905
|
WorldModelManager,
|
|
51338
51906
|
WorldStateSnapshot,
|
|
@@ -51342,6 +51910,7 @@ export {
|
|
|
51342
51910
|
applyPagination,
|
|
51343
51911
|
asWarning,
|
|
51344
51912
|
batchProcess,
|
|
51913
|
+
batchProcessViaWorkers,
|
|
51345
51914
|
buildTFVector,
|
|
51346
51915
|
calculateIDF,
|
|
51347
51916
|
calculateIDFFromTokenSets,
|
|
@@ -51412,6 +51981,7 @@ export {
|
|
|
51412
51981
|
getQuickHint,
|
|
51413
51982
|
getRoleProfile,
|
|
51414
51983
|
getWorkerPoolManager,
|
|
51984
|
+
getWorkerTaskManager,
|
|
51415
51985
|
globalMemoryMonitor,
|
|
51416
51986
|
groupEntitiesByType,
|
|
51417
51987
|
hasAllTags,
|