ruvector 0.1.62 → 0.1.63

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.
@@ -202,13 +202,112 @@ export declare function isAttentionAvailable(): boolean;
202
202
  * Get attention module version
203
203
  */
204
204
  export declare function getAttentionVersion(): string | null;
205
+ /**
206
+ * Graph attention with Rotary Position Embeddings
207
+ * Excellent for code AST and dependency graphs
208
+ */
209
+ export declare class GraphRoPeAttention {
210
+ private inner;
211
+ readonly dim: number;
212
+ readonly numHeads: number;
213
+ readonly maxSeqLen: number;
214
+ constructor(dim: number, numHeads?: number, maxSeqLen?: number);
215
+ compute(query: number[] | Float32Array, keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[], positions?: number[]): AttentionOutput;
216
+ }
217
+ /**
218
+ * Edge-featured attention for graphs with edge attributes
219
+ * Useful for weighted dependency graphs
220
+ */
221
+ export declare class EdgeFeaturedAttention {
222
+ private inner;
223
+ readonly dim: number;
224
+ readonly edgeDim: number;
225
+ constructor(dim: number, edgeDim?: number);
226
+ compute(query: number[] | Float32Array, keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[], edgeFeatures?: (number[] | Float32Array)[]): AttentionOutput;
227
+ }
228
+ /**
229
+ * Dual-space attention (Euclidean + Hyperbolic)
230
+ * Best of both worlds for hierarchical + semantic similarity
231
+ */
232
+ export declare class DualSpaceAttention {
233
+ private inner;
234
+ readonly dim: number;
235
+ readonly curvature: number;
236
+ readonly alpha: number;
237
+ constructor(dim: number, curvature?: number, alpha?: number);
238
+ compute(query: number[] | Float32Array, keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[]): AttentionOutput;
239
+ }
240
+ /**
241
+ * Basic dot-product attention
242
+ */
243
+ export declare class DotProductAttention {
244
+ private inner;
245
+ readonly dim: number;
246
+ constructor(dim: number);
247
+ compute(query: number[] | Float32Array, keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[]): AttentionOutput;
248
+ }
249
+ /**
250
+ * Compute attention in parallel across multiple queries
251
+ */
252
+ export declare function parallelAttentionCompute(queries: (number[] | Float32Array)[], keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[], attentionType?: 'dot' | 'multi-head' | 'flash' | 'hyperbolic' | 'linear'): Promise<number[][]>;
253
+ /**
254
+ * Batch attention compute for multiple query-key-value sets
255
+ */
256
+ export declare function batchAttentionCompute(batches: Array<{
257
+ query: number[] | Float32Array;
258
+ keys: (number[] | Float32Array)[];
259
+ values: (number[] | Float32Array)[];
260
+ }>, attentionType?: 'dot' | 'multi-head' | 'flash' | 'hyperbolic' | 'linear'): Promise<number[][]>;
261
+ /**
262
+ * Async flash attention with callback
263
+ */
264
+ export declare function computeFlashAttentionAsync(query: number[] | Float32Array, keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[]): Promise<number[]>;
265
+ /**
266
+ * Async hyperbolic attention
267
+ */
268
+ export declare function computeHyperbolicAttentionAsync(query: number[] | Float32Array, keys: (number[] | Float32Array)[], values: (number[] | Float32Array)[], curvature?: number): Promise<number[]>;
269
+ /**
270
+ * Adam optimizer for attention training
271
+ */
272
+ export declare class AdamOptimizer {
273
+ private inner;
274
+ constructor(learningRate?: number, beta1?: number, beta2?: number);
275
+ step(gradients: number[] | Float32Array, params: number[] | Float32Array): number[];
276
+ }
277
+ /**
278
+ * InfoNCE contrastive loss
279
+ */
280
+ export declare function infoNceLoss(anchor: number[] | Float32Array, positive: number[] | Float32Array, negatives: (number[] | Float32Array)[], temperature?: number): number;
281
+ /**
282
+ * Hard negative mining for contrastive learning
283
+ */
284
+ export declare function mineHardNegatives(anchor: number[] | Float32Array, candidates: (number[] | Float32Array)[], topK?: number): number[][];
285
+ /**
286
+ * Benchmark attention implementations
287
+ */
288
+ export declare function benchmarkAttention(dim: number, seqLen: number, iterations?: number): Promise<Record<string, {
289
+ avgMs: number;
290
+ minMs: number;
291
+ maxMs: number;
292
+ }>>;
205
293
  declare const _default: {
294
+ DotProductAttention: typeof DotProductAttention;
206
295
  MultiHeadAttention: typeof MultiHeadAttention;
207
296
  FlashAttention: typeof FlashAttention;
208
297
  HyperbolicAttention: typeof HyperbolicAttention;
209
298
  LinearAttention: typeof LinearAttention;
210
299
  LocalGlobalAttention: typeof LocalGlobalAttention;
211
300
  MoEAttention: typeof MoEAttention;
301
+ GraphRoPeAttention: typeof GraphRoPeAttention;
302
+ EdgeFeaturedAttention: typeof EdgeFeaturedAttention;
303
+ DualSpaceAttention: typeof DualSpaceAttention;
304
+ parallelAttentionCompute: typeof parallelAttentionCompute;
305
+ batchAttentionCompute: typeof batchAttentionCompute;
306
+ computeFlashAttentionAsync: typeof computeFlashAttentionAsync;
307
+ computeHyperbolicAttentionAsync: typeof computeHyperbolicAttentionAsync;
308
+ AdamOptimizer: typeof AdamOptimizer;
309
+ infoNceLoss: typeof infoNceLoss;
310
+ mineHardNegatives: typeof mineHardNegatives;
212
311
  projectToPoincareBall: typeof projectToPoincareBall;
213
312
  poincareDistance: typeof poincareDistance;
214
313
  mobiusAddition: typeof mobiusAddition;
@@ -216,6 +315,7 @@ declare const _default: {
216
315
  logMap: typeof logMap;
217
316
  isAttentionAvailable: typeof isAttentionAvailable;
218
317
  getAttentionVersion: typeof getAttentionVersion;
318
+ benchmarkAttention: typeof benchmarkAttention;
219
319
  };
220
320
  export default _default;
221
321
  //# sourceMappingURL=attention-fallbacks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"attention-fallbacks.d.ts","sourceRoot":"","sources":["../../src/core/attention-fallbacks.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA8CH;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,qCAAqC;IACrC,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,2DAA2D;IAC3D,GAAG,EAAE,YAAY,CAAC;CACnB;AAED;;;;GAIG;AACH,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,KAAK,CAAM;IACnB,SAAgB,GAAG,EAAE,MAAM,CAAC;IAC5B,SAAgB,QAAQ,EAAE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AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,EAAE,GAAG,YAAY,EAC/B,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,YAAY,CAAC,EAAE,EACvC,IAAI,GAAE,MAAU,GACf,MAAM,EAAE,EAAE,CAKZ;AAMD;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,UAAU,GAAE,MAAY,GACvB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAG1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAED,wBAqCE"}
@@ -9,7 +9,7 @@
9
9
  * This wrapper handles the conversion automatically.
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.MoEAttention = exports.LocalGlobalAttention = exports.LinearAttention = exports.HyperbolicAttention = exports.FlashAttention = exports.MultiHeadAttention = void 0;
12
+ exports.AdamOptimizer = exports.DotProductAttention = exports.DualSpaceAttention = exports.EdgeFeaturedAttention = exports.GraphRoPeAttention = exports.MoEAttention = exports.LocalGlobalAttention = exports.LinearAttention = exports.HyperbolicAttention = exports.FlashAttention = exports.MultiHeadAttention = void 0;
13
13
  exports.projectToPoincareBall = projectToPoincareBall;
14
14
  exports.poincareDistance = poincareDistance;
15
15
  exports.mobiusAddition = mobiusAddition;
@@ -17,6 +17,13 @@ exports.expMap = expMap;
17
17
  exports.logMap = logMap;
18
18
  exports.isAttentionAvailable = isAttentionAvailable;
19
19
  exports.getAttentionVersion = getAttentionVersion;
20
+ exports.parallelAttentionCompute = parallelAttentionCompute;
21
+ exports.batchAttentionCompute = batchAttentionCompute;
22
+ exports.computeFlashAttentionAsync = computeFlashAttentionAsync;
23
+ exports.computeHyperbolicAttentionAsync = computeHyperbolicAttentionAsync;
24
+ exports.infoNceLoss = infoNceLoss;
25
+ exports.mineHardNegatives = mineHardNegatives;
26
+ exports.benchmarkAttention = benchmarkAttention;
20
27
  // Lazy load to avoid import errors if not installed
21
28
  let attentionModule = null;
22
29
  let loadError = null;
@@ -344,18 +351,202 @@ function getAttentionVersion() {
344
351
  return null;
345
352
  }
346
353
  }
