@unrdf/knowledge-engine 5.0.1 → 26.4.3

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.
Files changed (71) hide show
  1. package/package.json +13 -7
  2. package/src/ai-enhanced-search.mjs +371 -0
  3. package/src/anomaly-detector.mjs +226 -0
  4. package/src/artifact-generator.mjs +251 -0
  5. package/src/browser.mjs +1 -1
  6. package/src/chatman/disruption-arithmetic.mjs +140 -0
  7. package/src/chatman/market-dynamics.mjs +140 -0
  8. package/src/chatman/organizational-dynamics.mjs +140 -0
  9. package/src/chatman/strategic-dynamics.mjs +140 -0
  10. package/src/chatman-config-loader.mjs +282 -0
  11. package/src/chatman-engine.mjs +431 -0
  12. package/src/chatman-operator.mjs +342 -0
  13. package/src/dark-field-detector.mjs +312 -0
  14. package/src/formation-theorems.mjs +345 -0
  15. package/src/index.mjs +20 -2
  16. package/src/knowledge-hook-manager.mjs +1 -1
  17. package/src/lockchain-writer-browser.mjs +2 -2
  18. package/src/observability.mjs +40 -4
  19. package/src/query-optimizer.mjs +1 -1
  20. package/src/resolution-layer.mjs +1 -1
  21. package/src/transaction.mjs +11 -9
  22. package/README.md +0 -84
  23. package/src/browser-shims.mjs +0 -343
  24. package/src/canonicalize.mjs +0 -414
  25. package/src/condition-cache.mjs +0 -109
  26. package/src/condition-evaluator.mjs +0 -722
  27. package/src/dark-matter-core.mjs +0 -742
  28. package/src/define-hook.mjs +0 -213
  29. package/src/effect-sandbox-browser.mjs +0 -283
  30. package/src/effect-sandbox-worker.mjs +0 -170
  31. package/src/effect-sandbox.mjs +0 -517
  32. package/src/engines/index.mjs +0 -11
  33. package/src/engines/rdf-engine.mjs +0 -299
  34. package/src/file-resolver.mjs +0 -387
  35. package/src/hook-executor-batching.mjs +0 -277
  36. package/src/hook-executor.mjs +0 -870
  37. package/src/hook-management.mjs +0 -150
  38. package/src/ken-parliment.mjs +0 -119
  39. package/src/ken.mjs +0 -149
  40. package/src/knowledge-engine/builtin-rules.mjs +0 -190
  41. package/src/knowledge-engine/inference-engine.mjs +0 -418
  42. package/src/knowledge-engine/knowledge-engine.mjs +0 -317
  43. package/src/knowledge-engine/pattern-dsl.mjs +0 -142
  44. package/src/knowledge-engine/pattern-matcher.mjs +0 -215
  45. package/src/knowledge-engine/rules.mjs +0 -184
  46. package/src/knowledge-engine.mjs +0 -319
  47. package/src/knowledge-hook-engine.mjs +0 -360
  48. package/src/knowledge-substrate-core.mjs +0 -927
  49. package/src/lite.mjs +0 -222
  50. package/src/lockchain-writer.mjs +0 -602
  51. package/src/monitoring/andon-signals.mjs +0 -775
  52. package/src/parse.mjs +0 -290
  53. package/src/performance-optimizer.mjs +0 -678
  54. package/src/policy-pack.mjs +0 -572
  55. package/src/query-cache.mjs +0 -116
  56. package/src/query.mjs +0 -306
  57. package/src/reason.mjs +0 -350
  58. package/src/schemas.mjs +0 -1063
  59. package/src/security/error-sanitizer.mjs +0 -257
  60. package/src/security/path-validator.mjs +0 -194
  61. package/src/security/sandbox-restrictions.mjs +0 -331
  62. package/src/security-validator.mjs +0 -389
  63. package/src/store-cache.mjs +0 -137
  64. package/src/telemetry.mjs +0 -167
  65. package/src/utils/adaptive-monitor.mjs +0 -746
  66. package/src/utils/circuit-breaker.mjs +0 -513
  67. package/src/utils/edge-case-handler.mjs +0 -503
  68. package/src/utils/memory-manager.mjs +0 -498
  69. package/src/utils/ring-buffer.mjs +0 -282
  70. package/src/validate.mjs +0 -319
  71. package/src/validators/index.mjs +0 -338
