@sparkleideas/ruv-swarm 1.0.18-patch.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1565 -0
- package/bin/ruv-swarm-clean.js +1872 -0
- package/bin/ruv-swarm-memory.js +119 -0
- package/bin/ruv-swarm-secure-heartbeat.js +1549 -0
- package/bin/ruv-swarm-secure.js +1689 -0
- package/package.json +221 -0
- package/src/agent.ts +342 -0
- package/src/benchmark.js +267 -0
- package/src/claude-flow-enhanced.js +839 -0
- package/src/claude-integration/advanced-commands.js +561 -0
- package/src/claude-integration/core.js +112 -0
- package/src/claude-integration/docs.js +1548 -0
- package/src/claude-integration/env-template.js +39 -0
- package/src/claude-integration/index.js +209 -0
- package/src/claude-integration/remote.js +408 -0
- package/src/cli-diagnostics.js +364 -0
- package/src/cognitive-pattern-evolution.js +1317 -0
- package/src/daa-cognition.js +977 -0
- package/src/daa-service.d.ts +298 -0
- package/src/daa-service.js +1116 -0
- package/src/diagnostics.js +533 -0
- package/src/errors.js +528 -0
- package/src/github-coordinator/README.md +193 -0
- package/src/github-coordinator/claude-hooks.js +162 -0
- package/src/github-coordinator/gh-cli-coordinator.js +260 -0
- package/src/hooks/cli.js +82 -0
- package/src/hooks/index.js +1900 -0
- package/src/index-enhanced.d.ts +371 -0
- package/src/index-enhanced.js +734 -0
- package/src/index.d.ts +287 -0
- package/src/index.js +405 -0
- package/src/index.ts +457 -0
- package/src/logger.js +182 -0
- package/src/logging-config.js +179 -0
- package/src/mcp-daa-tools.js +735 -0
- package/src/mcp-tools-benchmarks.js +328 -0
- package/src/mcp-tools-enhanced.js +2863 -0
- package/src/memory-config.js +42 -0
- package/src/meta-learning-framework.js +1359 -0
- package/src/neural-agent.js +830 -0
- package/src/neural-coordination-protocol.js +1363 -0
- package/src/neural-models/README.md +118 -0
- package/src/neural-models/autoencoder.js +543 -0
- package/src/neural-models/base.js +269 -0
- package/src/neural-models/cnn.js +497 -0
- package/src/neural-models/gnn.js +447 -0
- package/src/neural-models/gru.js +536 -0
- package/src/neural-models/index.js +273 -0
- package/src/neural-models/lstm.js +551 -0
- package/src/neural-models/neural-presets-complete.js +1306 -0
- package/src/neural-models/presets/graph.js +392 -0
- package/src/neural-models/presets/index.js +279 -0
- package/src/neural-models/presets/nlp.js +328 -0
- package/src/neural-models/presets/timeseries.js +368 -0
- package/src/neural-models/presets/vision.js +387 -0
- package/src/neural-models/resnet.js +534 -0
- package/src/neural-models/transformer.js +515 -0
- package/src/neural-models/vae.js +489 -0
- package/src/neural-network-manager.js +1938 -0
- package/src/neural-network.ts +296 -0
- package/src/neural.js +574 -0
- package/src/performance-benchmarks.js +898 -0
- package/src/performance.js +458 -0
- package/src/persistence-pooled.js +695 -0
- package/src/persistence.js +480 -0
- package/src/schemas.js +864 -0
- package/src/security.js +218 -0
- package/src/singleton-container.js +183 -0
- package/src/sqlite-pool.js +587 -0
- package/src/sqlite-worker.js +141 -0
- package/src/types.ts +164 -0
- package/src/utils.ts +286 -0
- package/src/wasm-loader.js +601 -0
- package/src/wasm-loader2.js +404 -0
- package/src/wasm-memory-optimizer.js +783 -0
- package/src/wasm-types.d.ts +63 -0
- package/wasm/README.md +347 -0
- package/wasm/neuro-divergent.wasm +0 -0
- package/wasm/package.json +18 -0
- package/wasm/ruv-fann.wasm +0 -0
- package/wasm/ruv_swarm_simd.wasm +0 -0
- package/wasm/ruv_swarm_wasm.d.ts +391 -0
- package/wasm/ruv_swarm_wasm.js +2164 -0
- package/wasm/ruv_swarm_wasm_bg.wasm +0 -0
- package/wasm/ruv_swarm_wasm_bg.wasm.d.ts +123 -0
- package/wasm/wasm-bindings-loader.mjs +435 -0
- package/wasm/wasm-updates.md +684 -0
|
@@ -0,0 +1,1317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cognitive Pattern Evolution System
|
|
3
|
+
* Enables autonomous learning and adaptation of cognitive patterns
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
class CognitivePatternEvolution {
|
|
7
|
+
constructor() {
|
|
8
|
+
this.agentPatterns = new Map();
|
|
9
|
+
this.evolutionHistory = new Map();
|
|
10
|
+
this.patternTemplates = new Map();
|
|
11
|
+
this.crossAgentPatterns = new Map();
|
|
12
|
+
this.evolutionMetrics = new Map();
|
|
13
|
+
|
|
14
|
+
// Initialize base cognitive pattern templates
|
|
15
|
+
this.initializePatternTemplates();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Initialize base cognitive pattern templates
|
|
20
|
+
*/
|
|
21
|
+
initializePatternTemplates() {
|
|
22
|
+
// Convergent thinking patterns
|
|
23
|
+
this.patternTemplates.set('convergent', {
|
|
24
|
+
name: 'Convergent Thinking',
|
|
25
|
+
description: 'Focus on single optimal solutions',
|
|
26
|
+
characteristics: {
|
|
27
|
+
searchStrategy: 'directed',
|
|
28
|
+
explorationRate: 0.1,
|
|
29
|
+
exploitationRate: 0.9,
|
|
30
|
+
decisionMaking: 'decisive',
|
|
31
|
+
patternRecognition: 'exact_match',
|
|
32
|
+
},
|
|
33
|
+
adaptationRules: {
|
|
34
|
+
increasePrecision: (context) => context.accuracy > 0.8,
|
|
35
|
+
reduceExploration: (context) => context.confidence > 0.7,
|
|
36
|
+
focusAttention: (context) => context.taskComplexity < 0.5,
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// Divergent thinking patterns
|
|
41
|
+
this.patternTemplates.set('divergent', {
|
|
42
|
+
name: 'Divergent Thinking',
|
|
43
|
+
description: 'Explore multiple creative solutions',
|
|
44
|
+
characteristics: {
|
|
45
|
+
searchStrategy: 'random',
|
|
46
|
+
explorationRate: 0.8,
|
|
47
|
+
exploitationRate: 0.2,
|
|
48
|
+
decisionMaking: 'exploratory',
|
|
49
|
+
patternRecognition: 'flexible_match',
|
|
50
|
+
},
|
|
51
|
+
adaptationRules: {
|
|
52
|
+
increaseCreativity: (context) => context.noveltyScore > 0.6,
|
|
53
|
+
expandSearch: (context) => context.solutionDiversity < 0.5,
|
|
54
|
+
encourageRisk: (context) => context.safetyMargin > 0.8,
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Lateral thinking patterns
|
|
59
|
+
this.patternTemplates.set('lateral', {
|
|
60
|
+
name: 'Lateral Thinking',
|
|
61
|
+
description: 'Approach problems from unexpected angles',
|
|
62
|
+
characteristics: {
|
|
63
|
+
searchStrategy: 'lateral',
|
|
64
|
+
explorationRate: 0.6,
|
|
65
|
+
exploitationRate: 0.4,
|
|
66
|
+
decisionMaking: 'innovative',
|
|
67
|
+
patternRecognition: 'analogical',
|
|
68
|
+
},
|
|
69
|
+
adaptationRules: {
|
|
70
|
+
seekAlternatives: (context) => context.standardSolutionFailed,
|
|
71
|
+
useAnalogies: (context) => context.domainKnowledge > 0.5,
|
|
72
|
+
breakAssumptions: (context) => context.progressStalled,
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// Systems thinking patterns
|
|
77
|
+
this.patternTemplates.set('systems', {
|
|
78
|
+
name: 'Systems Thinking',
|
|
79
|
+
description: 'Consider holistic interconnections and emergent properties',
|
|
80
|
+
characteristics: {
|
|
81
|
+
searchStrategy: 'holistic',
|
|
82
|
+
explorationRate: 0.4,
|
|
83
|
+
exploitationRate: 0.6,
|
|
84
|
+
decisionMaking: 'systemic',
|
|
85
|
+
patternRecognition: 'pattern_networks',
|
|
86
|
+
},
|
|
87
|
+
adaptationRules: {
|
|
88
|
+
mapConnections: (context) => context.systemComplexity > 0.7,
|
|
89
|
+
identifyFeedback: (context) => context.iterationCount > 5,
|
|
90
|
+
emergentProperties: (context) => context.componentInteractions > 0.6,
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// Critical thinking patterns
|
|
95
|
+
this.patternTemplates.set('critical', {
|
|
96
|
+
name: 'Critical Thinking',
|
|
97
|
+
description: 'Systematic evaluation and logical analysis',
|
|
98
|
+
characteristics: {
|
|
99
|
+
searchStrategy: 'systematic',
|
|
100
|
+
explorationRate: 0.3,
|
|
101
|
+
exploitationRate: 0.7,
|
|
102
|
+
decisionMaking: 'analytical',
|
|
103
|
+
patternRecognition: 'evidence_based',
|
|
104
|
+
},
|
|
105
|
+
adaptationRules: {
|
|
106
|
+
validateEvidence: (context) => context.informationQuality < 0.8,
|
|
107
|
+
checkBias: (context) => context.subjectivity > 0.5,
|
|
108
|
+
logicalConsistency: (context) => context.contradictions > 0.2,
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// Abstract thinking patterns
|
|
113
|
+
this.patternTemplates.set('abstract', {
|
|
114
|
+
name: 'Abstract Thinking',
|
|
115
|
+
description: 'Work with concepts, principles, and generalizations',
|
|
116
|
+
characteristics: {
|
|
117
|
+
searchStrategy: 'conceptual',
|
|
118
|
+
explorationRate: 0.5,
|
|
119
|
+
exploitationRate: 0.5,
|
|
120
|
+
decisionMaking: 'principled',
|
|
121
|
+
patternRecognition: 'abstraction_layers',
|
|
122
|
+
},
|
|
123
|
+
adaptationRules: {
|
|
124
|
+
generalizePatterns: (context) => context.specificExamples > 3,
|
|
125
|
+
identifyPrinciples: (context) => context.abstraction_level < 0.6,
|
|
126
|
+
conceptualMapping: (context) => context.domainTransfer > 0.4,
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Initialize agent with cognitive patterns
|
|
133
|
+
* @param {string} agentId - Agent identifier
|
|
134
|
+
* @param {Object} config - Agent configuration
|
|
135
|
+
*/
|
|
136
|
+
async initializeAgent(agentId, config) {
|
|
137
|
+
const initialPatterns = this.selectInitialPatterns(config);
|
|
138
|
+
|
|
139
|
+
this.agentPatterns.set(agentId, {
|
|
140
|
+
activePatterns: initialPatterns,
|
|
141
|
+
dominantPattern: initialPatterns[0] || 'convergent',
|
|
142
|
+
adaptationHistory: [],
|
|
143
|
+
evolutionScore: 0,
|
|
144
|
+
lastEvolution: Date.now(),
|
|
145
|
+
crossAgentLearning: new Map(),
|
|
146
|
+
specializations: new Set(),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
this.evolutionHistory.set(agentId, []);
|
|
150
|
+
this.evolutionMetrics.set(agentId, {
|
|
151
|
+
totalEvolutions: 0,
|
|
152
|
+
successfulAdaptations: 0,
|
|
153
|
+
patternSwitches: 0,
|
|
154
|
+
crossAgentTransfers: 0,
|
|
155
|
+
emergentPatterns: 0,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
console.log(`Initialized cognitive patterns for agent ${agentId}: ${initialPatterns.join(', ')}`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Select initial cognitive patterns based on configuration
|
|
163
|
+
* @param {Object} config - Agent configuration
|
|
164
|
+
*/
|
|
165
|
+
selectInitialPatterns(config) {
|
|
166
|
+
const patterns = [];
|
|
167
|
+
|
|
168
|
+
// Select patterns based on model type and use case
|
|
169
|
+
if (config.modelType) {
|
|
170
|
+
switch (config.modelType) {
|
|
171
|
+
case 'transformer':
|
|
172
|
+
case 'lstm':
|
|
173
|
+
case 'gru':
|
|
174
|
+
patterns.push('convergent', 'systems');
|
|
175
|
+
break;
|
|
176
|
+
case 'cnn':
|
|
177
|
+
case 'resnet':
|
|
178
|
+
patterns.push('critical', 'abstract');
|
|
179
|
+
break;
|
|
180
|
+
case 'gnn':
|
|
181
|
+
case 'gat':
|
|
182
|
+
patterns.push('systems', 'lateral');
|
|
183
|
+
break;
|
|
184
|
+
case 'vae':
|
|
185
|
+
case 'autoencoder':
|
|
186
|
+
patterns.push('divergent', 'abstract');
|
|
187
|
+
break;
|
|
188
|
+
case 'diffusion_model':
|
|
189
|
+
case 'neural_ode':
|
|
190
|
+
patterns.push('divergent', 'lateral');
|
|
191
|
+
break;
|
|
192
|
+
default:
|
|
193
|
+
patterns.push('convergent', 'critical');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Add patterns based on task characteristics
|
|
198
|
+
if (config.template) {
|
|
199
|
+
if (config.template.includes('analyzer')) {
|
|
200
|
+
patterns.push('critical');
|
|
201
|
+
}
|
|
202
|
+
if (config.template.includes('generator')) {
|
|
203
|
+
patterns.push('divergent');
|
|
204
|
+
}
|
|
205
|
+
if (config.template.includes('processor')) {
|
|
206
|
+
patterns.push('systems');
|
|
207
|
+
}
|
|
208
|
+
if (config.template.includes('learner')) {
|
|
209
|
+
patterns.push('abstract');
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Ensure at least one pattern
|
|
214
|
+
if (patterns.length === 0) {
|
|
215
|
+
patterns.push('convergent');
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return [...new Set(patterns)]; // Remove duplicates
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Evolve cognitive patterns based on training data and performance
|
|
223
|
+
* @param {string} agentId - Agent identifier
|
|
224
|
+
* @param {Object} trainingData - Training data context
|
|
225
|
+
*/
|
|
226
|
+
async evolvePatterns(agentId, trainingData) {
|
|
227
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
228
|
+
if (!agentData) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const context = this.analyzeTrainingContext(trainingData);
|
|
233
|
+
const currentPatterns = agentData.activePatterns;
|
|
234
|
+
|
|
235
|
+
// Evaluate current pattern effectiveness
|
|
236
|
+
const patternEffectiveness = await this.evaluatePatternEffectiveness(agentId, context);
|
|
237
|
+
|
|
238
|
+
// Determine if evolution is needed
|
|
239
|
+
const evolutionNeed = this.assessEvolutionNeed(patternEffectiveness, context);
|
|
240
|
+
|
|
241
|
+
if (evolutionNeed.required) {
|
|
242
|
+
const evolutionStrategy = this.selectEvolutionStrategy(evolutionNeed, context);
|
|
243
|
+
const newPatterns = await this.applyEvolution(agentId, evolutionStrategy, context);
|
|
244
|
+
|
|
245
|
+
// Record evolution
|
|
246
|
+
this.recordEvolution(agentId, {
|
|
247
|
+
timestamp: Date.now(),
|
|
248
|
+
trigger: evolutionNeed.reason,
|
|
249
|
+
strategy: evolutionStrategy,
|
|
250
|
+
oldPatterns: [...currentPatterns],
|
|
251
|
+
newPatterns,
|
|
252
|
+
context,
|
|
253
|
+
effectiveness: patternEffectiveness,
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
console.log(`Evolved cognitive patterns for agent ${agentId}: ${evolutionStrategy.type}`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Analyze training context to understand cognitive requirements
|
|
262
|
+
* @param {Object} trainingData - Training data
|
|
263
|
+
*/
|
|
264
|
+
analyzeTrainingContext(trainingData) {
|
|
265
|
+
const context = {
|
|
266
|
+
dataComplexity: this.calculateDataComplexity(trainingData),
|
|
267
|
+
taskType: this.inferTaskType(trainingData),
|
|
268
|
+
noiseLevel: this.estimateNoiseLevel(trainingData),
|
|
269
|
+
patternRegularity: this.assessPatternRegularity(trainingData),
|
|
270
|
+
dimensionality: this.calculateDimensionality(trainingData),
|
|
271
|
+
temporalDependency: this.assessTemporalDependency(trainingData),
|
|
272
|
+
abstractionLevel: this.estimateAbstractionLevel(trainingData),
|
|
273
|
+
creativity_required: this.assessCreativityRequirement(trainingData),
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
return context;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Calculate data complexity score
|
|
281
|
+
* @param {Object} trainingData - Training data
|
|
282
|
+
*/
|
|
283
|
+
calculateDataComplexity(trainingData) {
|
|
284
|
+
if (!trainingData.samples || trainingData.samples.length === 0) {
|
|
285
|
+
return 0.5;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const sampleSize = trainingData.samples.length;
|
|
289
|
+
const featureVariance = this.calculateFeatureVariance(trainingData.samples);
|
|
290
|
+
const labelDistribution = this.calculateLabelDistribution(trainingData.samples);
|
|
291
|
+
|
|
292
|
+
// Combine metrics for overall complexity
|
|
293
|
+
const sizeComplexity = Math.min(1, sampleSize / 10000);
|
|
294
|
+
const varianceComplexity = Math.min(1, featureVariance);
|
|
295
|
+
const distributionComplexity = labelDistribution;
|
|
296
|
+
|
|
297
|
+
return (sizeComplexity + varianceComplexity + distributionComplexity) / 3;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Calculate feature variance across samples
|
|
302
|
+
* @param {Array} samples - Training samples
|
|
303
|
+
*/
|
|
304
|
+
calculateFeatureVariance(samples) {
|
|
305
|
+
if (samples.length < 2) {
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const firstSample = Array.isArray(samples[0]) ? samples[0] : [samples[0]];
|
|
310
|
+
const numFeatures = firstSample.length;
|
|
311
|
+
|
|
312
|
+
let totalVariance = 0;
|
|
313
|
+
|
|
314
|
+
for (let f = 0; f < numFeatures; f++) {
|
|
315
|
+
const values = samples.map(s => Array.isArray(s) ? s[f] : s).filter(v => typeof v === 'number');
|
|
316
|
+
if (values.length < 2) {
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
|
|
321
|
+
const variance = values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / values.length;
|
|
322
|
+
totalVariance += variance;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return totalVariance / numFeatures;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Calculate label distribution entropy
|
|
330
|
+
* @param {Array} samples - Training samples
|
|
331
|
+
*/
|
|
332
|
+
calculateLabelDistribution(samples) {
|
|
333
|
+
const labelCounts = new Map();
|
|
334
|
+
|
|
335
|
+
samples.forEach(sample => {
|
|
336
|
+
const label = sample.label || sample.target || 'unknown';
|
|
337
|
+
labelCounts.set(label, (labelCounts.get(label) || 0) + 1);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
const totalSamples = samples.length;
|
|
341
|
+
let entropy = 0;
|
|
342
|
+
|
|
343
|
+
for (const count of labelCounts.values()) {
|
|
344
|
+
const probability = count / totalSamples;
|
|
345
|
+
entropy -= probability * Math.log2(probability);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Normalize entropy (max entropy for uniform distribution)
|
|
349
|
+
const maxEntropy = Math.log2(labelCounts.size);
|
|
350
|
+
return maxEntropy > 0 ? entropy / maxEntropy : 0;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Infer task type from training data characteristics
|
|
355
|
+
* @param {Object} trainingData - Training data
|
|
356
|
+
*/
|
|
357
|
+
inferTaskType(trainingData) {
|
|
358
|
+
if (!trainingData.samples) {
|
|
359
|
+
return 'unknown';
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const sample = trainingData.samples[0];
|
|
363
|
+
if (!sample) {
|
|
364
|
+
return 'unknown';
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Check for common task patterns
|
|
368
|
+
if (sample.target && Array.isArray(sample.target)) {
|
|
369
|
+
return sample.target.length > 1 ? 'multi_classification' : 'regression';
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (sample.label !== undefined) {
|
|
373
|
+
return 'classification';
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (sample.sequence || Array.isArray(sample.input)) {
|
|
377
|
+
return 'sequence';
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return 'regression';
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Estimate noise level in training data
|
|
385
|
+
* @param {Object} trainingData - Training data
|
|
386
|
+
*/
|
|
387
|
+
estimateNoiseLevel(trainingData) {
|
|
388
|
+
if (!trainingData.samples || trainingData.samples.length < 10) {
|
|
389
|
+
return 0.5;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Simple heuristic: calculate coefficient of variation
|
|
393
|
+
const values = trainingData.samples.map(s => {
|
|
394
|
+
if (typeof s === 'number') {
|
|
395
|
+
return s;
|
|
396
|
+
}
|
|
397
|
+
if (Array.isArray(s)) {
|
|
398
|
+
return s.reduce((sum, v) => sum + v, 0) / s.length;
|
|
399
|
+
}
|
|
400
|
+
return 0;
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
|
|
404
|
+
const variance = values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / values.length;
|
|
405
|
+
const stdDev = Math.sqrt(variance);
|
|
406
|
+
|
|
407
|
+
return mean !== 0 ? Math.min(1, stdDev / Math.abs(mean)) : 0.5;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Assess pattern regularity in data
|
|
412
|
+
* @param {Object} trainingData - Training data
|
|
413
|
+
*/
|
|
414
|
+
assessPatternRegularity(trainingData) {
|
|
415
|
+
// Simplified regularity assessment
|
|
416
|
+
if (!trainingData.samples || trainingData.samples.length < 5) {
|
|
417
|
+
return 0.5;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// Check for periodic patterns or consistent structures
|
|
421
|
+
const labelSequence = trainingData.samples.map(s => s.label || s.target || 0);
|
|
422
|
+
const uniqueLabels = new Set(labelSequence);
|
|
423
|
+
|
|
424
|
+
// More unique labels = less regular
|
|
425
|
+
const regularity = 1 - (uniqueLabels.size / labelSequence.length);
|
|
426
|
+
return Math.max(0, Math.min(1, regularity));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Calculate effective dimensionality
|
|
431
|
+
* @param {Object} trainingData - Training data
|
|
432
|
+
*/
|
|
433
|
+
calculateDimensionality(trainingData) {
|
|
434
|
+
if (!trainingData.samples || trainingData.samples.length === 0) {
|
|
435
|
+
return 0;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const sample = trainingData.samples[0];
|
|
439
|
+
if (Array.isArray(sample)) {
|
|
440
|
+
return Math.min(1, sample.length / 1000); // Normalize to 0-1
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
return 0.1; // Low dimensionality for non-array data
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Assess temporal dependency in data
|
|
448
|
+
* @param {Object} trainingData - Training data
|
|
449
|
+
*/
|
|
450
|
+
assessTemporalDependency(trainingData) {
|
|
451
|
+
// Check if data has temporal structure
|
|
452
|
+
const hasTimestamps = trainingData.samples?.some(s => s.timestamp || s.time);
|
|
453
|
+
const hasSequence = trainingData.samples?.some(s => s.sequence || Array.isArray(s.input));
|
|
454
|
+
|
|
455
|
+
if (hasTimestamps) {
|
|
456
|
+
return 0.8;
|
|
457
|
+
}
|
|
458
|
+
if (hasSequence) {
|
|
459
|
+
return 0.6;
|
|
460
|
+
}
|
|
461
|
+
return 0.2;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Estimate required abstraction level
|
|
466
|
+
* @param {Object} trainingData - Training data
|
|
467
|
+
*/
|
|
468
|
+
estimateAbstractionLevel(trainingData) {
|
|
469
|
+
// Higher abstraction for complex, structured data
|
|
470
|
+
const complexity = this.calculateDataComplexity(trainingData);
|
|
471
|
+
const dimensionality = this.calculateDimensionality(trainingData);
|
|
472
|
+
|
|
473
|
+
return (complexity + dimensionality) / 2;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Assess creativity requirement from data
|
|
478
|
+
* @param {Object} trainingData - Training data
|
|
479
|
+
*/
|
|
480
|
+
assessCreativityRequirement(trainingData) {
|
|
481
|
+
// Check for generation tasks or high variability
|
|
482
|
+
const taskType = this.inferTaskType(trainingData);
|
|
483
|
+
const noiseLevel = this.estimateNoiseLevel(trainingData);
|
|
484
|
+
|
|
485
|
+
if (taskType.includes('generation')) {
|
|
486
|
+
return 0.8;
|
|
487
|
+
}
|
|
488
|
+
if (noiseLevel > 0.7) {
|
|
489
|
+
return 0.6;
|
|
490
|
+
}
|
|
491
|
+
return 0.3;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Evaluate effectiveness of current cognitive patterns
|
|
496
|
+
* @param {string} agentId - Agent identifier
|
|
497
|
+
* @param {Object} context - Training context
|
|
498
|
+
*/
|
|
499
|
+
async evaluatePatternEffectiveness(agentId, context) {
|
|
500
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
501
|
+
if (!agentData) {
|
|
502
|
+
return {};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const effectiveness = {};
|
|
506
|
+
|
|
507
|
+
for (const patternType of agentData.activePatterns) {
|
|
508
|
+
const template = this.patternTemplates.get(patternType);
|
|
509
|
+
if (!template) {
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// Evaluate how well this pattern matches the context
|
|
514
|
+
const contextMatch = this.calculateContextMatch(template, context);
|
|
515
|
+
const historicalPerformance = this.getHistoricalPerformance(agentId, patternType);
|
|
516
|
+
const adaptationSuccess = this.getAdaptationSuccess(agentId, patternType);
|
|
517
|
+
|
|
518
|
+
effectiveness[patternType] = {
|
|
519
|
+
contextMatch,
|
|
520
|
+
historicalPerformance,
|
|
521
|
+
adaptationSuccess,
|
|
522
|
+
overall: (contextMatch + historicalPerformance + adaptationSuccess) / 3,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
return effectiveness;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Calculate how well a pattern template matches the current context
|
|
531
|
+
* @param {Object} template - Pattern template
|
|
532
|
+
* @param {Object} context - Current context
|
|
533
|
+
*/
|
|
534
|
+
calculateContextMatch(template, context) {
|
|
535
|
+
const { characteristics } = template;
|
|
536
|
+
let totalMatch = 0;
|
|
537
|
+
let weightSum = 0;
|
|
538
|
+
|
|
539
|
+
// Match exploration vs exploitation preference
|
|
540
|
+
const explorationNeed = context.creativity_required + context.noiseLevel;
|
|
541
|
+
const explorationMatch = Math.abs(characteristics.explorationRate - explorationNeed);
|
|
542
|
+
totalMatch += (1 - explorationMatch) * 0.3;
|
|
543
|
+
weightSum += 0.3;
|
|
544
|
+
|
|
545
|
+
// Match decision making style
|
|
546
|
+
const systematicNeed = context.dataComplexity + context.patternRegularity;
|
|
547
|
+
const systematicMatch = this.matchDecisionStyle(characteristics.decisionMaking, systematicNeed);
|
|
548
|
+
totalMatch += systematicMatch * 0.25;
|
|
549
|
+
weightSum += 0.25;
|
|
550
|
+
|
|
551
|
+
// Match pattern recognition approach
|
|
552
|
+
const abstractionMatch = this.matchPatternRecognition(characteristics.patternRecognition, context);
|
|
553
|
+
totalMatch += abstractionMatch * 0.25;
|
|
554
|
+
weightSum += 0.25;
|
|
555
|
+
|
|
556
|
+
// Match search strategy
|
|
557
|
+
const searchMatch = this.matchSearchStrategy(characteristics.searchStrategy, context);
|
|
558
|
+
totalMatch += searchMatch * 0.2;
|
|
559
|
+
weightSum += 0.2;
|
|
560
|
+
|
|
561
|
+
return weightSum > 0 ? totalMatch / weightSum : 0;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Match decision making style to context needs
|
|
566
|
+
* @param {string} style - Decision making style
|
|
567
|
+
* @param {number} systematicNeed - Need for systematic approach (0-1)
|
|
568
|
+
*/
|
|
569
|
+
matchDecisionStyle(style, systematicNeed) {
|
|
570
|
+
const styleScores = {
|
|
571
|
+
'decisive': 0.9,
|
|
572
|
+
'analytical': 0.8,
|
|
573
|
+
'systematic': 0.8,
|
|
574
|
+
'principled': 0.7,
|
|
575
|
+
'exploratory': 0.3,
|
|
576
|
+
'innovative': 0.2,
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
const styleScore = styleScores[style] || 0.5;
|
|
580
|
+
return 1 - Math.abs(styleScore - systematicNeed);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Match pattern recognition approach to context
|
|
585
|
+
* @param {string} approach - Pattern recognition approach
|
|
586
|
+
* @param {Object} context - Context object
|
|
587
|
+
*/
|
|
588
|
+
matchPatternRecognition(approach, context) {
|
|
589
|
+
const approachScores = {
|
|
590
|
+
'exact_match': context.patternRegularity,
|
|
591
|
+
'flexible_match': 1 - context.patternRegularity,
|
|
592
|
+
'analogical': context.abstractionLevel,
|
|
593
|
+
'pattern_networks': context.dataComplexity,
|
|
594
|
+
'evidence_based': 1 - context.noiseLevel,
|
|
595
|
+
'abstraction_layers': context.abstractionLevel,
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
return approachScores[approach] || 0.5;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Match search strategy to context
|
|
603
|
+
* @param {string} strategy - Search strategy
|
|
604
|
+
* @param {Object} context - Context object
|
|
605
|
+
*/
|
|
606
|
+
matchSearchStrategy(strategy, context) {
|
|
607
|
+
const strategyScores = {
|
|
608
|
+
'directed': 1 - context.creativity_required,
|
|
609
|
+
'random': context.creativity_required,
|
|
610
|
+
'lateral': context.noiseLevel + context.creativity_required,
|
|
611
|
+
'holistic': context.dataComplexity,
|
|
612
|
+
'systematic': context.patternRegularity,
|
|
613
|
+
'conceptual': context.abstractionLevel,
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
return Math.min(1, strategyScores[strategy] || 0.5);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Get historical performance of a pattern for an agent
|
|
621
|
+
* @param {string} agentId - Agent identifier
|
|
622
|
+
* @param {string} patternType - Pattern type
|
|
623
|
+
*/
|
|
624
|
+
getHistoricalPerformance(agentId, patternType) {
|
|
625
|
+
const history = this.evolutionHistory.get(agentId) || [];
|
|
626
|
+
const patternHistory = history.filter(h => h.oldPatterns.includes(patternType) || h.newPatterns.includes(patternType));
|
|
627
|
+
|
|
628
|
+
if (patternHistory.length === 0) {
|
|
629
|
+
return 0.5;
|
|
630
|
+
} // Default neutral score
|
|
631
|
+
|
|
632
|
+
// Calculate average effectiveness from historical data
|
|
633
|
+
const totalEffectiveness = patternHistory.reduce((sum, h) => {
|
|
634
|
+
const effectiveness = h.effectiveness?.[patternType]?.overall || 0.5;
|
|
635
|
+
return sum + effectiveness;
|
|
636
|
+
}, 0);
|
|
637
|
+
|
|
638
|
+
return totalEffectiveness / patternHistory.length;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Get adaptation success rate for a pattern
|
|
643
|
+
* @param {string} agentId - Agent identifier
|
|
644
|
+
* @param {string} patternType - Pattern type
|
|
645
|
+
*/
|
|
646
|
+
getAdaptationSuccess(agentId, patternType) {
|
|
647
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
648
|
+
if (!agentData) {
|
|
649
|
+
return 0.5;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const adaptations = agentData.adaptationHistory.filter(a => a.patternType === patternType);
|
|
653
|
+
if (adaptations.length === 0) {
|
|
654
|
+
return 0.5;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const successfulAdaptations = adaptations.filter(a => a.success).length;
|
|
658
|
+
return successfulAdaptations / adaptations.length;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Assess if cognitive evolution is needed
|
|
663
|
+
* @param {Object} effectiveness - Pattern effectiveness scores
|
|
664
|
+
* @param {Object} context - Current context
|
|
665
|
+
*/
|
|
666
|
+
assessEvolutionNeed(effectiveness, context) {
|
|
667
|
+
const avgEffectiveness = Object.values(effectiveness).reduce((sum, e) => sum + e.overall, 0) / Object.keys(effectiveness).length;
|
|
668
|
+
|
|
669
|
+
// Evolution needed if effectiveness is low
|
|
670
|
+
if (avgEffectiveness < 0.4) {
|
|
671
|
+
return { required: true, reason: 'low_effectiveness', urgency: 'high' };
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// Evolution needed if context has changed significantly
|
|
675
|
+
if (context.dataComplexity > 0.8 && avgEffectiveness < 0.6) {
|
|
676
|
+
return { required: true, reason: 'high_complexity', urgency: 'medium' };
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// Evolution for exploration if effectiveness is moderate
|
|
680
|
+
if (avgEffectiveness < 0.7 && context.creativity_required > 0.6) {
|
|
681
|
+
return { required: true, reason: 'creativity_required', urgency: 'low' };
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
return { required: false, reason: 'stable', urgency: 'none' };
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Select evolution strategy based on need and context
|
|
689
|
+
* @param {Object} evolutionNeed - Evolution need assessment
|
|
690
|
+
* @param {Object} context - Current context
|
|
691
|
+
*/
|
|
692
|
+
selectEvolutionStrategy(evolutionNeed, context) {
|
|
693
|
+
const strategies = {
|
|
694
|
+
'pattern_addition': {
|
|
695
|
+
type: 'pattern_addition',
|
|
696
|
+
description: 'Add new cognitive patterns',
|
|
697
|
+
priority: context.creativity_required > 0.6 ? 0.8 : 0.4,
|
|
698
|
+
},
|
|
699
|
+
'pattern_removal': {
|
|
700
|
+
type: 'pattern_removal',
|
|
701
|
+
description: 'Remove ineffective patterns',
|
|
702
|
+
priority: evolutionNeed.urgency === 'high' ? 0.9 : 0.3,
|
|
703
|
+
},
|
|
704
|
+
'pattern_modification': {
|
|
705
|
+
type: 'pattern_modification',
|
|
706
|
+
description: 'Modify existing patterns',
|
|
707
|
+
priority: 0.6,
|
|
708
|
+
},
|
|
709
|
+
'pattern_rebalancing': {
|
|
710
|
+
type: 'pattern_rebalancing',
|
|
711
|
+
description: 'Rebalance pattern weights',
|
|
712
|
+
priority: evolutionNeed.urgency === 'medium' ? 0.7 : 0.5,
|
|
713
|
+
},
|
|
714
|
+
'pattern_hybridization': {
|
|
715
|
+
type: 'pattern_hybridization',
|
|
716
|
+
description: 'Create hybrid patterns',
|
|
717
|
+
priority: context.dataComplexity > 0.7 ? 0.8 : 0.3,
|
|
718
|
+
},
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
// Select strategy with highest priority
|
|
722
|
+
const selectedStrategy = Object.values(strategies).reduce((best, current) =>
|
|
723
|
+
current.priority > best.priority ? current : best,
|
|
724
|
+
);
|
|
725
|
+
|
|
726
|
+
return selectedStrategy;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Apply evolution strategy to agent patterns
|
|
731
|
+
* @param {string} agentId - Agent identifier
|
|
732
|
+
* @param {Object} strategy - Evolution strategy
|
|
733
|
+
* @param {Object} context - Current context
|
|
734
|
+
*/
|
|
735
|
+
async applyEvolution(agentId, strategy, context) {
|
|
736
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
737
|
+
if (!agentData) {
|
|
738
|
+
return [];
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
let newPatterns = [...agentData.activePatterns];
|
|
742
|
+
|
|
743
|
+
switch (strategy.type) {
|
|
744
|
+
case 'pattern_addition':
|
|
745
|
+
newPatterns = await this.addPatterns(agentId, newPatterns, context);
|
|
746
|
+
break;
|
|
747
|
+
|
|
748
|
+
case 'pattern_removal':
|
|
749
|
+
newPatterns = await this.removePatterns(agentId, newPatterns, context);
|
|
750
|
+
break;
|
|
751
|
+
|
|
752
|
+
case 'pattern_modification':
|
|
753
|
+
newPatterns = await this.modifyPatterns(agentId, newPatterns, context);
|
|
754
|
+
break;
|
|
755
|
+
|
|
756
|
+
case 'pattern_rebalancing':
|
|
757
|
+
newPatterns = await this.rebalancePatterns(agentId, newPatterns, context);
|
|
758
|
+
break;
|
|
759
|
+
|
|
760
|
+
case 'pattern_hybridization':
|
|
761
|
+
newPatterns = await this.hybridizePatterns(agentId, newPatterns, context);
|
|
762
|
+
break;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// Update agent patterns
|
|
766
|
+
agentData.activePatterns = newPatterns;
|
|
767
|
+
agentData.dominantPattern = this.selectDominantPattern(newPatterns, context);
|
|
768
|
+
agentData.lastEvolution = Date.now();
|
|
769
|
+
agentData.evolutionScore += 1;
|
|
770
|
+
|
|
771
|
+
// Update metrics
|
|
772
|
+
const metrics = this.evolutionMetrics.get(agentId);
|
|
773
|
+
if (metrics) {
|
|
774
|
+
metrics.totalEvolutions++;
|
|
775
|
+
if (strategy.type === 'pattern_addition') {
|
|
776
|
+
metrics.patternSwitches++;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
return newPatterns;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* Add new cognitive patterns
|
|
785
|
+
* @param {string} agentId - Agent identifier
|
|
786
|
+
* @param {Array} currentPatterns - Current patterns
|
|
787
|
+
* @param {Object} context - Current context
|
|
788
|
+
*/
|
|
789
|
+
async addPatterns(agentId, currentPatterns, context) {
|
|
790
|
+
const availablePatterns = Array.from(this.patternTemplates.keys());
|
|
791
|
+
const unusedPatterns = availablePatterns.filter(p => !currentPatterns.includes(p));
|
|
792
|
+
|
|
793
|
+
if (unusedPatterns.length === 0) {
|
|
794
|
+
return currentPatterns;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// Select best pattern to add based on context
|
|
798
|
+
let bestPattern = null;
|
|
799
|
+
let bestScore = 0;
|
|
800
|
+
|
|
801
|
+
for (const pattern of unusedPatterns) {
|
|
802
|
+
const template = this.patternTemplates.get(pattern);
|
|
803
|
+
const score = this.calculateContextMatch(template, context);
|
|
804
|
+
|
|
805
|
+
if (score > bestScore) {
|
|
806
|
+
bestScore = score;
|
|
807
|
+
bestPattern = pattern;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
if (bestPattern && bestScore > 0.6) {
|
|
812
|
+
return [...currentPatterns, bestPattern];
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
return currentPatterns;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Remove ineffective cognitive patterns
|
|
820
|
+
* @param {string} agentId - Agent identifier
|
|
821
|
+
* @param {Array} currentPatterns - Current patterns
|
|
822
|
+
* @param {Object} context - Current context
|
|
823
|
+
*/
|
|
824
|
+
async removePatterns(agentId, currentPatterns, context) {
|
|
825
|
+
if (currentPatterns.length <= 1) {
|
|
826
|
+
return currentPatterns;
|
|
827
|
+
} // Keep at least one pattern
|
|
828
|
+
|
|
829
|
+
// Find least effective pattern
|
|
830
|
+
let worstPattern = null;
|
|
831
|
+
let worstScore = 1;
|
|
832
|
+
|
|
833
|
+
for (const pattern of currentPatterns) {
|
|
834
|
+
const template = this.patternTemplates.get(pattern);
|
|
835
|
+
const score = this.calculateContextMatch(template, context);
|
|
836
|
+
|
|
837
|
+
if (score < worstScore) {
|
|
838
|
+
worstScore = score;
|
|
839
|
+
worstPattern = pattern;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
if (worstPattern && worstScore < 0.3) {
|
|
844
|
+
return currentPatterns.filter(p => p !== worstPattern);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
return currentPatterns;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Modify existing patterns (create adaptive variants)
|
|
852
|
+
* @param {string} agentId - Agent identifier
|
|
853
|
+
* @param {Array} currentPatterns - Current patterns
|
|
854
|
+
* @param {Object} context - Current context
|
|
855
|
+
*/
|
|
856
|
+
async modifyPatterns(agentId, currentPatterns, context) {
|
|
857
|
+
// Create modified versions of existing patterns
|
|
858
|
+
const modifiedPatterns = [];
|
|
859
|
+
|
|
860
|
+
for (const pattern of currentPatterns) {
|
|
861
|
+
const template = this.patternTemplates.get(pattern);
|
|
862
|
+
if (!template) {
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// Create adaptive modification
|
|
867
|
+
const modifiedPattern = `${pattern}_adaptive_${Date.now()}`;
|
|
868
|
+
const modifiedTemplate = this.createAdaptiveVariant(template, context);
|
|
869
|
+
|
|
870
|
+
this.patternTemplates.set(modifiedPattern, modifiedTemplate);
|
|
871
|
+
modifiedPatterns.push(modifiedPattern);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
return modifiedPatterns.length > 0 ? modifiedPatterns : currentPatterns;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* Create adaptive variant of a pattern template
|
|
879
|
+
* @param {Object} template - Original template
|
|
880
|
+
* @param {Object} context - Current context
|
|
881
|
+
*/
|
|
882
|
+
createAdaptiveVariant(template, context) {
|
|
883
|
+
const adaptiveTemplate = JSON.parse(JSON.stringify(template)); // Deep copy
|
|
884
|
+
|
|
885
|
+
// Adapt characteristics based on context
|
|
886
|
+
if (context.creativity_required > 0.7) {
|
|
887
|
+
adaptiveTemplate.characteristics.explorationRate = Math.min(1, adaptiveTemplate.characteristics.explorationRate + 0.2);
|
|
888
|
+
adaptiveTemplate.characteristics.exploitationRate = Math.max(0, adaptiveTemplate.characteristics.exploitationRate - 0.2);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
if (context.dataComplexity > 0.8) {
|
|
892
|
+
adaptiveTemplate.characteristics.patternRecognition = 'pattern_networks';
|
|
893
|
+
adaptiveTemplate.characteristics.searchStrategy = 'systematic';
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
if (context.noiseLevel > 0.6) {
|
|
897
|
+
adaptiveTemplate.characteristics.decisionMaking = 'exploratory';
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
adaptiveTemplate.name += ' (Adaptive)';
|
|
901
|
+
adaptiveTemplate.description += ' - Adapted for current context';
|
|
902
|
+
|
|
903
|
+
return adaptiveTemplate;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* Rebalance pattern priorities and weights
|
|
908
|
+
* @param {string} agentId - Agent identifier
|
|
909
|
+
* @param {Array} currentPatterns - Current patterns
|
|
910
|
+
* @param {Object} context - Current context
|
|
911
|
+
*/
|
|
912
|
+
async rebalancePatterns(agentId, currentPatterns, context) {
|
|
913
|
+
// Rebalancing keeps the same patterns but changes their relative importance
|
|
914
|
+
// This would typically involve adjusting weights in the neural network
|
|
915
|
+
// For now, we reorder patterns by effectiveness
|
|
916
|
+
|
|
917
|
+
const patternScores = [];
|
|
918
|
+
|
|
919
|
+
for (const pattern of currentPatterns) {
|
|
920
|
+
const template = this.patternTemplates.get(pattern);
|
|
921
|
+
const score = this.calculateContextMatch(template, context);
|
|
922
|
+
patternScores.push({ pattern, score });
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
// Sort by score (descending)
|
|
926
|
+
patternScores.sort((a, b) => b.score - a.score);
|
|
927
|
+
|
|
928
|
+
return patternScores.map(ps => ps.pattern);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Create hybrid patterns by combining existing ones
|
|
933
|
+
* @param {string} agentId - Agent identifier
|
|
934
|
+
* @param {Array} currentPatterns - Current patterns
|
|
935
|
+
* @param {Object} context - Current context
|
|
936
|
+
*/
|
|
937
|
+
async hybridizePatterns(agentId, currentPatterns, context) {
|
|
938
|
+
if (currentPatterns.length < 2) {
|
|
939
|
+
return currentPatterns;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// Create hybrid of two best patterns
|
|
943
|
+
const hybridPattern = `hybrid_${currentPatterns[0]}_${currentPatterns[1]}_${Date.now()}`;
|
|
944
|
+
const template1 = this.patternTemplates.get(currentPatterns[0]);
|
|
945
|
+
const template2 = this.patternTemplates.get(currentPatterns[1]);
|
|
946
|
+
|
|
947
|
+
if (!template1 || !template2) {
|
|
948
|
+
return currentPatterns;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
const hybridTemplate = this.createHybridTemplate(template1, template2, context);
|
|
952
|
+
this.patternTemplates.set(hybridPattern, hybridTemplate);
|
|
953
|
+
|
|
954
|
+
return [hybridPattern, ...currentPatterns.slice(2)];
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* Create hybrid template from two parent templates
|
|
959
|
+
* @param {Object} template1 - First parent template
|
|
960
|
+
* @param {Object} template2 - Second parent template
|
|
961
|
+
* @param {Object} context - Current context
|
|
962
|
+
*/
|
|
963
|
+
createHybridTemplate(template1, template2, context) {
|
|
964
|
+
const hybrid = {
|
|
965
|
+
name: `Hybrid: ${template1.name} + ${template2.name}`,
|
|
966
|
+
description: `Combination of ${template1.name.toLowerCase()} and ${template2.name.toLowerCase()}`,
|
|
967
|
+
characteristics: {},
|
|
968
|
+
adaptationRules: {},
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
// Blend characteristics
|
|
972
|
+
const chars1 = template1.characteristics;
|
|
973
|
+
const chars2 = template2.characteristics;
|
|
974
|
+
|
|
975
|
+
hybrid.characteristics = {
|
|
976
|
+
searchStrategy: context.creativity_required > 0.5 ? chars2.searchStrategy : chars1.searchStrategy,
|
|
977
|
+
explorationRate: (chars1.explorationRate + chars2.explorationRate) / 2,
|
|
978
|
+
exploitationRate: (chars1.exploitationRate + chars2.exploitationRate) / 2,
|
|
979
|
+
decisionMaking: context.dataComplexity > 0.6 ? chars1.decisionMaking : chars2.decisionMaking,
|
|
980
|
+
patternRecognition: chars1.patternRecognition, // Use first template's approach
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
// Combine adaptation rules
|
|
984
|
+
hybrid.adaptationRules = {
|
|
985
|
+
...template1.adaptationRules,
|
|
986
|
+
...template2.adaptationRules,
|
|
987
|
+
};
|
|
988
|
+
|
|
989
|
+
return hybrid;
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* Select dominant pattern from active patterns
|
|
994
|
+
* @param {Array} patterns - Active patterns
|
|
995
|
+
* @param {Object} context - Current context
|
|
996
|
+
*/
|
|
997
|
+
selectDominantPattern(patterns, context) {
|
|
998
|
+
if (patterns.length === 0) {
|
|
999
|
+
return 'convergent';
|
|
1000
|
+
}
|
|
1001
|
+
if (patterns.length === 1) {
|
|
1002
|
+
return patterns[0];
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// Select pattern that best matches current context
|
|
1006
|
+
let bestPattern = patterns[0];
|
|
1007
|
+
let bestScore = 0;
|
|
1008
|
+
|
|
1009
|
+
for (const pattern of patterns) {
|
|
1010
|
+
const template = this.patternTemplates.get(pattern);
|
|
1011
|
+
if (!template) {
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
const score = this.calculateContextMatch(template, context);
|
|
1016
|
+
if (score > bestScore) {
|
|
1017
|
+
bestScore = score;
|
|
1018
|
+
bestPattern = pattern;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
return bestPattern;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* Record evolution event
|
|
1027
|
+
* @param {string} agentId - Agent identifier
|
|
1028
|
+
* @param {Object} evolution - Evolution details
|
|
1029
|
+
*/
|
|
1030
|
+
recordEvolution(agentId, evolution) {
|
|
1031
|
+
const history = this.evolutionHistory.get(agentId) || [];
|
|
1032
|
+
history.push(evolution);
|
|
1033
|
+
|
|
1034
|
+
// Keep only recent evolution history (last 50 events)
|
|
1035
|
+
if (history.length > 50) {
|
|
1036
|
+
history.splice(0, history.length - 50);
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
this.evolutionHistory.set(agentId, history);
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/**
|
|
1043
|
+
* Enable cross-agent pattern evolution
|
|
1044
|
+
* @param {Array} agentIds - List of agent IDs
|
|
1045
|
+
* @param {Object} session - Collaborative session
|
|
1046
|
+
*/
|
|
1047
|
+
async enableCrossAgentEvolution(agentIds, session) {
|
|
1048
|
+
// Create cross-agent pattern exchange matrix
|
|
1049
|
+
const exchangeMatrix = {};
|
|
1050
|
+
|
|
1051
|
+
for (const agentId of agentIds) {
|
|
1052
|
+
exchangeMatrix[agentId] = new Map();
|
|
1053
|
+
|
|
1054
|
+
// Initialize exchange relationships
|
|
1055
|
+
for (const otherAgentId of agentIds) {
|
|
1056
|
+
if (agentId !== otherAgentId) {
|
|
1057
|
+
exchangeMatrix[agentId].set(otherAgentId, {
|
|
1058
|
+
lastExchange: 0,
|
|
1059
|
+
exchangeCount: 0,
|
|
1060
|
+
successRate: 0.5,
|
|
1061
|
+
patternCompatibility: 0.5,
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
this.crossAgentPatterns.set(session.id, exchangeMatrix);
|
|
1068
|
+
|
|
1069
|
+
console.log(`Cross-agent pattern evolution enabled for ${agentIds.length} agents`);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* Transfer patterns between agents
|
|
1074
|
+
* @param {string} targetAgentId - Target agent ID
|
|
1075
|
+
* @param {Array} patterns - Patterns to transfer
|
|
1076
|
+
*/
|
|
1077
|
+
async transferPatterns(targetAgentId, patterns) {
|
|
1078
|
+
const targetData = this.agentPatterns.get(targetAgentId);
|
|
1079
|
+
if (!targetData) {
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// Evaluate pattern compatibility
|
|
1084
|
+
const compatiblePatterns = [];
|
|
1085
|
+
|
|
1086
|
+
for (const pattern of patterns) {
|
|
1087
|
+
const compatibility = await this.evaluatePatternCompatibility(targetAgentId, pattern);
|
|
1088
|
+
|
|
1089
|
+
if (compatibility > 0.6) {
|
|
1090
|
+
compatiblePatterns.push(pattern);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// Transfer compatible patterns
|
|
1095
|
+
if (compatiblePatterns.length > 0) {
|
|
1096
|
+
targetData.activePatterns = [...new Set([...targetData.activePatterns, ...compatiblePatterns])];
|
|
1097
|
+
|
|
1098
|
+
// Update metrics
|
|
1099
|
+
const metrics = this.evolutionMetrics.get(targetAgentId);
|
|
1100
|
+
if (metrics) {
|
|
1101
|
+
metrics.crossAgentTransfers += compatiblePatterns.length;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
console.log(`Transferred ${compatiblePatterns.length} patterns to agent ${targetAgentId}`);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* Evaluate pattern compatibility with target agent
|
|
1110
|
+
* @param {string} agentId - Target agent ID
|
|
1111
|
+
* @param {Object} pattern - Pattern to evaluate
|
|
1112
|
+
*/
|
|
1113
|
+
async evaluatePatternCompatibility(agentId, pattern) {
|
|
1114
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
1115
|
+
if (!agentData) {
|
|
1116
|
+
return 0;
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// Check if pattern type is already present
|
|
1120
|
+
if (agentData.activePatterns.includes(pattern.type)) {
|
|
1121
|
+
return 0.3; // Low compatibility if already present
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// Evaluate based on agent's current pattern mix
|
|
1125
|
+
const currentPatternTypes = agentData.activePatterns.map(p => p.split('_')[0]);
|
|
1126
|
+
const patternType = pattern.type?.split('_')[0] || 'unknown';
|
|
1127
|
+
|
|
1128
|
+
// Check for complementary patterns
|
|
1129
|
+
const complementaryPatterns = {
|
|
1130
|
+
'convergent': ['divergent', 'lateral'],
|
|
1131
|
+
'divergent': ['convergent', 'critical'],
|
|
1132
|
+
'lateral': ['systems', 'convergent'],
|
|
1133
|
+
'systems': ['lateral', 'abstract'],
|
|
1134
|
+
'critical': ['divergent', 'abstract'],
|
|
1135
|
+
'abstract': ['critical', 'systems'],
|
|
1136
|
+
};
|
|
1137
|
+
|
|
1138
|
+
const complements = complementaryPatterns[patternType] || [];
|
|
1139
|
+
const hasComplement = currentPatternTypes.some(ct => complements.includes(ct));
|
|
1140
|
+
|
|
1141
|
+
return hasComplement ? 0.8 : 0.5;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* Extract patterns from agent for sharing
|
|
1146
|
+
* @param {string} agentId - Agent identifier
|
|
1147
|
+
*/
|
|
1148
|
+
async extractPatterns(agentId) {
|
|
1149
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
1150
|
+
if (!agentData) {
|
|
1151
|
+
return [];
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
const extractedPatterns = [];
|
|
1155
|
+
|
|
1156
|
+
for (const patternType of agentData.activePatterns) {
|
|
1157
|
+
const template = this.patternTemplates.get(patternType);
|
|
1158
|
+
if (!template) {
|
|
1159
|
+
continue;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
extractedPatterns.push({
|
|
1163
|
+
type: patternType,
|
|
1164
|
+
template,
|
|
1165
|
+
effectiveness: this.getHistoricalPerformance(agentId, patternType),
|
|
1166
|
+
adaptationHistory: agentData.adaptationHistory.filter(a => a.patternType === patternType),
|
|
1167
|
+
dominance: patternType === agentData.dominantPattern ? 1.0 : 0.5,
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
return extractedPatterns;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Apply pattern updates from coordination
|
|
1176
|
+
* @param {string} agentId - Agent identifier
|
|
1177
|
+
* @param {Array} patternUpdates - Pattern updates
|
|
1178
|
+
*/
|
|
1179
|
+
async applyPatternUpdates(agentId, patternUpdates) {
|
|
1180
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
1181
|
+
if (!agentData) {
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
for (const update of patternUpdates) {
|
|
1186
|
+
if (update.type === 'add_pattern') {
|
|
1187
|
+
if (!agentData.activePatterns.includes(update.pattern)) {
|
|
1188
|
+
agentData.activePatterns.push(update.pattern);
|
|
1189
|
+
}
|
|
1190
|
+
} else if (update.type === 'remove_pattern') {
|
|
1191
|
+
agentData.activePatterns = agentData.activePatterns.filter(p => p !== update.pattern);
|
|
1192
|
+
} else if (update.type === 'modify_pattern') {
|
|
1193
|
+
// Apply modifications to pattern template
|
|
1194
|
+
const template = this.patternTemplates.get(update.pattern);
|
|
1195
|
+
if (template && update.modifications) {
|
|
1196
|
+
Object.assign(template.characteristics, update.modifications);
|
|
1197
|
+
}
|
|
1198
|
+
} else if (update.type === 'set_dominant') {
|
|
1199
|
+
agentData.dominantPattern = update.pattern;
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// Ensure at least one pattern remains active
|
|
1204
|
+
if (agentData.activePatterns.length === 0) {
|
|
1205
|
+
agentData.activePatterns.push('convergent');
|
|
1206
|
+
agentData.dominantPattern = 'convergent';
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/**
|
|
1211
|
+
* Calculate aggregation weights for gradient coordination
|
|
1212
|
+
* @param {Array} gradients - Array of gradient sets
|
|
1213
|
+
*/
|
|
1214
|
+
calculateAggregationWeights(gradients) {
|
|
1215
|
+
// Weight gradients based on cognitive pattern effectiveness
|
|
1216
|
+
const weights = new Array(gradients.length).fill(1 / gradients.length);
|
|
1217
|
+
|
|
1218
|
+
// This would typically incorporate pattern effectiveness scores
|
|
1219
|
+
// For now, return uniform weights
|
|
1220
|
+
return weights;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/**
|
|
1224
|
+
* Assess cognitive growth for an agent
|
|
1225
|
+
* @param {string} agentId - Agent identifier
|
|
1226
|
+
*/
|
|
1227
|
+
async assessGrowth(agentId) {
|
|
1228
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
1229
|
+
const metrics = this.evolutionMetrics.get(agentId);
|
|
1230
|
+
|
|
1231
|
+
if (!agentData || !metrics) {
|
|
1232
|
+
return 0;
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
const growth = {
|
|
1236
|
+
patternDiversity: agentData.activePatterns.length / 6, // Normalize by max patterns
|
|
1237
|
+
evolutionFrequency: metrics.totalEvolutions / Math.max(1, (Date.now() - agentData.lastEvolution) / (24 * 60 * 60 * 1000)),
|
|
1238
|
+
adaptationSuccess: metrics.successfulAdaptations / Math.max(1, metrics.totalEvolutions),
|
|
1239
|
+
crossAgentLearning: metrics.crossAgentTransfers / Math.max(1, metrics.totalEvolutions),
|
|
1240
|
+
emergentPatterns: metrics.emergentPatterns / Math.max(1, metrics.totalEvolutions),
|
|
1241
|
+
};
|
|
1242
|
+
|
|
1243
|
+
// Calculate overall growth score
|
|
1244
|
+
const overallGrowth = (
|
|
1245
|
+
growth.patternDiversity * 0.2 +
|
|
1246
|
+
growth.evolutionFrequency * 0.2 +
|
|
1247
|
+
growth.adaptationSuccess * 0.3 +
|
|
1248
|
+
growth.crossAgentLearning * 0.15 +
|
|
1249
|
+
growth.emergentPatterns * 0.15
|
|
1250
|
+
);
|
|
1251
|
+
|
|
1252
|
+
return Math.min(1, overallGrowth);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/**
|
|
1256
|
+
* Get statistics for the cognitive evolution system
|
|
1257
|
+
*/
|
|
1258
|
+
getStatistics() {
|
|
1259
|
+
const totalAgents = this.agentPatterns.size;
|
|
1260
|
+
let totalEvolutions = 0;
|
|
1261
|
+
let totalPatterns = 0;
|
|
1262
|
+
const avgGrowthScore = 0;
|
|
1263
|
+
|
|
1264
|
+
for (const [agentId, metrics] of this.evolutionMetrics.entries()) {
|
|
1265
|
+
totalEvolutions += metrics.totalEvolutions;
|
|
1266
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
1267
|
+
if (agentData) {
|
|
1268
|
+
totalPatterns += agentData.activePatterns.length;
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
return {
|
|
1273
|
+
totalAgents,
|
|
1274
|
+
totalEvolutions,
|
|
1275
|
+
avgPatternsPerAgent: totalAgents > 0 ? totalPatterns / totalAgents : 0,
|
|
1276
|
+
availablePatternTypes: this.patternTemplates.size,
|
|
1277
|
+
crossAgentSessions: this.crossAgentPatterns.size,
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
/**
|
|
1282
|
+
* Preserve cognitive evolution history before agent reset
|
|
1283
|
+
* @param {string} agentId - Agent identifier
|
|
1284
|
+
*/
|
|
1285
|
+
async preserveHistory(agentId) {
|
|
1286
|
+
const agentData = this.agentPatterns.get(agentId);
|
|
1287
|
+
const history = this.evolutionHistory.get(agentId);
|
|
1288
|
+
const metrics = this.evolutionMetrics.get(agentId);
|
|
1289
|
+
|
|
1290
|
+
return {
|
|
1291
|
+
patterns: agentData ? { ...agentData } : null,
|
|
1292
|
+
history: history ? [...history] : [],
|
|
1293
|
+
metrics: metrics ? { ...metrics } : null,
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/**
|
|
1298
|
+
* Restore cognitive evolution history after agent reset
|
|
1299
|
+
* @param {string} agentId - Agent identifier
|
|
1300
|
+
* @param {Object} preservedHistory - Preserved history
|
|
1301
|
+
*/
|
|
1302
|
+
async restoreHistory(agentId, preservedHistory) {
|
|
1303
|
+
if (preservedHistory.patterns) {
|
|
1304
|
+
this.agentPatterns.set(agentId, preservedHistory.patterns);
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
if (preservedHistory.history) {
|
|
1308
|
+
this.evolutionHistory.set(agentId, preservedHistory.history);
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
if (preservedHistory.metrics) {
|
|
1312
|
+
this.evolutionMetrics.set(agentId, preservedHistory.metrics);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
export { CognitivePatternEvolution };
|