354
+ // ============================================================================
355
+ // Graph-based Attention (for code structure)
356
+ // ============================================================================
357
+ /**
358
+ * Graph attention with Rotary Position Embeddings
359
+ * Excellent for code AST and dependency graphs
360
+ */
361
+ class GraphRoPeAttention {
362
+ constructor(dim, numHeads = 4, maxSeqLen = 4096) {
363
+ const attention = getAttentionModule();
364
+ this.inner = new attention.GraphRoPeAttention(dim, numHeads, maxSeqLen);
365
+ this.dim = dim;
366
+ this.numHeads = numHeads;
367
+ this.maxSeqLen = maxSeqLen;
368
+ }
369
+ compute(query, keys, values, positions) {
370
+ const raw = this.inner.compute(toFloat32Array(query), toFloat32Arrays(keys), toFloat32Arrays(values), positions ? new Int32Array(positions) : undefined);
371
+ return { values: fromFloat32Array(raw), raw };
372
+ }
373
+ }
374
+ exports.GraphRoPeAttention = GraphRoPeAttention;
375
+ /**
376
+ * Edge-featured attention for graphs with edge attributes
377
+ * Useful for weighted dependency graphs
378
+ */
379
+ class EdgeFeaturedAttention {
380
+ constructor(dim, edgeDim = 16) {
381
+ const attention = getAttentionModule();
382
+ this.inner = new attention.EdgeFeaturedAttention(dim, edgeDim);
383
+ this.dim = dim;
384
+ this.edgeDim = edgeDim;
385
+ }
386
+ compute(query, keys, values, edgeFeatures) {
387
+ const raw = this.inner.compute(toFloat32Array(query), toFloat32Arrays(keys), toFloat32Arrays(values), edgeFeatures ? toFloat32Arrays(edgeFeatures) : undefined);
388
+ return { values: fromFloat32Array(raw), raw };
389
+ }
390
+ }
391
+ exports.EdgeFeaturedAttention = EdgeFeaturedAttention;
392
+ /**
393
+ * Dual-space attention (Euclidean + Hyperbolic)
394
+ * Best of both worlds for hierarchical + semantic similarity
395
+ */
396
+ class DualSpaceAttention {
397
+ constructor(dim, curvature = 1.0, alpha = 0.5) {
398
+ const attention = getAttentionModule();
399
+ this.inner = new attention.DualSpaceAttention(dim, curvature, alpha);
400
+ this.dim = dim;
401
+ this.curvature = curvature;
402
+ this.alpha = alpha;
403
+ }
404
+ compute(query, keys, values) {
405
+ const raw = this.inner.compute(toFloat32Array(query), toFloat32Arrays(keys), toFloat32Arrays(values));
406
+ return { values: fromFloat32Array(raw), raw };
407
+ }
408
+ }
409
+ exports.DualSpaceAttention = DualSpaceAttention;
410
+ /**
411
+ * Basic dot-product attention
412
+ */
413
+ class DotProductAttention {
414
+ constructor(dim) {
415
+ const attention = getAttentionModule();
416
+ this.inner = new attention.DotProductAttention(dim);
417
+ this.dim = dim;
418
+ }
419
+ compute(query, keys, values) {
420
+ const raw = this.inner.compute(toFloat32Array(query), toFloat32Arrays(keys), toFloat32Arrays(values));
421
+ return { values: fromFloat32Array(raw), raw };
422
+ }
423
+ }
424
+ exports.DotProductAttention = DotProductAttention;
425
+ // ============================================================================
426
+ // Parallel/Batch Attention Compute
427
+ // ============================================================================
428
+ /**
429
+ * Compute attention in parallel across multiple queries
430
+ */
431
+ async function parallelAttentionCompute(queries, keys, values, attentionType = 'multi-head') {
432
+ const attention = getAttentionModule();
433
+ const results = await attention.parallelAttentionCompute(toFloat32Arrays(queries), toFloat32Arrays(keys), toFloat32Arrays(values), attentionType);
434
+ return results.map((r) => fromFloat32Array(r));
435
+ }
436
+ /**
437
+ * Batch attention compute for multiple query-key-value sets
438
+ */
439
+ async function batchAttentionCompute(batches, attentionType = 'multi-head') {
440
+ const attention = getAttentionModule();
441
+ const nativeBatches = batches.map(b => ({
442
+ query: toFloat32Array(b.query),
443
+ keys: toFloat32Arrays(b.keys),
444
+ values: toFloat32Arrays(b.values),
445
+ }));
446
+ const results = await attention.batchAttentionCompute(nativeBatches, attentionType);
447
+ return results.map((r) => fromFloat32Array(r));
448
+ }
449
+ /**
450
+ * Async flash attention with callback
451
+ */
452
+ function computeFlashAttentionAsync(query, keys, values) {
453
+ const attention = getAttentionModule();
454
+ return new Promise((resolve, reject) => {
455
+ attention.computeFlashAttentionAsync(toFloat32Array(query), toFloat32Arrays(keys), toFloat32Arrays(values), (err, result) => {
456
+ if (err)
457
+ reject(err);
458
+ else
459
+ resolve(fromFloat32Array(result));
460
+ });
461
+ });
462
+ }
463
+ /**
464
+ * Async hyperbolic attention
465
+ */
466
+ function computeHyperbolicAttentionAsync(query, keys, values, curvature = 1.0) {
467
+ const attention = getAttentionModule();
468
+ return new Promise((resolve, reject) => {
469
+ attention.computeHyperbolicAttentionAsync(toFloat32Array(query), toFloat32Arrays(keys), toFloat32Arrays(values), curvature, (err, result) => {
470
+ if (err)
471
+ reject(err);
472
+ else
473
+ resolve(fromFloat32Array(result));
474
+ });
475
+ });
476
+ }
477
+ // ============================================================================
478
+ // Training Utilities (for SONA integration)
479
+ // ============================================================================
480
+ /**
481
+ * Adam optimizer for attention training
482
+ */
483
+ class AdamOptimizer {
484
+ constructor(learningRate = 0.001, beta1 = 0.9, beta2 = 0.999) {
485
+ const attention = getAttentionModule();
486
+ this.inner = new attention.AdamOptimizer(learningRate, beta1, beta2);
487
+ }
488
+ step(gradients, params) {
489
+ const result = this.inner.step(toFloat32Array(gradients), toFloat32Array(params));
490
+ return fromFloat32Array(result);
491
+ }
492
+ }
493
+ exports.AdamOptimizer = AdamOptimizer;
494
+ /**
495
+ * InfoNCE contrastive loss
496
+ */
497
+ function infoNceLoss(anchor, positive, negatives, temperature = 0.07) {
498
+ const attention = getAttentionModule();
499
+ return attention.InfoNceLoss.compute(toFloat32Array(anchor), toFloat32Array(positive), toFloat32Arrays(negatives), temperature);
500
+ }
501
+ /**
502
+ * Hard negative mining for contrastive learning
503
+ */
504
+ function mineHardNegatives(anchor, candidates, topK = 5) {
505
+ const attention = getAttentionModule();
506
+ const miner = new attention.HardNegativeMiner(topK);
507
+ const results = miner.mine(toFloat32Array(anchor), toFloat32Arrays(candidates));
508
+ return results.map((r) => fromFloat32Array(r));
509
+ }
510
+ // ============================================================================
511
+ // Benchmarking
512
+ // ============================================================================
513
+ /**
514
+ * Benchmark attention implementations
515
+ */
516
+ async function benchmarkAttention(dim, seqLen, iterations = 100) {
517
+ const attention = getAttentionModule();
518
+ return attention.benchmarkAttention(dim, seqLen, iterations);
519
+ }
347
520
  exports.default = {
521
+ // Core attention types
522
+ DotProductAttention,
348
523
  MultiHeadAttention,
349
524
  FlashAttention,
350
525
  HyperbolicAttention,
351
526
  LinearAttention,
352
527
  LocalGlobalAttention,
353
528
  MoEAttention,
529
+ // Graph attention types
530
+ GraphRoPeAttention,
531
+ EdgeFeaturedAttention,
532
+ DualSpaceAttention,
533
+ // Parallel/batch compute
534
+ parallelAttentionCompute,
535
+ batchAttentionCompute,
536
+ computeFlashAttentionAsync,
537
+ computeHyperbolicAttentionAsync,
538
+ // Training utilities
539
+ AdamOptimizer,
540
+ infoNceLoss,
541
+ mineHardNegatives,
542
+ // Hyperbolic math
354
543
  projectToPoincareBall,
355
544
  poincareDistance,
356
545
  mobiusAddition,
357
546
  expMap,
358
547
  logMap,
548
+ // Utilities
359
549
  isAttentionAvailable,
360
550
  getAttentionVersion,
551
+ benchmarkAttention,
361
552
  };
