ruvector 0.1.50 → 0.1.52

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.
@@ -0,0 +1,822 @@
1
+ "use strict";
2
+ /**
3
+ * IntelligenceEngine - Full RuVector Intelligence Stack
4
+ *
5
+ * Integrates all RuVector capabilities for self-learning hooks:
6
+ * - VectorDB with HNSW for semantic memory (150x faster)
7
+ * - SONA for continual learning (Micro-LoRA, EWC++)
8
+ * - FastAgentDB for episode/trajectory storage
9
+ * - Attention mechanisms for pattern recognition
10
+ * - ReasoningBank for pattern clustering
11
+ *
12
+ * Replaces the simple Q-learning approach with real ML-powered intelligence.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.IntelligenceEngine = void 0;
16
+ exports.createIntelligenceEngine = createIntelligenceEngine;
17
+ exports.createHighPerformanceEngine = createHighPerformanceEngine;
18
+ exports.createLightweightEngine = createLightweightEngine;
19
+ const agentdb_fast_1 = require("./agentdb-fast");
20
+ const sona_wrapper_1 = require("./sona-wrapper");
21
+ // ============================================================================
22
+ // Lazy Loading
23
+ // ============================================================================
24
+ let VectorDB = null;
25
+ let vectorDbError = null;
26
+ function getVectorDB() {
27
+ if (VectorDB)
28
+ return VectorDB;
29
+ if (vectorDbError)
30
+ throw vectorDbError;
31
+ try {
32
+ const core = require('@ruvector/core');
33
+ VectorDB = core.VectorDb || core.VectorDB;
34
+ return VectorDB;
35
+ }
36
+ catch {
37
+ try {
38
+ const pkg = require('ruvector');
39
+ VectorDB = pkg.VectorDb || pkg.VectorDB;
40
+ return VectorDB;
41
+ }
42
+ catch (e) {
43
+ vectorDbError = new Error(`VectorDB not available: ${e.message}`);
44
+ throw vectorDbError;
45
+ }
46
+ }
47
+ }
48
+ let attentionModule = null;
49
+ let attentionError = null;
50
+ function getAttention() {
51
+ if (attentionModule)
52
+ return attentionModule;
53
+ if (attentionError)
54
+ return null; // Silently fail for optional module
55
+ try {
56
+ attentionModule = require('@ruvector/attention');
57
+ return attentionModule;
58
+ }
59
+ catch (e) {
60
+ attentionError = e;
61
+ return null;
62
+ }
63
+ }
64
+ // ============================================================================
65
+ // Intelligence Engine
66
+ // ============================================================================
67
+ /**
68
+ * Full-stack intelligence engine using all RuVector capabilities
69
+ */
70
+ class IntelligenceEngine {
71
+ constructor(config = {}) {
72
+ this.vectorDb = null;
73
+ this.sona = null;
74
+ this.attention = null;
75
+ // In-memory data structures
76
+ this.memories = new Map();
77
+ this.routingPatterns = new Map(); // state -> action -> value
78
+ this.errorPatterns = new Map(); // error -> fixes
79
+ this.coEditPatterns = new Map(); // file -> related files -> count
80
+ this.agentMappings = new Map(); // extension/dir -> agent
81
+ // Runtime state
82
+ this.currentTrajectoryId = null;
83
+ this.sessionStart = Date.now();
84
+ this.learningEnabled = true;
85
+ this.config = {
86
+ embeddingDim: config.embeddingDim ?? 256,
87
+ maxMemories: config.maxMemories ?? 100000,
88
+ maxEpisodes: config.maxEpisodes ?? 50000,
89
+ enableSona: config.enableSona ?? true,
90
+ enableAttention: config.enableAttention ?? true,
91
+ sonaConfig: config.sonaConfig ?? {},
92
+ storagePath: config.storagePath ?? '',
93
+ learningRate: config.learningRate ?? 0.1,
94
+ };
95
+ // Initialize FastAgentDB for episode storage
96
+ this.agentDb = new agentdb_fast_1.FastAgentDB(this.config.embeddingDim, this.config.maxEpisodes);
97
+ // Initialize SONA if enabled and available
98
+ if (this.config.enableSona && (0, sona_wrapper_1.isSonaAvailable)()) {
99
+ try {
100
+ this.sona = sona_wrapper_1.SonaEngine.withConfig({
101
+ hiddenDim: this.config.embeddingDim,
102
+ embeddingDim: this.config.embeddingDim,
103
+ microLoraRank: 2, // Fast adaptations
104
+ baseLoraRank: 8,
105
+ patternClusters: 100,
106
+ trajectoryCapacity: 10000,
107
+ ...this.config.sonaConfig,
108
+ });
109
+ }
110
+ catch (e) {
111
+ console.warn('SONA initialization failed, using fallback learning');
112
+ }
113
+ }
114
+ // Initialize attention if enabled
115
+ if (this.config.enableAttention) {
116
+ this.attention = getAttention();
117
+ }
118
+ // Initialize VectorDB for memory
119
+ this.initVectorDb();
120
+ }
121
+ async initVectorDb() {
122
+ try {
123
+ const VDB = getVectorDB();
124
+ this.vectorDb = new VDB({
125
+ dimensions: this.config.embeddingDim,
126
+ distanceMetric: 'Cosine',
127
+ });
128
+ }
129
+ catch {
130
+ // VectorDB not available, use fallback
131
+ }
132
+ }
133
+ // =========================================================================
134
+ // Embedding Generation
135
+ // =========================================================================
136
+ /**
137
+ * Generate embedding using attention if available, otherwise use improved hash
138
+ */
139
+ embed(text) {
140
+ const dim = this.config.embeddingDim;
141
+ // Try to use attention-based embedding
142
+ if (this.attention?.DotProductAttention) {
143
+ try {
144
+ return this.attentionEmbed(text, dim);
145
+ }
146
+ catch {
147
+ // Fall through to hash embedding
148
+ }
149
+ }
150
+ // Improved positional hash embedding
151
+ return this.hashEmbed(text, dim);
152
+ }
153
+ /**
154
+ * Attention-based embedding using self-attention
155
+ */
156
+ attentionEmbed(text, dim) {
157
+ const tokens = this.tokenize(text);
158
+ const tokenEmbeddings = tokens.map(t => this.tokenEmbed(t, dim));
159
+ if (tokenEmbeddings.length === 0) {
160
+ return new Array(dim).fill(0);
161
+ }
162
+ // Apply self-attention to aggregate token embeddings
163
+ const attn = new this.attention.DotProductAttention();
164
+ const query = this.meanPool(tokenEmbeddings);
165
+ const result = attn.forward(new Float32Array(query), tokenEmbeddings.map(e => new Float32Array(e)), tokenEmbeddings.map(e => new Float32Array(e)));
166
+ return Array.from(result);
167
+ }
168
+ /**
169
+ * Improved hash-based embedding with positional encoding
170
+ */
171
+ hashEmbed(text, dim) {
172
+ const embedding = new Array(dim).fill(0);
173
+ const tokens = this.tokenize(text);
174
+ for (let t = 0; t < tokens.length; t++) {
175
+ const token = tokens[t];
176
+ const posWeight = 1 / (1 + t * 0.1); // Positional decay
177
+ for (let i = 0; i < token.length; i++) {
178
+ const charCode = token.charCodeAt(i);
179
+ // Multiple hash functions for better distribution
180
+ const h1 = (charCode * 31 + i * 17 + t * 7) % dim;
181
+ const h2 = (charCode * 37 + i * 23 + t * 11) % dim;
182
+ const h3 = (charCode * 41 + i * 29 + t * 13) % dim;
183
+ embedding[h1] += posWeight;
184
+ embedding[h2] += posWeight * 0.5;
185
+ embedding[h3] += posWeight * 0.25;
186
+ }
187
+ }
188
+ // L2 normalize
189
+ const norm = Math.sqrt(embedding.reduce((a, b) => a + b * b, 0));
190
+ if (norm > 0) {
191
+ for (let i = 0; i < dim; i++)
192
+ embedding[i] /= norm;
193
+ }
194
+ return embedding;
195
+ }
196
+ tokenize(text) {
197
+ return text.toLowerCase()
198
+ .replace(/[^\w\s]/g, ' ')
199
+ .split(/\s+/)
200
+ .filter(t => t.length > 0);
201
+ }
202
+ tokenEmbed(token, dim) {
203
+ const embedding = new Array(dim).fill(0);
204
+ for (let i = 0; i < token.length; i++) {
205
+ const idx = (token.charCodeAt(i) * 31 + i * 17) % dim;
206
+ embedding[idx] += 1;
207
+ }
208
+ const norm = Math.sqrt(embedding.reduce((a, b) => a + b * b, 0));
209
+ if (norm > 0)
210
+ for (let i = 0; i < dim; i++)
211
+ embedding[i] /= norm;
212
+ return embedding;
213
+ }
214
+ meanPool(embeddings) {
215
+ if (embeddings.length === 0)
216
+ return [];
217
+ const dim = embeddings[0].length;
218
+ const result = new Array(dim).fill(0);
219
+ for (const emb of embeddings) {
220
+ for (let i = 0; i < dim; i++)
221
+ result[i] += emb[i];
222
+ }
223
+ for (let i = 0; i < dim; i++)
224
+ result[i] /= embeddings.length;
225
+ return result;
226
+ }
227
+ // =========================================================================
228
+ // Memory Operations
229
+ // =========================================================================
230
+ /**
231
+ * Store content in vector memory
232
+ */
233
+ async remember(content, type = 'general') {
234
+ const id = `mem-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
235
+ const embedding = this.embed(content);
236
+ const entry = {
237
+ id,
238
+ content,
239
+ type,
240
+ embedding,
241
+ created: new Date().toISOString(),
242
+ accessed: 0,
243
+ };
244
+ this.memories.set(id, entry);
245
+ // Index in VectorDB if available
246
+ if (this.vectorDb) {
247
+ try {
248
+ await this.vectorDb.insert({
249
+ id,
250
+ vector: new Float32Array(embedding),
251
+ metadata: JSON.stringify({ content, type, created: entry.created }),
252
+ });
253
+ }
254
+ catch {
255
+ // Ignore indexing errors
256
+ }
257
+ }
258
+ return entry;
259
+ }
260
+ /**
261
+ * Semantic search of memories
262
+ */
263
+ async recall(query, topK = 5) {
264
+ const queryEmbed = this.embed(query);
265
+ // Try VectorDB search first (HNSW - 150x faster)
266
+ if (this.vectorDb) {
267
+ try {
268
+ const results = await this.vectorDb.search({
269
+ vector: new Float32Array(queryEmbed),
270
+ k: topK,
271
+ });
272
+ return results.map((r) => {
273
+ const entry = this.memories.get(r.id);
274
+ if (entry) {
275
+ entry.accessed++;
276
+ entry.score = 1 - r.score; // Convert distance to similarity
277
+ }
278
+ return entry;
279
+ }).filter((e) => e !== null);
280
+ }
281
+ catch {
282
+ // Fall through to brute force
283
+ }
284
+ }
285
+ // Fallback: brute-force cosine similarity
286
+ const scored = Array.from(this.memories.values()).map(m => ({
287
+ ...m,
288
+ score: this.cosineSimilarity(queryEmbed, m.embedding),
289
+ }));
290
+ return scored
291
+ .sort((a, b) => (b.score || 0) - (a.score || 0))
292
+ .slice(0, topK);
293
+ }
294
+ cosineSimilarity(a, b) {
295
+ if (a.length !== b.length)
296
+ return 0;
297
+ let dot = 0, normA = 0, normB = 0;
298
+ for (let i = 0; i < a.length; i++) {
299
+ dot += a[i] * b[i];
300
+ normA += a[i] * a[i];
301
+ normB += b[i] * b[i];
302
+ }
303
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
304
+ return denom > 0 ? dot / denom : 0;
305
+ }
306
+ // =========================================================================
307
+ // Agent Routing with SONA
308
+ // =========================================================================
309
+ /**
310
+ * Route a task to the best agent using learned patterns
311
+ */
312
+ async route(task, file) {
313
+ const ext = file ? this.getExtension(file) : '';
314
+ const state = this.getState(task, ext);
315
+ const taskEmbed = this.embed(task + ' ' + (file || ''));
316
+ // Apply SONA micro-LoRA transformation if available
317
+ let adaptedEmbed = taskEmbed;
318
+ if (this.sona) {
319
+ try {
320
+ adaptedEmbed = this.sona.applyMicroLora(taskEmbed);
321
+ }
322
+ catch {
323
+ // Use original embedding
324
+ }
325
+ }
326
+ // Find similar patterns using ReasoningBank
327
+ let patterns = [];
328
+ if (this.sona) {
329
+ try {
330
+ patterns = this.sona.findPatterns(adaptedEmbed, 5);
331
+ }
332
+ catch {
333
+ // No patterns
334
+ }
335
+ }
336
+ // Default agent mappings
337
+ const defaults = {
338
+ '.rs': 'rust-developer',
339
+ '.ts': 'typescript-developer',
340
+ '.tsx': 'react-developer',
341
+ '.js': 'javascript-developer',
342
+ '.jsx': 'react-developer',
343
+ '.py': 'python-developer',
344
+ '.go': 'go-developer',
345
+ '.sql': 'database-specialist',
346
+ '.md': 'documentation-specialist',
347
+ '.yml': 'devops-engineer',
348
+ '.yaml': 'devops-engineer',
349
+ '.json': 'coder',
350
+ '.toml': 'coder',
351
+ };
352
+ // Check learned patterns first
353
+ const statePatterns = this.routingPatterns.get(state);
354
+ let bestAgent = defaults[ext] || 'coder';
355
+ let bestScore = 0.5;
356
+ let reason = 'default mapping';
357
+ if (statePatterns && statePatterns.size > 0) {
358
+ for (const [agent, score] of statePatterns) {
359
+ if (score > bestScore) {
360
+ bestAgent = agent;
361
+ bestScore = score;
362
+ reason = 'learned from patterns';
363
+ }
364
+ }
365
+ }
366
+ // Check custom agent mappings
367
+ if (this.agentMappings.has(ext)) {
368
+ const mapped = this.agentMappings.get(ext);
369
+ if (bestScore < 0.8) {
370
+ bestAgent = mapped;
371
+ bestScore = 0.8;
372
+ reason = 'custom mapping';
373
+ }
374
+ }
375
+ // Boost confidence if SONA patterns match
376
+ if (patterns.length > 0 && patterns[0].avgQuality > 0.7) {
377
+ bestScore = Math.min(1.0, bestScore + 0.1);
378
+ reason += ' + SONA pattern match';
379
+ }
380
+ return {
381
+ agent: bestAgent,
382
+ confidence: Math.min(1.0, bestScore),
383
+ reason,
384
+ patterns: patterns.length > 0 ? patterns : undefined,
385
+ alternates: this.getAlternates(statePatterns, bestAgent),
386
+ };
387
+ }
388
+ getExtension(file) {
389
+ const idx = file.lastIndexOf('.');
390
+ return idx >= 0 ? file.slice(idx).toLowerCase() : '';
391
+ }
392
+ getState(task, ext) {
393
+ const taskType = task.includes('fix') ? 'fix' :
394
+ task.includes('test') ? 'test' :
395
+ task.includes('refactor') ? 'refactor' :
396
+ task.includes('document') ? 'docs' : 'edit';
397
+ return `${taskType}:${ext || 'unknown'}`;
398
+ }
399
+ getAlternates(patterns, exclude) {
400
+ if (!patterns)
401
+ return [];
402
+ return Array.from(patterns.entries())
403
+ .filter(([a]) => a !== exclude)
404
+ .sort((a, b) => b[1] - a[1])
405
+ .slice(0, 3)
406
+ .map(([agent, confidence]) => ({ agent, confidence: Math.min(1.0, confidence) }));
407
+ }
408
+ // =========================================================================
409
+ // Trajectory Learning
410
+ // =========================================================================
411
+ /**
412
+ * Begin recording a trajectory (before edit/command)
413
+ */
414
+ beginTrajectory(context, file) {
415
+ const embed = this.embed(context + ' ' + (file || ''));
416
+ if (this.sona) {
417
+ try {
418
+ this.currentTrajectoryId = this.sona.beginTrajectory(embed);
419
+ if (file) {
420
+ this.sona.addContext(this.currentTrajectoryId, file);
421
+ }
422
+ }
423
+ catch {
424
+ this.currentTrajectoryId = null;
425
+ }
426
+ }
427
+ }
428
+ /**
429
+ * Add a step to the current trajectory
430
+ */
431
+ addTrajectoryStep(activations, reward) {
432
+ if (this.sona && this.currentTrajectoryId !== null) {
433
+ try {
434
+ const attentionWeights = new Array(activations.length).fill(1 / activations.length);
435
+ this.sona.addStep(this.currentTrajectoryId, activations, attentionWeights, reward);
436
+ }
437
+ catch {
438
+ // Ignore step errors
439
+ }
440
+ }
441
+ }
442
+ /**
443
+ * End the current trajectory with a quality score
444
+ */
445
+ endTrajectory(success, quality) {
446
+ const q = quality ?? (success ? 0.9 : 0.3);
447
+ if (this.sona && this.currentTrajectoryId !== null) {
448
+ try {
449
+ this.sona.endTrajectory(this.currentTrajectoryId, q);
450
+ }
451
+ catch {
452
+ // Ignore end errors
453
+ }
454
+ }
455
+ this.currentTrajectoryId = null;
456
+ }
457
+ /**
458
+ * Set the agent route for current trajectory
459
+ */
460
+ setTrajectoryRoute(agent) {
461
+ if (this.sona && this.currentTrajectoryId !== null) {
462
+ try {
463
+ this.sona.setRoute(this.currentTrajectoryId, agent);
464
+ }
465
+ catch {
466
+ // Ignore route errors
467
+ }
468
+ }
469
+ }
470
+ // =========================================================================
471
+ // Episode Learning (Q-learning compatible)
472
+ // =========================================================================
473
+ /**
474
+ * Record an episode for learning
475
+ */
476
+ async recordEpisode(state, action, reward, nextState, done, metadata) {
477
+ const stateEmbed = this.embed(state);
478
+ const nextStateEmbed = this.embed(nextState);
479
+ // Store in FastAgentDB
480
+ await this.agentDb.storeEpisode({
481
+ state: stateEmbed,
482
+ action,
483
+ reward,
484
+ nextState: nextStateEmbed,
485
+ done,
486
+ metadata,
487
+ });
488
+ // Update routing patterns (Q-learning style)
489
+ if (!this.routingPatterns.has(state)) {
490
+ this.routingPatterns.set(state, new Map());
491
+ }
492
+ const patterns = this.routingPatterns.get(state);
493
+ const oldValue = patterns.get(action) || 0.5;
494
+ const newValue = oldValue + this.config.learningRate * (reward - oldValue);
495
+ patterns.set(action, newValue);
496
+ }
497
+ /**
498
+ * Learn from similar past episodes
499
+ */
500
+ async learnFromSimilar(state, k = 5) {
501
+ const stateEmbed = this.embed(state);
502
+ return this.agentDb.searchByState(stateEmbed, k);
503
+ }
504
+ // =========================================================================
505
+ // Co-edit Pattern Learning
506
+ // =========================================================================
507
+ /**
508
+ * Record a co-edit pattern
509
+ */
510
+ recordCoEdit(file1, file2) {
511
+ if (!this.coEditPatterns.has(file1)) {
512
+ this.coEditPatterns.set(file1, new Map());
513
+ }
514
+ if (!this.coEditPatterns.has(file2)) {
515
+ this.coEditPatterns.set(file2, new Map());
516
+ }
517
+ const count1 = this.coEditPatterns.get(file1).get(file2) || 0;
518
+ this.coEditPatterns.get(file1).set(file2, count1 + 1);
519
+ const count2 = this.coEditPatterns.get(file2).get(file1) || 0;
520
+ this.coEditPatterns.get(file2).set(file1, count2 + 1);
521
+ }
522
+ /**
523
+ * Get likely next files to edit
524
+ */
525
+ getLikelyNextFiles(file, topK = 5) {
526
+ const related = this.coEditPatterns.get(file);
527
+ if (!related)
528
+ return [];
529
+ return Array.from(related.entries())
530
+ .sort((a, b) => b[1] - a[1])
531
+ .slice(0, topK)
532
+ .map(([f, count]) => ({ file: f, count }));
533
+ }
534
+ // =========================================================================
535
+ // Error Pattern Learning
536
+ // =========================================================================
537
+ /**
538
+ * Record an error pattern with fixes
539
+ */
540
+ recordErrorFix(errorPattern, fix) {
541
+ if (!this.errorPatterns.has(errorPattern)) {
542
+ this.errorPatterns.set(errorPattern, []);
543
+ }
544
+ const fixes = this.errorPatterns.get(errorPattern);
545
+ if (!fixes.includes(fix)) {
546
+ fixes.push(fix);
547
+ }
548
+ }
549
+ /**
550
+ * Get suggested fixes for an error
551
+ */
552
+ getSuggestedFixes(error) {
553
+ // Exact match
554
+ if (this.errorPatterns.has(error)) {
555
+ return this.errorPatterns.get(error);
556
+ }
557
+ // Fuzzy match by embedding similarity
558
+ const errorEmbed = this.embed(error);
559
+ const matches = [];
560
+ for (const [pattern, fixes] of this.errorPatterns) {
561
+ const patternEmbed = this.embed(pattern);
562
+ const similarity = this.cosineSimilarity(errorEmbed, patternEmbed);
563
+ if (similarity > 0.7) {
564
+ matches.push({ pattern, similarity, fixes });
565
+ }
566
+ }
567
+ if (matches.length === 0)
568
+ return [];
569
+ // Return fixes from most similar pattern
570
+ matches.sort((a, b) => b.similarity - a.similarity);
571
+ return matches[0].fixes;
572
+ }
573
+ // =========================================================================
574
+ // Tick / Background Learning
575
+ // =========================================================================
576
+ /**
577
+ * Run background learning cycle
578
+ */
579
+ tick() {
580
+ if (this.sona) {
581
+ try {
582
+ return this.sona.tick();
583
+ }
584
+ catch {
585
+ return null;
586
+ }
587
+ }
588
+ return null;
589
+ }
590
+ /**
591
+ * Force immediate learning
592
+ */
593
+ forceLearn() {
594
+ if (this.sona) {
595
+ try {
596
+ return this.sona.forceLearn();
597
+ }
598
+ catch {
599
+ return null;
600
+ }
601
+ }
602
+ return null;
603
+ }
604
+ // =========================================================================
605
+ // Statistics
606
+ // =========================================================================
607
+ /**
608
+ * Get comprehensive learning statistics
609
+ */
610
+ getStats() {
611
+ const agentDbStats = this.agentDb.getStats();
612
+ let sonaStats = null;
613
+ if (this.sona) {
614
+ try {
615
+ sonaStats = this.sona.getStats();
616
+ }
617
+ catch {
618
+ // No SONA stats
619
+ }
620
+ }
621
+ // Calculate average reward from patterns
622
+ let totalReward = 0;
623
+ let rewardCount = 0;
624
+ for (const patterns of this.routingPatterns.values()) {
625
+ for (const reward of patterns.values()) {
626
+ totalReward += reward;
627
+ rewardCount++;
628
+ }
629
+ }
630
+ return {
631
+ totalMemories: this.memories.size,
632
+ memoryDimensions: this.config.embeddingDim,
633
+ totalEpisodes: agentDbStats.episodeCount,
634
+ totalTrajectories: agentDbStats.trajectoryCount,
635
+ avgReward: rewardCount > 0 ? totalReward / rewardCount : 0,
636
+ sonaEnabled: this.sona !== null,
637
+ trajectoriesRecorded: sonaStats?.trajectoriesRecorded ?? 0,
638
+ patternsLearned: sonaStats?.patternsLearned ?? 0,
639
+ microLoraUpdates: sonaStats?.microLoraUpdates ?? 0,
640
+ baseLoraUpdates: sonaStats?.baseLoraUpdates ?? 0,
641
+ ewcConsolidations: sonaStats?.ewcConsolidations ?? 0,
642
+ routingPatterns: this.routingPatterns.size,
643
+ errorPatterns: this.errorPatterns.size,
644
+ coEditPatterns: this.coEditPatterns.size,
645
+ attentionEnabled: this.attention !== null,
646
+ };
647
+ }
648
+ // =========================================================================
649
+ // Persistence
650
+ // =========================================================================
651
+ /**
652
+ * Export all data for persistence
653
+ */
654
+ export() {
655
+ return {
656
+ version: '2.0.0',
657
+ exported: new Date().toISOString(),
658
+ config: this.config,
659
+ memories: Array.from(this.memories.values()),
660
+ routingPatterns: Object.fromEntries(Array.from(this.routingPatterns.entries()).map(([k, v]) => [
661
+ k,
662
+ Object.fromEntries(v),
663
+ ])),
664
+ errorPatterns: Object.fromEntries(this.errorPatterns),
665
+ coEditPatterns: Object.fromEntries(Array.from(this.coEditPatterns.entries()).map(([k, v]) => [
666
+ k,
667
+ Object.fromEntries(v),
668
+ ])),
669
+ agentMappings: Object.fromEntries(this.agentMappings),
670
+ stats: this.getStats(),
671
+ };
672
+ }
673
+ /**
674
+ * Import data from persistence
675
+ */
676
+ import(data, merge = false) {
677
+ if (!merge) {
678
+ this.memories.clear();
679
+ this.routingPatterns.clear();
680
+ this.errorPatterns.clear();
681
+ this.coEditPatterns.clear();
682
+ this.agentMappings.clear();
683
+ }
684
+ // Import memories
685
+ if (data.memories) {
686
+ for (const mem of data.memories) {
687
+ this.memories.set(mem.id, mem);
688
+ }
689
+ }
690
+ // Import routing patterns
691
+ if (data.routingPatterns) {
692
+ for (const [state, actions] of Object.entries(data.routingPatterns)) {
693
+ const map = new Map(Object.entries(actions));
694
+ if (merge && this.routingPatterns.has(state)) {
695
+ const existing = this.routingPatterns.get(state);
696
+ for (const [action, value] of map) {
697
+ existing.set(action, Math.max(existing.get(action) || 0, value));
698
+ }
699
+ }
700
+ else {
701
+ this.routingPatterns.set(state, map);
702
+ }
703
+ }
704
+ }
705
+ // Import error patterns
706
+ if (data.errorPatterns) {
707
+ for (const [pattern, fixes] of Object.entries(data.errorPatterns)) {
708
+ if (merge && this.errorPatterns.has(pattern)) {
709
+ const existing = this.errorPatterns.get(pattern);
710
+ for (const fix of fixes) {
711
+ if (!existing.includes(fix))
712
+ existing.push(fix);
713
+ }
714
+ }
715
+ else {
716
+ this.errorPatterns.set(pattern, fixes);
717
+ }
718
+ }
719
+ }
720
+ // Import co-edit patterns
721
+ if (data.coEditPatterns) {
722
+ for (const [file, related] of Object.entries(data.coEditPatterns)) {
723
+ const map = new Map(Object.entries(related));
724
+ if (merge && this.coEditPatterns.has(file)) {
725
+ const existing = this.coEditPatterns.get(file);
726
+ for (const [f, count] of map) {
727
+ existing.set(f, (existing.get(f) || 0) + count);
728
+ }
729
+ }
730
+ else {
731
+ this.coEditPatterns.set(file, map);
732
+ }
733
+ }
734
+ }
735
+ // Import agent mappings
736
+ if (data.agentMappings) {
737
+ for (const [ext, agent] of Object.entries(data.agentMappings)) {
738
+ this.agentMappings.set(ext, agent);
739
+ }
740
+ }
741
+ }
742
+ /**
743
+ * Clear all data
744
+ */
745
+ clear() {
746
+ this.memories.clear();
747
+ this.routingPatterns.clear();
748
+ this.errorPatterns.clear();
749
+ this.coEditPatterns.clear();
750
+ this.agentMappings.clear();
751
+ this.agentDb.clear();
752
+ }
753
+ // =========================================================================
754
+ // Compatibility with existing Intelligence class
755
+ // =========================================================================
756
+ /** Legacy: patterns object */
757
+ get patterns() {
758
+ const result = {};
759
+ for (const [state, actions] of this.routingPatterns) {
760
+ result[state] = Object.fromEntries(actions);
761
+ }
762
+ return result;
763
+ }
764
+ /** Legacy: file_sequences array */
765
+ get file_sequences() {
766
+ const sequences = [];
767
+ for (const [file, related] of this.coEditPatterns) {
768
+ const sorted = Array.from(related.entries())
769
+ .sort((a, b) => b[1] - a[1])
770
+ .map(([f]) => f);
771
+ if (sorted.length > 0) {
772
+ sequences.push([file, ...sorted.slice(0, 3)]);
773
+ }
774
+ }
775
+ return sequences;
776
+ }
777
+ /** Legacy: errors object */
778
+ get errors() {
779
+ return Object.fromEntries(this.errorPatterns);
780
+ }
781
+ }
782
+ exports.IntelligenceEngine = IntelligenceEngine;
783
+ // ============================================================================
784
+ // Factory Functions
785
+ // ============================================================================
786
+ /**
787
+ * Create a new IntelligenceEngine with default settings
788
+ */
789
+ function createIntelligenceEngine(config) {
790
+ return new IntelligenceEngine(config);
791
+ }
792
+ /**
793
+ * Create a high-performance engine with all features enabled
794
+ */
795
+ function createHighPerformanceEngine() {
796
+ return new IntelligenceEngine({
797
+ embeddingDim: 512,
798
+ maxMemories: 200000,
799
+ maxEpisodes: 100000,
800
+ enableSona: true,
801
+ enableAttention: true,
802
+ sonaConfig: {
803
+ hiddenDim: 512,
804
+ microLoraRank: 2,
805
+ baseLoraRank: 16,
806
+ patternClusters: 200,
807
+ },
808
+ });
809
+ }
810
+ /**
811
+ * Create a lightweight engine for fast startup
812
+ */
813
+ function createLightweightEngine() {
814
+ return new IntelligenceEngine({
815
+ embeddingDim: 128,
816
+ maxMemories: 10000,
817
+ maxEpisodes: 5000,
818
+ enableSona: false,
819
+ enableAttention: false,
820
+ });
821
+ }
822
+ exports.default = IntelligenceEngine;