@@ -1,498 +0,0 @@
1
- /**
2
- * @file Memory Manager for preventing heap OOM
3
- * @module memory-manager
4
- *
5
- * @description
6
- * Provides WeakMap/WeakSet-based memory management, connection pooling,
7
- * and automatic cleanup to prevent circular references and memory leaks.
8
- */
9
-
10
- import { EventEmitter } from 'node:events';
11
-
12
- /**
13
- * Memory Manager - Prevents circular references and unbounded growth
14
- */
15
- export class MemoryManager {
16
- /**
17
- *
18
- */
19
- constructor(config = {}) {
20
- this.config = {
21
- maxArraySize: config.maxArraySize || 1000,
22
- maxMapSize: config.maxMapSize || 10000,
23
- enableGCHints: config.enableGCHints !== false,
24
- gcInterval: config.gcInterval || 60000, // 1 minute
25
- memoryThreshold: config.memoryThreshold || 0.8, // 80% of heap
26
- ...config,
27
- };
28
-
29
- // Use WeakMap for circular reference prevention
30
- this.weakRefs = new WeakMap();
31
- this.weakSets = new WeakSet();
32
-
33
- // Track managed resources
34
- this.managedArrays = new Set();
35
- this.managedMaps = new Set();
36
- this.managedEmitters = new Set();
37
-
38
- // Cleanup registry for finalization
39
- this.cleanupRegistry = new FinalizationRegistry(this._finalize.bind(this));
40
-
41
- // Memory monitoring
42
- this.memoryStats = {
43
- arraysManaged: 0,
44
- mapsManaged: 0,
45
- emittersManaged: 0,
46
- gcRuns: 0,
47
- lastGC: null,
48
- };
49
-
50
- // Start memory monitoring
51
- if (this.config.enableGCHints) {
52
- this._startMonitoring();
53
- }
54
- }
55
-
56
- /**
57
- * Create a managed array with automatic size limiting
58
- * @param {Array} [initial=[]] - Initial array
59
- * @returns {Proxy} Managed array proxy
60
- */
61
- createManagedArray(initial = []) {
62
- const manager = this;
63
- const arr = [...initial];
64
- this.managedArrays.add(arr);
65
- this.memoryStats.arraysManaged++;
66
-
67
- return new Proxy(arr, {
68
- set(target, prop, value) {
69
- // Limit array size
70
- if (prop === 'length' || !isNaN(prop)) {
71
- if (target.length >= manager.config.maxArraySize) {
72
- // Remove oldest entries (FIFO)
73
- target.splice(0, Math.floor(manager.config.maxArraySize * 0.2));
74
- }
75
- }
76
- target[prop] = value;
77
- return true;
78
- },
79
- });
80
- }
81
-
82
- /**
83
- * Create a managed Map with automatic size limiting
84
- * @param {Map} [initial=new Map()] - Initial map
85
- * @returns {Proxy} Managed map proxy
86
- */
87
- createManagedMap(initial = new Map()) {
88
- const manager = this;
89
- const map = new Map(initial);
90
- this.managedMaps.add(map);
91
- this.memoryStats.mapsManaged++;
92
-
93
- return new Proxy(map, {
94
- get(target, prop) {
95
- if (prop === 'set') {
96
- return function (key, value) {
97
- // Check size limit
98
- if (target.size >= manager.config.maxMapSize && !target.has(key)) {
99
- // Remove oldest entry (first entry)
100
- const firstKey = target.keys().next().value;
101
- target.delete(firstKey);
102
- }
103
- return target.set(key, value);
104
- };
105
- }
106
- return target[prop];
107
- },
108
- });
109
- }
110
-
111
- /**
112
- * Register an EventEmitter for cleanup tracking
113
- * @param {EventEmitter} emitter - Event emitter
114
- * @returns {EventEmitter} Tracked emitter
115
- */
116
- trackEmitter(emitter) {
117
- if (!(emitter instanceof EventEmitter)) {
118
- throw new TypeError('Expected EventEmitter instance');
119
- }
120
-
121
- this.managedEmitters.add(emitter);
122
- this.memoryStats.emittersManaged++;
123
- this.cleanupRegistry.register(emitter, {
124
- type: 'emitter',
125
- id: Symbol('emitter'),
126
- });
127
-
128
- return emitter;
129
- }
130
-
131
- /**
132
- * Create a WeakRef wrapper for preventing circular references
133
- * @param {Object} obj - Object to wrap
134
- * @returns {WeakRef} Weak reference
135
- */
136
- createWeakRef(obj) {
137
- if (typeof obj !== 'object' || obj === null) {
138
- throw new TypeError('WeakRef requires an object');
139
- }
140
-
141
- const ref = new WeakRef(obj);
142
- this.cleanupRegistry.register(obj, {
143
- type: 'weakref',
144
- id: Symbol('weakref'),
145
- });
146
-
147
- return ref;
148
- }
149
-
150
- /**
151
- * Store data with weak reference (prevents circular refs)
152
- * @param {Object} key - Key object
153
- * @param {*} value - Value to store
154
- */
155
- setWeak(key, value) {
156
- this.weakRefs.set(key, value);
157
- }
158
-
159
- /**
160
- * Get data from weak reference
161
- * @param {Object} key - Key object
162
- * @returns {*} Stored value or undefined
163
- */
164
- getWeak(key) {
165
- return this.weakRefs.get(key);
166
- }
167
-
168
- /**
169
- * Add to weak set
170
- * @param {Object} obj - Object to add
171
- */
172
- addWeak(obj) {
173
- this.weakSets.add(obj);
174
- }
175
-
176
- /**
177
- * Check if weak set has object
178
- * @param {Object} obj - Object to check
179
- * @returns {boolean} Has object
180
- */
181
- hasWeak(obj) {
182
- return this.weakSets.has(obj);
183
- }
184
-
185
- /**
186
- * Manual cleanup trigger
187
- */
188
- cleanup() {
189
- // Clear managed arrays
190
- for (const arr of this.managedArrays) {
191
- arr.length = 0;
192
- }
193
- this.managedArrays.clear();
194
-
195
- // Clear managed maps
196
- for (const map of this.managedMaps) {
197
- map.clear();
198
- }
199
- this.managedMaps.clear();
200
-
201
- // Remove all listeners from emitters
202
- for (const emitter of this.managedEmitters) {
203
- emitter.removeAllListeners();
204
- }
205
- this.managedEmitters.clear();
206
-
207
- // Reset stats
208
- this.memoryStats.arraysManaged = 0;
209
- this.memoryStats.mapsManaged = 0;
210
- this.memoryStats.emittersManaged = 0;
211
-
212
- // Hint GC
213
- if (this.config.enableGCHints && global.gc) {
214
- global.gc();
215
- this.memoryStats.gcRuns++;
216
- this.memoryStats.lastGC = Date.now();
217
- }
218
- }
219
-
220
- /**
221
- * Get memory stats
222
- * @returns {Object} Memory statistics
223
- */
224
- getStats() {
225
- const heapUsed = process.memoryUsage().heapUsed;
226
- const heapTotal = process.memoryUsage().heapTotal;
227
-
228
- return {
229
- ...this.memoryStats,
230
- heapUsed,
231
- heapTotal,
232
- heapUsedMB: Math.round(heapUsed / 1024 / 1024),
233
- heapTotalMB: Math.round(heapTotal / 1024 / 1024),
234
- heapUtilization: heapUsed / heapTotal,
235
- timestamp: Date.now(),
236
- };
237
- }
238
-
239
- /**
240
- * Start memory monitoring
241
- * @private
242
- */
243
- _startMonitoring() {
244
- this._monitoringInterval = setInterval(() => {
245
- const stats = this.getStats();
246
-
247
- // Trigger GC if heap usage is above threshold
248
- if (stats.heapUtilization > this.config.memoryThreshold) {
249
- console.warn(
250
- `[MemoryManager] Heap usage ${(stats.heapUtilization * 100).toFixed(1)}% exceeds threshold ${(this.config.memoryThreshold * 100).toFixed(1)}%`
251
- );
252
-
253
- if (global.gc) {
254
- global.gc();
255
- this.memoryStats.gcRuns++;
256
- this.memoryStats.lastGC = Date.now();
257
- }
258
- }
259
- }, this.config.gcInterval);
260
-
261
- // Don't block process exit
262
- this._monitoringInterval.unref();
263
- }
264
-
265
- /**
266
- * Stop memory monitoring
267
- */
268
- stopMonitoring() {
269
- if (this._monitoringInterval) {
270
- clearInterval(this._monitoringInterval);
271
- this._monitoringInterval = null;
272
- }
273
- }
274
-
275
- /**
276
- * Finalization callback
277
- * @private
278
- */
279
- _finalize(_heldValue) {
280
- // Object was garbage collected
281
- // Nothing to do - cleanup already happened
282
- }
283
-
284
- /**
285
- * Destroy memory manager
286
- */
287
- destroy() {
288
- this.stopMonitoring();
289
- this.cleanup();
290
- }
291
- }
292
-
293
- /**
294
- * Connection Pool Manager
295
- * Prevents connection leaks and manages resource limits
296
- */
297
- export class ConnectionPool {
298
- /**
299
- *
300
- */
301
- constructor(config = {}) {
302
- this.config = {
303
- maxConnections: config.maxConnections || 10,
304
- minConnections: config.minConnections || 2,
305
- acquireTimeout: config.acquireTimeout || 5000,
306
- idleTimeout: config.idleTimeout || 30000,
307
- createConnection: config.createConnection || (() => Promise.resolve({})),
308
- destroyConnection: config.destroyConnection || (() => Promise.resolve()),
309
- validateConnection: config.validateConnection || (() => true),
310
- ...config,
311
- };
312
-
313
- this.available = [];
314
- this.inUse = new Set();
315
- this.total = 0;
316
- this.pendingAcquires = [];
317
-
318
- // Stats
319
- this.stats = {
320
- acquired: 0,
321
- released: 0,
322
- created: 0,
323
- destroyed: 0,
324
- timeouts: 0,
325
- errors: 0,
326
- };
327
- }
328
-
329
- /**
330
- * Initialize pool
331
- */
332
- async initialize() {
333
- for (let i = 0; i < this.config.minConnections; i++) {
334
- const conn = await this._createConnection();
335
- this.available.push(conn);
336
- }
337
- }
338
-
339
- /**
340
- * Acquire a connection from the pool
341
- * @returns {Promise<Object>} Connection
342
- */
343
- async acquire() {
344
- // Try to get from available
345
- if (this.available.length > 0) {
346
- const conn = this.available.pop();
347
-
348
- // Validate connection
349
- if (this.config.validateConnection(conn)) {
350
- this.inUse.add(conn);
351
- this.stats.acquired++;
352
- return conn;
353
- } else {
354
- // Connection is stale, destroy and create new
355
- await this._destroyConnection(conn);
356
- return this.acquire();
357
- }
358
- }
359
-
360
- // Create new if under limit
361
- if (this.total < this.config.maxConnections) {
362
- const conn = await this._createConnection();
363
- this.inUse.add(conn);
364
- this.stats.acquired++;
365
- return conn;
366
- }
367
-
368
- // Wait for connection to be released
369
- return new Promise((resolve, reject) => {
370
- const timeoutId = setTimeout(() => {
371
- const idx = this.pendingAcquires.findIndex(p => p.resolve === resolve);
372
- if (idx !== -1) {
373
- this.pendingAcquires.splice(idx, 1);
374
- }
375
- this.stats.timeouts++;
376
- reject(new Error('Connection acquire timeout'));
377
- }, this.config.acquireTimeout);
378
-
379
- this.pendingAcquires.push({ resolve, reject, timeoutId });
380
- });
381
- }
382
-
383
- /**
384
- * Release a connection back to the pool
385
- * @param {Object} conn - Connection to release
386
- */
387
- release(conn) {
388
- if (!this.inUse.has(conn)) {
389
- return;
390
- }
391
-
392
- this.inUse.delete(conn);
393
- this.stats.released++;
394
-
395
- // Give to pending acquire if any
396
- if (this.pendingAcquires.length > 0) {
397
- const { resolve, timeoutId } = this.pendingAcquires.shift();
398
- clearTimeout(timeoutId);
399
- this.inUse.add(conn);
400
- this.stats.acquired++;
401
- resolve(conn);
402
- return;
403
- }
404
-
405
- // Return to pool
406
- this.available.push(conn);
407
- }
408
-
409
- /**
410
- * Drain the pool (release all connections)
411
- */
412
- async drain() {
413
- // Wait for all in-use connections to be released
414
- while (this.inUse.size > 0) {
415
- await new Promise(resolve => setTimeout(resolve, 100));
416
- }
417
-
418
- // Destroy all available connections
419
- for (const conn of this.available) {
420
- await this._destroyConnection(conn);
421
- }
422
-
423
- this.available = [];
424
- this.total = 0;
425
- }
426
-
427
- /**
428
- * Create a new connection
429
- * @private
430
- */
431
- async _createConnection() {
432
- try {
433
- const conn = await this.config.createConnection();
434
- this.total++;
435
- this.stats.created++;
436
- return conn;
437
- } catch (error) {
438
- this.stats.errors++;
439
- throw error;
440
- }
441
- }
442
-
443
- /**
444
- * Destroy a connection
445
- * @private
446
- */
447
- async _destroyConnection(conn) {
448
- try {
449
- await this.config.destroyConnection(conn);
450
- this.total--;
451
- this.stats.destroyed++;
452
- } catch (error) {
453
- this.stats.errors++;
454
- }
455
- }
456
-
457
- /**
458
- * Get pool stats
459
- * @returns {Object} Pool statistics
460
- */
461
- getStats() {
462
- return {
463
- ...this.stats,
464
- available: this.available.length,
465
- inUse: this.inUse.size,
466
- total: this.total,
467
- pending: this.pendingAcquires.length,
468
- };
469
- }
470
- }
471
-
472
- /**
473
- * Global memory manager instance
474
- */
475
- export const globalMemoryManager = new MemoryManager({
476
- maxArraySize: 1000,
477
- maxMapSize: 10000,
478
- enableGCHints: true,
479
- gcInterval: 60000,
480
- });
481
-
482
- /**
483
- * Create a memory manager instance
484
- * @param {Object} [config] - Configuration
485
- * @returns {MemoryManager} Memory manager
486
- */
487
- export function createMemoryManager(config = {}) {
488
- return new MemoryManager(config);
489
- }
490
-
491
- /**
492
- * Create a connection pool instance
493
- * @param {Object} [config] - Configuration
494
- * @returns {ConnectionPool} Connection pool
495
- */
496
- export function createConnectionPool(config = {}) {
497
- return new ConnectionPool(config);
498
- }