@@ -11,6 +11,7 @@ export * from './sona-wrapper';
11
11
  export * from './intelligence-engine';
12
12
  export * from './onnx-embedder';
13
13
  export * from './parallel-intelligence';
14
+ export * from './parallel-workers';
14
15
  export { default as gnnWrapper } from './gnn-wrapper';
15
16
  export { default as attentionFallbacks } from './attention-fallbacks';
16
17
  export { default as agentdbFast } from './agentdb-fast';
@@ -18,4 +19,5 @@ export { default as Sona } from './sona-wrapper';
18
19
  export { default as IntelligenceEngine } from './intelligence-engine';
19
20
  export { default as OnnxEmbedder } from './onnx-embedder';
20
21
  export { default as ParallelIntelligence } from './parallel-intelligence';
22
+ export { default as ExtendedWorkerPool } from './parallel-workers';
21
23
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AAGxC,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AACxC,cAAc,oBAAoB,CAAC;AAGnC,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -23,7 +23,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
23
23
  return (mod && mod.__esModule) ? mod : { "default": mod };
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.ParallelIntelligence = exports.OnnxEmbedder = exports.IntelligenceEngine = exports.Sona = exports.agentdbFast = exports.attentionFallbacks = exports.gnnWrapper = void 0;
26
+ exports.ExtendedWorkerPool = exports.ParallelIntelligence = exports.OnnxEmbedder = exports.IntelligenceEngine = exports.Sona = exports.agentdbFast = exports.attentionFallbacks = exports.gnnWrapper = void 0;
27
27
  __exportStar(require("./gnn-wrapper"), exports);
28
28
  __exportStar(require("./attention-fallbacks"), exports);
29
29
  __exportStar(require("./agentdb-fast"), exports);
@@ -31,6 +31,7 @@ __exportStar(require("./sona-wrapper"), exports);
31
31
  __exportStar(require("./intelligence-engine"), exports);
32
32
  __exportStar(require("./onnx-embedder"), exports);
33
33
  __exportStar(require("./parallel-intelligence"), exports);
34
+ __exportStar(require("./parallel-workers"), exports);
34
35
  // Re-export default objects for convenience
35
36
  var gnn_wrapper_1 = require("./gnn-wrapper");
36
37
  Object.defineProperty(exports, "gnnWrapper", { enumerable: true, get: function () { return __importDefault(gnn_wrapper_1).default; } });
@@ -46,3 +47,5 @@ var onnx_embedder_1 = require("./onnx-embedder");
46
47
  Object.defineProperty(exports, "OnnxEmbedder", { enumerable: true, get: function () { return __importDefault(onnx_embedder_1).default; } });
47
48
  var parallel_intelligence_1 = require("./parallel-intelligence");
48
49
  Object.defineProperty(exports, "ParallelIntelligence", { enumerable: true, get: function () { return __importDefault(parallel_intelligence_1).default; } });
50
+ var parallel_workers_1 = require("./parallel-workers");
51
+ Object.defineProperty(exports, "ExtendedWorkerPool", { enumerable: true, get: function () { return __importDefault(parallel_workers_1).default; } });
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Parallel Workers - Extended worker capabilities for RuVector hooks
3
+ *
4
+ * Provides parallel processing for advanced operations:
5
+ *
6
+ * 1. SPECULATIVE PRE-COMPUTATION
7
+ * - Pre-embed likely next files based on co-edit patterns
8
+ * - Warm model cache before operations
9
+ * - Predictive route caching
10
+ *
11
+ * 2. REAL-TIME CODE ANALYSIS
12
+ * - Multi-file AST parsing with tree-sitter
13
+ * - Cross-file type inference
14
+ * - Live complexity metrics
15
+ * - Dependency graph updates
16
+ *
17
+ * 3. ADVANCED LEARNING
18
+ * - Distributed trajectory replay
19
+ * - Parallel SONA micro-LoRA updates
20
+ * - Background EWC consolidation
21
+ * - Online pattern clustering
22
+ *
23
+ * 4. INTELLIGENT RETRIEVAL
24
+ * - Parallel RAG chunking and retrieval
25
+ * - Sharded similarity search
26
+ * - Context relevance ranking
27
+ * - Semantic deduplication
28
+ *
29
+ * 5. SECURITY & QUALITY
30
+ * - Parallel SAST scanning
31
+ * - Multi-rule linting
32
+ * - Vulnerability detection
33
+ * - Code smell analysis
34
+ *
35
+ * 6. GIT INTELLIGENCE
36
+ * - Parallel blame analysis
37
+ * - Branch comparison
38
+ * - Merge conflict prediction
39
+ * - Code churn metrics
40
+ */
41
+ export interface WorkerPoolConfig {
42
+ numWorkers?: number;
43
+ enabled?: boolean;
44
+ taskTimeout?: number;
45
+ maxQueueSize?: number;
46
+ }
47
+ export interface SpeculativeEmbedding {
48
+ file: string;
49
+ embedding: number[];
50
+ confidence: number;
51
+ timestamp: number;
52
+ }
53
+ export interface ASTAnalysis {
54
+ file: string;
55
+ language: string;
56
+ complexity: number;
57
+ functions: string[];
58
+ imports: string[];
59
+ exports: string[];
60
+ dependencies: string[];
61
+ }
62
+ export interface SecurityFinding {
63
+ file: string;
64
+ line: number;
65
+ severity: 'low' | 'medium' | 'high' | 'critical';
66
+ rule: string;
67
+ message: string;
68
+ suggestion?: string;
69
+ }
70
+ export interface ContextChunk {
71
+ content: string;
72
+ source: string;
73
+ relevance: number;
74
+ embedding?: number[];
75
+ }
76
+ export interface GitBlame {
77
+ file: string;
78
+ lines: Array<{
79
+ line: number;
80
+ author: string;
81
+ date: string;
82
+ commit: string;
83
+ }>;
84
+ }
85
+ export interface CodeChurn {
86
+ file: string;
87
+ additions: number;
88
+ deletions: number;
89
+ commits: number;
90
+ authors: string[];
91
+ lastModified: string;
92
+ }
93
+ export declare class ExtendedWorkerPool {
94
+ private workers;
95
+ private taskQueue;
96
+ private busyWorkers;
97
+ private config;
98
+ private initialized;
99
+ private speculativeCache;
100
+ private astCache;
101
+ constructor(config?: WorkerPoolConfig);
102
+ init(): Promise<void>;
103
+ private getWorkerCode;
104
+ private getWorkerHandlers;
105
+ private handleWorkerResult;
106
+ private processQueue;
107
+ private execute;
108
+ /**
109
+ * Pre-embed files likely to be edited next based on co-edit patterns
110
+ * Hook: session-start, post-edit
111
+ */
112
+ speculativeEmbed(currentFile: string, coEditGraph: Map<string, string[]>): Promise<SpeculativeEmbedding[]>;
113
+ /**
114
+ * Analyze AST of multiple files in parallel
115
+ * Hook: pre-edit, route
116
+ */
117
+ analyzeAST(files: string[]): Promise<ASTAnalysis[]>;
118
+ /**
119
+ * Analyze code complexity for multiple files
120
+ * Hook: post-edit, session-end
121
+ */
122
+ analyzeComplexity(files: string[]): Promise<Array<{
123
+ file: string;
124
+ lines: number;
125
+ nonEmptyLines: number;
126
+ cyclomaticComplexity: number;
127
+ functions: number;
128
+ avgFunctionSize: number;
129
+ }>>;
130
+ /**
131
+ * Build dependency graph from entry points
132
+ * Hook: session-start
133
+ */
134
+ buildDependencyGraph(entryPoints: string[]): Promise<Record<string, string[]>>;
135
+ /**
136
+ * Scan files for security vulnerabilities
137
+ * Hook: pre-command (before commit), post-edit
138
+ */
139
+ securityScan(files: string[], rules?: string[]): Promise<SecurityFinding[]>;
140
+ /**
141
+ * Retrieve relevant context chunks in parallel
142
+ * Hook: suggest-context, recall
143
+ */
144
+ ragRetrieve(query: string, chunks: ContextChunk[], topK?: number): Promise<ContextChunk[]>;
145
+ /**
146
+ * Rank context items by relevance to query
147
+ * Hook: suggest-context
148
+ */
149
+ rankContext(context: string[], query: string): Promise<Array<{
150
+ index: number;
151
+ content: string;
152
+ relevance: number;
153
+ }>>;
154
+ /**
155
+ * Deduplicate similar items
156
+ * Hook: remember, suggest-context
157
+ */
158
+ deduplicate(items: string[], threshold?: number): Promise<string[]>;
159
+ /**
160
+ * Get blame information for files in parallel
161
+ * Hook: pre-edit (for context), coedit
162
+ */
163
+ gitBlame(files: string[]): Promise<GitBlame[]>;
164
+ /**
165
+ * Analyze code churn for files
166
+ * Hook: session-start, route
167
+ */
168
+ gitChurn(files: string[], since?: string): Promise<CodeChurn[]>;
169
+ getStats(): {
170
+ enabled: boolean;
171
+ workers: number;
172
+ busy: number;
173
+ queued: number;
174
+ speculativeCacheSize: number;
175
+ astCacheSize: number;
176
+ };
177
+ clearCaches(): void;
178
+ shutdown(): Promise<void>;
179
+ }
180
+ export declare function getExtendedWorkerPool(config?: WorkerPoolConfig): ExtendedWorkerPool;
181
+ export declare function initExtendedWorkerPool(config?: WorkerPoolConfig): Promise<ExtendedWorkerPool>;
182
+ export default ExtendedWorkerPool;
183
+ //# sourceMappingURL=parallel-workers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parallel-workers.d.ts","sourceRoot":"","sources":["../../src/core/parallel-workers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAWH,MAAM,WAAW,gBAAgB;IAC/B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,WAAW,CAAC,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AC,CAInG;AAED,eAAe,kBAAkB,CAAC"}
@@ -0,0 +1,671 @@
1
+ "use strict";
2
+ /**
3
+ * Parallel Workers - Extended worker capabilities for RuVector hooks
4
+ *
5
+ * Provides parallel processing for advanced operations:
6
+ *
7
+ * 1. SPECULATIVE PRE-COMPUTATION
8
+ * - Pre-embed likely next files based on co-edit patterns
9
+ * - Warm model cache before operations
10
+ * - Predictive route caching
11
+ *
12
+ * 2. REAL-TIME CODE ANALYSIS
13
+ * - Multi-file AST parsing with tree-sitter
14
+ * - Cross-file type inference
15
+ * - Live complexity metrics
16
+ * - Dependency graph updates
17
+ *
18
+ * 3. ADVANCED LEARNING
19
+ * - Distributed trajectory replay
20
+ * - Parallel SONA micro-LoRA updates
21
+ * - Background EWC consolidation
22
+ * - Online pattern clustering
23
+ *
24
+ * 4. INTELLIGENT RETRIEVAL
25
+ * - Parallel RAG chunking and retrieval
26
+ * - Sharded similarity search
27
+ * - Context relevance ranking
28
+ * - Semantic deduplication
29
+ *
30
+ * 5. SECURITY & QUALITY
31
+ * - Parallel SAST scanning
32
+ * - Multi-rule linting
33
+ * - Vulnerability detection
34
+ * - Code smell analysis
35
+ *
36
+ * 6. GIT INTELLIGENCE
37
+ * - Parallel blame analysis
38
+ * - Branch comparison
39
+ * - Merge conflict prediction
40
+ * - Code churn metrics
41
+ */
42
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
43
+ if (k2 === undefined) k2 = k;
44
+ var desc = Object.getOwnPropertyDescriptor(m, k);
45
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
46
+ desc = { enumerable: true, get: function() { return m[k]; } };
47
+ }
48
+ Object.defineProperty(o, k2, desc);
49
+ }) : (function(o, m, k, k2) {
50
+ if (k2 === undefined) k2 = k;
51
+ o[k2] = m[k];
52
+ }));
53
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
54
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
55
+ }) : function(o, v) {
56
+ o["default"] = v;
57
+ });
58
+ var __importStar = (this && this.__importStar) || (function () {
59
+ var ownKeys = function(o) {
60
+ ownKeys = Object.getOwnPropertyNames || function (o) {
61
+ var ar = [];
62
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
63
+ return ar;
64
+ };
65
+ return ownKeys(o);
66
+ };
67
+ return function (mod) {
68
+ if (mod && mod.__esModule) return mod;
69
+ var result = {};
70
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
71
+ __setModuleDefault(result, mod);
72
+ return result;
73
+ };
74
+ })();
75
+ Object.defineProperty(exports, "__esModule", { value: true });
76
+ exports.ExtendedWorkerPool = void 0;
77
+ exports.getExtendedWorkerPool = getExtendedWorkerPool;
78
+ exports.initExtendedWorkerPool = initExtendedWorkerPool;
79
+ const worker_threads_1 = require("worker_threads");
80
+ const os = __importStar(require("os"));
81
+ // ============================================================================
82
+ // Extended Worker Pool
83
+ // ============================================================================
84
+ class ExtendedWorkerPool {
85
+ constructor(config = {}) {
86
+ this.workers = [];
87
+ this.taskQueue = [];
88
+ this.busyWorkers = new Map();
89
+ this.initialized = false;
90
+ this.speculativeCache = new Map();
91
+ this.astCache = new Map();
92
+ const isCLI = process.env.RUVECTOR_CLI === '1';
93
+ const isMCP = process.env.MCP_SERVER === '1';
94
+ this.config = {
95
+ numWorkers: config.numWorkers ?? Math.max(1, os.cpus().length - 1),
96
+ enabled: config.enabled ?? (isMCP || process.env.RUVECTOR_PARALLEL === '1'),
97
+ taskTimeout: config.taskTimeout ?? 30000,
98
+ maxQueueSize: config.maxQueueSize ?? 1000,
99
+ };
100
+ }
101
+ async init() {
102
+ if (this.initialized || !this.config.enabled)
103
+ return;
104
+ const workerCode = this.getWorkerCode();
105
+ const workerBlob = new Blob([workerCode], { type: 'application/javascript' });
106
+ for (let i = 0; i < this.config.numWorkers; i++) {
107
+ // Create worker from inline code
108
+ const worker = new worker_threads_1.Worker(`
109
+ const { parentPort, workerData } = require('worker_threads');
110
+ ${this.getWorkerHandlers()}
111
+ `, { eval: true, workerData: { workerId: i } });
112
+ worker.on('message', (result) => {
113
+ this.handleWorkerResult(worker, result);
114
+ });
115
+ worker.on('error', (err) => {
116
+ console.error(`Worker ${i} error:`, err);
117
+ this.busyWorkers.delete(worker);
118
+ this.processQueue();
119
+ });
120
+ this.workers.push(worker);
121
+ }
122
+ this.initialized = true;
123
+ }
124
+ getWorkerCode() {
125
+ return `
126
+ const { parentPort, workerData } = require('worker_threads');
127
+ ${this.getWorkerHandlers()}
128
+ `;
129
+ }
130
+ getWorkerHandlers() {
131
+ return `
132
+ parentPort.on('message', async (task) => {
133
+ try {
134
+ let result;
135
+ switch (task.type) {
136
+ case 'speculative-embed':
137
+ result = await speculativeEmbed(task.files, task.coEditGraph);
138
+ break;
139
+ case 'ast-analyze':
140
+ result = await astAnalyze(task.files);
141
+ break;
142
+ case 'security-scan':
143
+ result = await securityScan(task.files, task.rules);
144
+ break;
145
+ case 'rag-retrieve':
146
+ result = await ragRetrieve(task.query, task.chunks, task.topK);
147
+ break;
148
+ case 'context-rank':
149
+ result = await contextRank(task.context, task.query);
150
+ break;
151
+ case 'git-blame':
152
+ result = await gitBlame(task.files);
153
+ break;
154
+ case 'git-churn':
155
+ result = await gitChurn(task.files, task.since);
156
+ break;
157
+ case 'complexity-analyze':
158
+ result = await complexityAnalyze(task.files);
159
+ break;
160
+ case 'dependency-graph':
161
+ result = await dependencyGraph(task.entryPoints);
162
+ break;
163
+ case 'deduplicate':
164
+ result = await deduplicate(task.items, task.threshold);
165
+ break;
166
+ default:
167
+ throw new Error('Unknown task type: ' + task.type);
168
+ }
169
+ parentPort.postMessage({ success: true, data: result, taskId: task.taskId });
170
+ } catch (error) {
171
+ parentPort.postMessage({ success: false, error: error.message, taskId: task.taskId });
172
+ }
173
+ });
174
+
175
+ // Worker implementations
176
+ async function speculativeEmbed(files, coEditGraph) {
177
+ // Pre-compute embeddings for likely next files
178
+ return files.map(f => ({ file: f, embedding: [], confidence: 0.5 }));
179
+ }
180
+
181
+ async function astAnalyze(files) {
182
+ const fs = require('fs');
183
+ return files.map(file => {
184
+ try {
185
+ const content = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
186
+ const lines = content.split('\\n');
187
+ return {
188
+ file,
189
+ language: file.split('.').pop() || 'unknown',
190
+ complexity: Math.min(lines.length / 10, 100),
191
+ functions: extractFunctions(content),
192
+ imports: extractImports(content),
193
+ exports: extractExports(content),
194
+ dependencies: [],
195
+ };
196
+ } catch {
197
+ return { file, language: 'unknown', complexity: 0, functions: [], imports: [], exports: [], dependencies: [] };
198
+ }
199
+ });
200
+ }
201
+
202
+ function extractFunctions(content) {
203
+ const patterns = [
204
+ /function\\s+(\\w+)/g,
205
+ /const\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>/g,
206
+ /(?:async\\s+)?(?:public|private|protected)?\\s*(\\w+)\\s*\\([^)]*\\)\\s*{/g,
207
+ ];
208
+ const funcs = new Set();
209
+ for (const pattern of patterns) {
210
+ let match;
211
+ while ((match = pattern.exec(content)) !== null) {
212
+ if (match[1] && !['if', 'for', 'while', 'switch', 'catch'].includes(match[1])) {
213
+ funcs.add(match[1]);
214
+ }
215
+ }
216
+ }
217
+ return Array.from(funcs);
218
+ }
219
+
220
+ function extractImports(content) {
221
+ const imports = [];
222
+ const patterns = [
223
+ /import\\s+.*?from\\s+['"]([^'"]+)['"]/g,
224
+ /require\\s*\\(['"]([^'"]+)['"]\\)/g,
225
+ ];
226
+ for (const pattern of patterns) {
227
+ let match;
228
+ while ((match = pattern.exec(content)) !== null) {
229
+ imports.push(match[1]);
230
+ }
231
+ }
232
+ return imports;
233
+ }
234
+
235
+ function extractExports(content) {
236
+ const exports = [];
237
+ const patterns = [
238
+ /export\\s+(?:default\\s+)?(?:class|function|const|let|var)\\s+(\\w+)/g,
239
+ /module\\.exports\\s*=\\s*(\\w+)/g,
240
+ ];
241
+ for (const pattern of patterns) {
242
+ let match;
243
+ while ((match = pattern.exec(content)) !== null) {
244
+ exports.push(match[1]);
245
+ }
246
+ }
247
+ return exports;
248
+ }
249
+
250
+ async function securityScan(files, rules) {
251
+ const fs = require('fs');
252
+ const findings = [];
253
+ const securityPatterns = [
254
+ { pattern: /eval\\s*\\(/g, rule: 'no-eval', severity: 'high', message: 'Avoid eval()' },
255
+ { pattern: /innerHTML\\s*=/g, rule: 'no-inner-html', severity: 'medium', message: 'Avoid innerHTML, use textContent' },
256
+ { pattern: /password\\s*=\\s*['"][^'"]+['"]/gi, rule: 'no-hardcoded-secrets', severity: 'critical', message: 'Hardcoded password detected' },
257
+ { pattern: /api[_-]?key\\s*=\\s*['"][^'"]+['"]/gi, rule: 'no-hardcoded-secrets', severity: 'critical', message: 'Hardcoded API key detected' },
258
+ { pattern: /exec\\s*\\(/g, rule: 'no-exec', severity: 'high', message: 'Avoid exec(), use execFile or spawn' },
259
+ { pattern: /\\$\\{.*\\}/g, rule: 'template-injection', severity: 'medium', message: 'Potential template injection' },
260
+ ];
261
+
262
+ for (const file of files) {
263
+ try {
264
+ if (!fs.existsSync(file)) continue;
265
+ const content = fs.readFileSync(file, 'utf8');
266
+ const lines = content.split('\\n');
267
+
268
+ for (const { pattern, rule, severity, message } of securityPatterns) {
269
+ let match;
270
+ const regex = new RegExp(pattern.source, pattern.flags);
271
+ while ((match = regex.exec(content)) !== null) {
272
+ const lineNum = content.substring(0, match.index).split('\\n').length;
273
+ findings.push({ file, line: lineNum, severity, rule, message });
274
+ }
275
+ }
276
+ } catch {}
277
+ }
278
+ return findings;
279
+ }
280
+
281
+ async function ragRetrieve(query, chunks, topK) {
282
+ // Simple keyword-based retrieval (would use embeddings in production)
283
+ const queryTerms = query.toLowerCase().split(/\\s+/);
284
+ return chunks
285
+ .map(chunk => {
286
+ const content = chunk.content.toLowerCase();
287
+ const matches = queryTerms.filter(term => content.includes(term)).length;
288
+ return { ...chunk, relevance: matches / queryTerms.length };
289
+ })
290
+ .sort((a, b) => b.relevance - a.relevance)
291
+ .slice(0, topK);
292
+ }
293
+
294
+ async function contextRank(context, query) {
295
+ const queryTerms = query.toLowerCase().split(/\\s+/);
296
+ return context
297
+ .map((ctx, i) => {
298
+ const content = ctx.toLowerCase();
299
+ const matches = queryTerms.filter(term => content.includes(term)).length;
300
+ return { index: i, content: ctx, relevance: matches / queryTerms.length };
301
+ })
302
+ .sort((a, b) => b.relevance - a.relevance);
303
+ }
304
+
305
+ async function gitBlame(files) {
306
+ const { execSync } = require('child_process');
307
+ const results = [];
308
+ for (const file of files) {
309
+ try {
310
+ const output = execSync(\`git blame --line-porcelain "\${file}" 2>/dev/null\`, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 });
311
+ const lines = [];
312
+ let currentLine = {};
313
+ for (const line of output.split('\\n')) {
314
+ if (line.startsWith('author ')) currentLine.author = line.slice(7);
315
+ else if (line.startsWith('author-time ')) currentLine.date = new Date(parseInt(line.slice(12)) * 1000).toISOString();
316
+ else if (line.match(/^[a-f0-9]{40}/)) currentLine.commit = line.slice(0, 40);
317
+ else if (line.startsWith('\\t')) {
318
+ lines.push({ ...currentLine, line: lines.length + 1 });
319
+ currentLine = {};
320
+ }
321
+ }
322
+ results.push({ file, lines });
323
+ } catch {
324
+ results.push({ file, lines: [] });
325
+ }
326
+ }
327
+ return results;
328
+ }
329
+
330
+ async function gitChurn(files, since) {
331
+ const { execSync } = require('child_process');
332
+ const results = [];
333
+ const sinceArg = since ? \`--since="\${since}"\` : '--since="30 days ago"';
334
+
335
+ for (const file of files) {
336
+ try {
337
+ const log = execSync(\`git log \${sinceArg} --format="%H|%an|%aI" --numstat -- "\${file}" 2>/dev/null\`, { encoding: 'utf8' });
338
+ let additions = 0, deletions = 0, commits = 0;
339
+ const authors = new Set();
340
+ let lastModified = '';
341
+
342
+ for (const line of log.split('\\n')) {
343
+ if (line.includes('|')) {
344
+ const [commit, author, date] = line.split('|');
345
+ authors.add(author);
346
+ commits++;
347
+ if (!lastModified) lastModified = date;
348
+ } else if (line.match(/^\\d+\\s+\\d+/)) {
349
+ const [add, del] = line.split('\\t');
350
+ additions += parseInt(add) || 0;
351
+ deletions += parseInt(del) || 0;
352
+ }
353
+ }
354
+
355
+ results.push({ file, additions, deletions, commits, authors: Array.from(authors), lastModified });
356
+ } catch {
357
+ results.push({ file, additions: 0, deletions: 0, commits: 0, authors: [], lastModified: '' });
358
+ }
359
+ }
360
+ return results;
361
+ }
362
+
363
+ async function complexityAnalyze(files) {
364
+ const fs = require('fs');
365
+ return files.map(file => {
366
+ try {
367
+ const content = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
368
+ const lines = content.split('\\n');
369
+ const nonEmpty = lines.filter(l => l.trim()).length;
370
+ const branches = (content.match(/\\b(if|else|switch|case|for|while|catch|\\?|&&|\\|\\|)\\b/g) || []).length;
371
+ const functions = (content.match(/function|=>|\\bdef\\b|\\bfn\\b/g) || []).length;
372
+
373
+ return {
374
+ file,
375
+ lines: lines.length,
376
+ nonEmptyLines: nonEmpty,
377
+ cyclomaticComplexity: branches + 1,
378
+ functions,
379
+ avgFunctionSize: functions > 0 ? Math.round(nonEmpty / functions) : nonEmpty,
380
+ };
381
+ } catch {
382
+ return { file, lines: 0, nonEmptyLines: 0, cyclomaticComplexity: 1, functions: 0, avgFunctionSize: 0 };
383
+ }
384
+ });
385
+ }
386
+
387
+ async function dependencyGraph(entryPoints) {
388
+ const fs = require('fs');
389
+ const path = require('path');
390
+ const graph = new Map();
391
+
392
+ function analyze(file, visited = new Set()) {
393
+ if (visited.has(file)) return;
394
+ visited.add(file);
395
+
396
+ try {
397
+ if (!fs.existsSync(file)) return;
398
+ const content = fs.readFileSync(file, 'utf8');
399
+ const deps = [];
400
+
401
+ // Extract imports
402
+ const importRegex = /(?:import|require)\\s*\\(?['"]([^'"]+)['"]/g;
403
+ let match;
404
+ while ((match = importRegex.exec(content)) !== null) {
405
+ const dep = match[1];
406
+ if (dep.startsWith('.')) {
407
+ const resolved = path.resolve(path.dirname(file), dep);
408
+ deps.push(resolved);
409
+ analyze(resolved, visited);
410
+ } else {
411
+ deps.push(dep);
412
+ }
413
+ }
414
+
415
+ graph.set(file, deps);
416
+ } catch {}
417
+ }
418
+
419
+ for (const entry of entryPoints) {
420
+ analyze(entry);
421
+ }
422
+
423
+ return Object.fromEntries(graph);
424
+ }
425
+
426
+ async function deduplicate(items, threshold) {
427
+ // Simple Jaccard similarity deduplication
428
+ const unique = [];
429
+ const seen = new Set();
430
+
431
+ for (const item of items) {
432
+ const tokens = new Set(item.toLowerCase().split(/\\s+/));
433
+ let isDup = false;
434
+
435
+ for (const existing of unique) {
436
+ const existingTokens = new Set(existing.toLowerCase().split(/\\s+/));
437
+ const intersection = [...tokens].filter(t => existingTokens.has(t)).length;
438
+ const union = new Set([...tokens, ...existingTokens]).size;
439
+ const similarity = intersection / union;
440
+
441
+ if (similarity >= threshold) {
442
+ isDup = true;
443
+ break;
444
+ }
445
+ }
446
+
447
+ if (!isDup) unique.push(item);
448
+ }
449
+
450
+ return unique;
451
+ }
452
+ `;
453
+ }
454
+ handleWorkerResult(worker, result) {
455
+ this.busyWorkers.delete(worker);
456
+ // Find and resolve the corresponding task
457
+ const taskIndex = this.taskQueue.findIndex(t => t.task.taskId === result.taskId);
458
+ if (taskIndex >= 0) {
459
+ const task = this.taskQueue.splice(taskIndex, 1)[0];
460
+ clearTimeout(task.timeout);
461
+ if (result.success) {
462
+ task.resolve(result.data);
463
+ }
464
+ else {
465
+ task.reject(new Error(result.error));
466
+ }
467
+ }
468
+ this.processQueue();
469
+ }
470
+ processQueue() {
471
+ while (this.taskQueue.length > 0) {
472
+ const availableWorker = this.workers.find(w => !this.busyWorkers.has(w));
473
+ if (!availableWorker)
474
+ break;
475
+ const task = this.taskQueue[0];
476
+ this.busyWorkers.set(availableWorker, task.task.type);
477
+ availableWorker.postMessage(task.task);
478
+ }
479
+ }
480
+ async execute(task) {
481
+ if (!this.initialized || !this.config.enabled) {
482
+ throw new Error('Worker pool not initialized');
483
+ }
484
+ const taskId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
485
+ const taskWithId = { ...task, taskId };
486
+ return new Promise((resolve, reject) => {
487
+ if (this.taskQueue.length >= this.config.maxQueueSize) {
488
+ reject(new Error('Task queue full'));
489
+ return;
490
+ }
491
+ const timeout = setTimeout(() => {
492
+ const idx = this.taskQueue.findIndex(t => t.task.taskId === taskId);
493
+ if (idx >= 0) {
494
+ this.taskQueue.splice(idx, 1);
495
+ reject(new Error('Task timeout'));
496
+ }
497
+ }, this.config.taskTimeout);
498
+ const availableWorker = this.workers.find(w => !this.busyWorkers.has(w));
499
+ if (availableWorker) {
500
+ this.busyWorkers.set(availableWorker, task.type);
501
+ this.taskQueue.push({ task: taskWithId, resolve, reject, timeout });
502
+ availableWorker.postMessage(taskWithId);
503
+ }
504
+ else {
505
+ this.taskQueue.push({ task: taskWithId, resolve, reject, timeout });
506
+ }
507
+ });
508
+ }
509
+ // =========================================================================
510
+ // Public API - Speculative Pre-computation
511
+ // =========================================================================
512
+ /**
513
+ * Pre-embed files likely to be edited next based on co-edit patterns
514
+ * Hook: session-start, post-edit
515
+ */
516
+ async speculativeEmbed(currentFile, coEditGraph) {
517
+ const likelyFiles = coEditGraph.get(currentFile) || [];
518
+ if (likelyFiles.length === 0)
519
+ return [];
520
+ // Check cache first
521
+ const uncached = likelyFiles.filter(f => !this.speculativeCache.has(f));
522
+ if (uncached.length === 0) {
523
+ return likelyFiles.map(f => this.speculativeCache.get(f));
524
+ }
525
+ const results = await this.execute({
526
+ type: 'speculative-embed',
527
+ files: uncached,
528
+ coEditGraph,
529
+ });
530
+ // Update cache
531
+ for (const result of results) {
532
+ this.speculativeCache.set(result.file, result);
533
+ }
534
+ return likelyFiles.map(f => this.speculativeCache.get(f)).filter(Boolean);
535
+ }
536
+ // =========================================================================
537
+ // Public API - Code Analysis
538
+ // =========================================================================
539
+ /**
540
+ * Analyze AST of multiple files in parallel
541
+ * Hook: pre-edit, route
542
+ */
543
+ async analyzeAST(files) {
544
+ // Check cache
545
+ const uncached = files.filter(f => !this.astCache.has(f));
546
+ if (uncached.length === 0) {
547
+ return files.map(f => this.astCache.get(f));
548
+ }
549
+ const results = await this.execute({
550
+ type: 'ast-analyze',
551
+ files: uncached,
552
+ });
553
+ // Update cache
554
+ for (const result of results) {
555
+ this.astCache.set(result.file, result);
556
+ }
557
+ return files.map(f => this.astCache.get(f)).filter(Boolean);
558
+ }
559
+ /**
560
+ * Analyze code complexity for multiple files
561
+ * Hook: post-edit, session-end
562
+ */
563
+ async analyzeComplexity(files) {
564
+ return this.execute({ type: 'complexity-analyze', files });
565
+ }
566
+ /**
567
+ * Build dependency graph from entry points
568
+ * Hook: session-start
569
+ */
570
+ async buildDependencyGraph(entryPoints) {
571
+ return this.execute({ type: 'dependency-graph', entryPoints });
572
+ }
573
+ // =========================================================================
574
+ // Public API - Security
575
+ // =========================================================================
576
+ /**
577
+ * Scan files for security vulnerabilities
578
+ * Hook: pre-command (before commit), post-edit
579
+ */
580
+ async securityScan(files, rules) {
581
+ return this.execute({ type: 'security-scan', files, rules });
582
+ }
583
+ // =========================================================================
584
+ // Public API - RAG & Context
585
+ // =========================================================================
586
+ /**
587
+ * Retrieve relevant context chunks in parallel
588
+ * Hook: suggest-context, recall
589
+ */
590
+ async ragRetrieve(query, chunks, topK = 5) {
591
+ return this.execute({ type: 'rag-retrieve', query, chunks, topK });
592
+ }
593
+ /**
594
+ * Rank context items by relevance to query
595
+ * Hook: suggest-context
596
+ */
597
+ async rankContext(context, query) {
598
+ return this.execute({ type: 'context-rank', context, query });
599
+ }
600
+ /**
601
+ * Deduplicate similar items
602
+ * Hook: remember, suggest-context
603
+ */
604
+ async deduplicate(items, threshold = 0.8) {
605
+ return this.execute({ type: 'deduplicate', items, threshold });
606
+ }
607
+ // =========================================================================
608
+ // Public API - Git Intelligence
609
+ // =========================================================================
610
+ /**
611
+ * Get blame information for files in parallel
612
+ * Hook: pre-edit (for context), coedit
613
+ */
614
+ async gitBlame(files) {
615
+ return this.execute({ type: 'git-blame', files });
616
+ }
617
+ /**
618
+ * Analyze code churn for files
619
+ * Hook: session-start, route
620
+ */
621
+ async gitChurn(files, since) {
622
+ return this.execute({ type: 'git-churn', files, since });
623
+ }
624
+ // =========================================================================
625
+ // Stats & Lifecycle
626
+ // =========================================================================
627
+ getStats() {
628
+ return {
629
+ enabled: this.config.enabled,
630
+ workers: this.workers.length,
631
+ busy: this.busyWorkers.size,
632
+ queued: this.taskQueue.length,
633
+ speculativeCacheSize: this.speculativeCache.size,
634
+ astCacheSize: this.astCache.size,
635
+ };
636
+ }
637
+ clearCaches() {
638
+ this.speculativeCache.clear();
639
+ this.astCache.clear();
640
+ }
641
+ async shutdown() {
642
+ // Clear pending tasks
643
+ for (const task of this.taskQueue) {
644
+ clearTimeout(task.timeout);
645
+ task.reject(new Error('Worker pool shutting down'));
646
+ }
647
+ this.taskQueue = [];
648
+ // Terminate workers
649
+ await Promise.all(this.workers.map(w => w.terminate()));
650
+ this.workers = [];
651
+ this.busyWorkers.clear();
652
+ this.initialized = false;
653
+ }
654
+ }
655
+ exports.ExtendedWorkerPool = ExtendedWorkerPool;
656
+ // ============================================================================
657
+ // Singleton
658
+ // ============================================================================
659
+ let instance = null;
660
+ function getExtendedWorkerPool(config) {
661
+ if (!instance) {
662
+ instance = new ExtendedWorkerPool(config);
663
+ }
664
+ return instance;
665
+ }
666
+ async function initExtendedWorkerPool(config) {
667
+ const pool = getExtendedWorkerPool(config);
668
+ await pool.init();
669
+ return pool;
670
+ }
671
+ exports.default = ExtendedWorkerPool;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ruvector",
3
- "version": "0.1.62",
3
+ "version": "0.1.63",
4
4
  "description": "High-performance vector database for Node.js with automatic native/WASM fallback",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/ruvector.db CHANGED
Binary file