@soulcraft/brainy 1.5.0 → 2.0.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/CHANGELOG.md +188 -0
- package/LICENSE +2 -2
- package/README.md +200 -595
- package/bin/brainy-interactive.js +564 -0
- package/bin/brainy-ts.js +18 -0
- package/bin/brainy.js +672 -81
- package/dist/augmentationPipeline.d.ts +48 -220
- package/dist/augmentationPipeline.js +60 -508
- package/dist/augmentationRegistry.d.ts +22 -31
- package/dist/augmentationRegistry.js +28 -79
- package/dist/augmentations/apiServerAugmentation.d.ts +108 -0
- package/dist/augmentations/apiServerAugmentation.js +502 -0
- package/dist/augmentations/batchProcessingAugmentation.d.ts +95 -0
- package/dist/augmentations/batchProcessingAugmentation.js +567 -0
- package/dist/augmentations/brainyAugmentation.d.ts +153 -0
- package/dist/augmentations/brainyAugmentation.js +145 -0
- package/dist/augmentations/cacheAugmentation.d.ts +105 -0
- package/dist/augmentations/cacheAugmentation.js +238 -0
- package/dist/augmentations/conduitAugmentations.d.ts +54 -156
- package/dist/augmentations/conduitAugmentations.js +156 -1082
- package/dist/augmentations/connectionPoolAugmentation.d.ts +62 -0
- package/dist/augmentations/connectionPoolAugmentation.js +316 -0
- package/dist/augmentations/defaultAugmentations.d.ts +53 -0
- package/dist/augmentations/defaultAugmentations.js +88 -0
- package/dist/augmentations/entityRegistryAugmentation.d.ts +126 -0
- package/dist/augmentations/entityRegistryAugmentation.js +386 -0
- package/dist/augmentations/indexAugmentation.d.ts +117 -0
- package/dist/augmentations/indexAugmentation.js +284 -0
- package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +152 -0
- package/dist/augmentations/intelligentVerbScoringAugmentation.js +554 -0
- package/dist/augmentations/metricsAugmentation.d.ts +202 -0
- package/dist/augmentations/metricsAugmentation.js +291 -0
- package/dist/augmentations/monitoringAugmentation.d.ts +94 -0
- package/dist/augmentations/monitoringAugmentation.js +227 -0
- package/dist/augmentations/neuralImport.d.ts +50 -117
- package/dist/augmentations/neuralImport.js +255 -629
- package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +52 -0
- package/dist/augmentations/requestDeduplicatorAugmentation.js +162 -0
- package/dist/augmentations/serverSearchAugmentations.d.ts +43 -22
- package/dist/augmentations/serverSearchAugmentations.js +125 -72
- package/dist/augmentations/storageAugmentation.d.ts +54 -0
- package/dist/augmentations/storageAugmentation.js +93 -0
- package/dist/augmentations/storageAugmentations.d.ts +96 -0
- package/dist/augmentations/storageAugmentations.js +182 -0
- package/dist/augmentations/synapseAugmentation.d.ts +156 -0
- package/dist/augmentations/synapseAugmentation.js +312 -0
- package/dist/augmentations/walAugmentation.d.ts +108 -0
- package/dist/augmentations/walAugmentation.js +515 -0
- package/dist/brainyData.d.ts +404 -130
- package/dist/brainyData.js +1331 -853
- package/dist/chat/BrainyChat.d.ts +16 -8
- package/dist/chat/BrainyChat.js +60 -32
- package/dist/chat/ChatCLI.d.ts +1 -1
- package/dist/chat/ChatCLI.js +6 -6
- package/dist/cli/catalog.d.ts +3 -3
- package/dist/cli/catalog.js +116 -70
- package/dist/cli/commands/core.d.ts +61 -0
- package/dist/cli/commands/core.js +348 -0
- package/dist/cli/commands/neural.d.ts +25 -0
- package/dist/cli/commands/neural.js +508 -0
- package/dist/cli/commands/utility.d.ts +37 -0
- package/dist/cli/commands/utility.js +276 -0
- package/dist/cli/index.d.ts +7 -0
- package/dist/cli/index.js +167 -0
- package/dist/cli/interactive.d.ts +164 -0
- package/dist/cli/interactive.js +542 -0
- package/dist/cortex/neuralImport.js +5 -5
- package/dist/critical/model-guardian.js +11 -4
- package/dist/embeddings/lightweight-embedder.d.ts +23 -0
- package/dist/embeddings/lightweight-embedder.js +136 -0
- package/dist/embeddings/universal-memory-manager.d.ts +38 -0
- package/dist/embeddings/universal-memory-manager.js +206 -0
- package/dist/embeddings/worker-embedding.d.ts +7 -0
- package/dist/embeddings/worker-embedding.js +77 -0
- package/dist/embeddings/worker-manager.d.ts +28 -0
- package/dist/embeddings/worker-manager.js +162 -0
- package/dist/examples/basicUsage.js +7 -7
- package/dist/graph/pathfinding.d.ts +78 -0
- package/dist/graph/pathfinding.js +393 -0
- package/dist/hnsw/hnswIndex.d.ts +13 -0
- package/dist/hnsw/hnswIndex.js +35 -0
- package/dist/hnsw/hnswIndexOptimized.d.ts +1 -0
- package/dist/hnsw/hnswIndexOptimized.js +3 -0
- package/dist/index.d.ts +9 -11
- package/dist/index.js +21 -11
- package/dist/indices/fieldIndex.d.ts +76 -0
- package/dist/indices/fieldIndex.js +357 -0
- package/dist/mcp/brainyMCPAdapter.js +3 -2
- package/dist/mcp/mcpAugmentationToolset.js +11 -17
- package/dist/neural/embeddedPatterns.d.ts +41 -0
- package/dist/neural/embeddedPatterns.js +4044 -0
- package/dist/neural/naturalLanguageProcessor.d.ts +94 -0
- package/dist/neural/naturalLanguageProcessor.js +317 -0
- package/dist/neural/naturalLanguageProcessorStatic.d.ts +64 -0
- package/dist/neural/naturalLanguageProcessorStatic.js +151 -0
- package/dist/neural/neuralAPI.d.ts +255 -0
- package/dist/neural/neuralAPI.js +612 -0
- package/dist/neural/patternLibrary.d.ts +101 -0
- package/dist/neural/patternLibrary.js +313 -0
- package/dist/neural/patterns.d.ts +27 -0
- package/dist/neural/patterns.js +68 -0
- package/dist/neural/staticPatternMatcher.d.ts +35 -0
- package/dist/neural/staticPatternMatcher.js +153 -0
- package/dist/scripts/precomputePatternEmbeddings.d.ts +19 -0
- package/dist/scripts/precomputePatternEmbeddings.js +100 -0
- package/dist/storage/adapters/fileSystemStorage.d.ts +5 -0
- package/dist/storage/adapters/fileSystemStorage.js +20 -0
- package/dist/storage/adapters/s3CompatibleStorage.d.ts +5 -0
- package/dist/storage/adapters/s3CompatibleStorage.js +16 -0
- package/dist/storage/enhancedClearOperations.d.ts +83 -0
- package/dist/storage/enhancedClearOperations.js +345 -0
- package/dist/storage/storageFactory.js +31 -27
- package/dist/triple/TripleIntelligence.d.ts +134 -0
- package/dist/triple/TripleIntelligence.js +548 -0
- package/dist/types/augmentations.d.ts +45 -344
- package/dist/types/augmentations.js +5 -2
- package/dist/types/brainyDataInterface.d.ts +20 -10
- package/dist/types/graphTypes.d.ts +46 -0
- package/dist/types/graphTypes.js +16 -2
- package/dist/utils/BoundedRegistry.d.ts +29 -0
- package/dist/utils/BoundedRegistry.js +54 -0
- package/dist/utils/embedding.js +20 -3
- package/dist/utils/hybridModelManager.js +10 -5
- package/dist/utils/metadataFilter.d.ts +33 -19
- package/dist/utils/metadataFilter.js +58 -23
- package/dist/utils/metadataIndex.d.ts +37 -6
- package/dist/utils/metadataIndex.js +427 -64
- package/dist/utils/requestDeduplicator.d.ts +10 -0
- package/dist/utils/requestDeduplicator.js +24 -0
- package/dist/utils/unifiedCache.d.ts +103 -0
- package/dist/utils/unifiedCache.js +311 -0
- package/package.json +40 -125
- package/scripts/ensure-models.js +108 -0
- package/scripts/prepare-models.js +387 -0
- package/OFFLINE_MODELS.md +0 -56
- package/dist/intelligence/neuralEngine.d.ts +0 -207
- package/dist/intelligence/neuralEngine.js +0 -706
- package/dist/utils/modelLoader.d.ts +0 -32
- package/dist/utils/modelLoader.js +0 -219
- package/dist/utils/modelManager.d.ts +0 -77
- package/dist/utils/modelManager.js +0 -219
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Intelligent Verb Scoring Augmentation
|
|
3
|
+
*
|
|
4
|
+
* Enhances relationship quality through intelligent semantic scoring
|
|
5
|
+
* Provides context-aware relationship weights based on:
|
|
6
|
+
* - Semantic proximity of connected entities
|
|
7
|
+
* - Frequency-based amplification
|
|
8
|
+
* - Temporal decay modeling
|
|
9
|
+
* - Adaptive learning from usage patterns
|
|
10
|
+
*
|
|
11
|
+
* Critical for enterprise knowledge graphs with millions of relationships
|
|
12
|
+
*/
|
|
13
|
+
import { BaseAugmentation } from './brainyAugmentation.js';
|
|
14
|
+
export class IntelligentVerbScoringAugmentation extends BaseAugmentation {
|
|
15
|
+
// Add enabled property for backward compatibility
|
|
16
|
+
get enabled() {
|
|
17
|
+
return this.config.enabled;
|
|
18
|
+
}
|
|
19
|
+
constructor(config = {}) {
|
|
20
|
+
super();
|
|
21
|
+
this.name = 'IntelligentVerbScoring';
|
|
22
|
+
this.timing = 'around';
|
|
23
|
+
this.operations = ['addVerb', 'relate'];
|
|
24
|
+
this.priority = 10; // Enhancement feature - runs after core operations
|
|
25
|
+
this.relationshipStats = new Map();
|
|
26
|
+
this.metrics = {
|
|
27
|
+
relationshipsScored: 0,
|
|
28
|
+
averageSemanticScore: 0,
|
|
29
|
+
averageFrequencyScore: 0,
|
|
30
|
+
averageTemporalScore: 0,
|
|
31
|
+
averageConfidenceScore: 0,
|
|
32
|
+
adaptiveAdjustments: 0,
|
|
33
|
+
computationTimeMs: 0
|
|
34
|
+
};
|
|
35
|
+
this.config = {
|
|
36
|
+
enabled: config.enabled ?? true, // Smart by default!
|
|
37
|
+
// Semantic Analysis
|
|
38
|
+
enableSemanticScoring: config.enableSemanticScoring ?? true,
|
|
39
|
+
semanticThreshold: config.semanticThreshold ?? 0.3,
|
|
40
|
+
semanticWeight: config.semanticWeight ?? 0.4,
|
|
41
|
+
// Frequency Analysis
|
|
42
|
+
enableFrequencyAmplification: config.enableFrequencyAmplification ?? true,
|
|
43
|
+
frequencyDecay: config.frequencyDecay ?? 0.95, // 5% decay per occurrence
|
|
44
|
+
maxFrequencyBoost: config.maxFrequencyBoost ?? 2.0,
|
|
45
|
+
// Temporal Analysis
|
|
46
|
+
enableTemporalDecay: config.enableTemporalDecay ?? true,
|
|
47
|
+
temporalDecayRate: config.temporalDecayRate ?? 0.01, // 1% per day
|
|
48
|
+
temporalWindow: config.temporalWindow ?? 365, // 1 year
|
|
49
|
+
// Learning & Adaptation
|
|
50
|
+
enableAdaptiveLearning: config.enableAdaptiveLearning ?? true,
|
|
51
|
+
learningRate: config.learningRate ?? 0.1,
|
|
52
|
+
confidenceThreshold: config.confidenceThreshold ?? 0.3,
|
|
53
|
+
// Weight Management
|
|
54
|
+
minWeight: config.minWeight ?? 0.1,
|
|
55
|
+
maxWeight: config.maxWeight ?? 1.0,
|
|
56
|
+
baseWeight: config.baseWeight ?? 0.5
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
async onInitialize() {
|
|
60
|
+
if (this.config.enabled) {
|
|
61
|
+
this.log('Intelligent verb scoring initialized for enhanced relationship quality');
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
this.log('Intelligent verb scoring disabled');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Get this augmentation instance for API compatibility
|
|
69
|
+
* Used by BrainyData to access scoring methods
|
|
70
|
+
*/
|
|
71
|
+
getScoring() {
|
|
72
|
+
return this;
|
|
73
|
+
}
|
|
74
|
+
shouldExecute(operation, params) {
|
|
75
|
+
// For addVerb, params are passed as array: [sourceId, targetId, verbType, metadata, weight]
|
|
76
|
+
if (operation === 'addVerb' && this.config.enabled) {
|
|
77
|
+
return Array.isArray(params) && params.length >= 3;
|
|
78
|
+
}
|
|
79
|
+
// For relate method, params might be an object
|
|
80
|
+
if (operation === 'relate' && this.config.enabled) {
|
|
81
|
+
return params.sourceId && params.targetId && params.relationType;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
async execute(operation, params, next) {
|
|
86
|
+
if (!this.shouldExecute(operation, params)) {
|
|
87
|
+
return next();
|
|
88
|
+
}
|
|
89
|
+
const startTime = Date.now();
|
|
90
|
+
try {
|
|
91
|
+
let sourceId, targetId, relationType, metadata;
|
|
92
|
+
let scoringResult = null;
|
|
93
|
+
// Extract parameters based on operation type
|
|
94
|
+
if (operation === 'addVerb' && Array.isArray(params)) {
|
|
95
|
+
// addVerb params: [sourceId, targetId, verbType, metadata, weight]
|
|
96
|
+
[sourceId, targetId, relationType, metadata] = params;
|
|
97
|
+
}
|
|
98
|
+
else if (operation === 'relate') {
|
|
99
|
+
// relate params might be an object
|
|
100
|
+
sourceId = params.sourceId;
|
|
101
|
+
targetId = params.targetId;
|
|
102
|
+
relationType = params.relationType;
|
|
103
|
+
metadata = params.metadata;
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
return next();
|
|
107
|
+
}
|
|
108
|
+
// Skip if weight is already provided explicitly
|
|
109
|
+
if (Array.isArray(params) && params[4] !== undefined && params[4] !== null) {
|
|
110
|
+
return next();
|
|
111
|
+
}
|
|
112
|
+
// Get the nouns to compute scoring
|
|
113
|
+
const sourceNoun = await this.context?.brain.get(sourceId);
|
|
114
|
+
const targetNoun = await this.context?.brain.get(targetId);
|
|
115
|
+
// Compute intelligent scores with reasoning
|
|
116
|
+
scoringResult = await this.computeVerbScores(sourceNoun, targetNoun, relationType);
|
|
117
|
+
// For addVerb, modify the params array
|
|
118
|
+
if (operation === 'addVerb' && Array.isArray(params)) {
|
|
119
|
+
// Set the weight parameter (index 4)
|
|
120
|
+
params[4] = scoringResult.weight;
|
|
121
|
+
// Enhance metadata with scoring info
|
|
122
|
+
params[3] = {
|
|
123
|
+
...params[3],
|
|
124
|
+
intelligentScoring: {
|
|
125
|
+
weight: scoringResult.weight,
|
|
126
|
+
confidence: scoringResult.confidence,
|
|
127
|
+
reasoning: scoringResult.reasoning,
|
|
128
|
+
scoringMethod: this.getScoringMethodsUsed(),
|
|
129
|
+
computedAt: Date.now()
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Execute with enhanced parameters
|
|
134
|
+
const result = await next();
|
|
135
|
+
// Learn from this relationship
|
|
136
|
+
if (this.config.enableAdaptiveLearning && scoringResult) {
|
|
137
|
+
await this.updateRelationshipLearning(sourceId, targetId, relationType, scoringResult.weight);
|
|
138
|
+
}
|
|
139
|
+
// Update metrics
|
|
140
|
+
const computationTime = Date.now() - startTime;
|
|
141
|
+
if (scoringResult) {
|
|
142
|
+
this.updateMetrics(scoringResult.weight, computationTime);
|
|
143
|
+
}
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
this.log(`Intelligent verb scoring error: ${error}`, 'error');
|
|
148
|
+
// Fallback to original parameters
|
|
149
|
+
return next();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async calculateIntelligentWeight(sourceId, targetId, relationType, metadata) {
|
|
153
|
+
let finalWeight = this.config.baseWeight;
|
|
154
|
+
let scoreComponents = {};
|
|
155
|
+
// 1. Semantic Proximity Score
|
|
156
|
+
if (this.config.enableSemanticScoring) {
|
|
157
|
+
const semanticScore = await this.calculateSemanticScore(sourceId, targetId);
|
|
158
|
+
scoreComponents.semantic = semanticScore;
|
|
159
|
+
finalWeight = finalWeight * (1 + semanticScore * this.config.semanticWeight);
|
|
160
|
+
}
|
|
161
|
+
// 2. Frequency Amplification Score
|
|
162
|
+
if (this.config.enableFrequencyAmplification) {
|
|
163
|
+
const frequencyScore = this.calculateFrequencyScore(sourceId, targetId, relationType);
|
|
164
|
+
scoreComponents.frequency = frequencyScore;
|
|
165
|
+
finalWeight = finalWeight * (1 + frequencyScore);
|
|
166
|
+
}
|
|
167
|
+
// 3. Temporal Relevance Score
|
|
168
|
+
if (this.config.enableTemporalDecay) {
|
|
169
|
+
const temporalScore = this.calculateTemporalScore(sourceId, targetId, relationType);
|
|
170
|
+
scoreComponents.temporal = temporalScore;
|
|
171
|
+
finalWeight = finalWeight * temporalScore;
|
|
172
|
+
}
|
|
173
|
+
// 4. Context Awareness (from metadata)
|
|
174
|
+
const contextScore = this.calculateContextScore(metadata);
|
|
175
|
+
scoreComponents.context = contextScore;
|
|
176
|
+
finalWeight = finalWeight * (1 + contextScore * 0.2);
|
|
177
|
+
// 5. Apply constraints
|
|
178
|
+
finalWeight = Math.max(this.config.minWeight, Math.min(this.config.maxWeight, finalWeight));
|
|
179
|
+
// Store detailed scoring for analysis
|
|
180
|
+
this.storeDetailedScoring(sourceId, targetId, relationType, {
|
|
181
|
+
finalWeight,
|
|
182
|
+
components: scoreComponents,
|
|
183
|
+
timestamp: Date.now()
|
|
184
|
+
});
|
|
185
|
+
return finalWeight;
|
|
186
|
+
}
|
|
187
|
+
async calculateSemanticScore(sourceId, targetId) {
|
|
188
|
+
try {
|
|
189
|
+
// Get embeddings for both entities
|
|
190
|
+
const sourceNoun = await this.context?.brain.get(sourceId);
|
|
191
|
+
const targetNoun = await this.context?.brain.get(targetId);
|
|
192
|
+
if (!sourceNoun?.vector || !targetNoun?.vector) {
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
// Get noun types using neural detection (taxonomy-based)
|
|
196
|
+
const sourceType = await this.detectNounType(sourceNoun.vector);
|
|
197
|
+
const targetType = await this.detectNounType(targetNoun.vector);
|
|
198
|
+
// Calculate direct similarity
|
|
199
|
+
const directSimilarity = this.calculateCosineSimilarity(sourceNoun.vector, targetNoun.vector);
|
|
200
|
+
// Calculate taxonomy-based similarity boost
|
|
201
|
+
const taxonomyBoost = await this.calculateTaxonomyBoost(sourceType, targetType);
|
|
202
|
+
// Blend direct similarity with taxonomy guidance
|
|
203
|
+
// Taxonomy provides consistency while preserving flexibility
|
|
204
|
+
const semanticScore = directSimilarity * 0.7 + taxonomyBoost * 0.3;
|
|
205
|
+
return Math.min(1, Math.max(0, semanticScore));
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
return 0;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Detect noun type using neural taxonomy matching
|
|
213
|
+
*/
|
|
214
|
+
async detectNounType(vector) {
|
|
215
|
+
// Use the same neural detection as addNoun for consistency
|
|
216
|
+
if (!this.context?.brain)
|
|
217
|
+
return 'unknown';
|
|
218
|
+
try {
|
|
219
|
+
// This would normally call the brain's detectNounType method
|
|
220
|
+
// For now, simplified type detection based on vector patterns
|
|
221
|
+
const magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));
|
|
222
|
+
// Heuristic type detection (would use actual taxonomy embeddings)
|
|
223
|
+
if (magnitude > 10)
|
|
224
|
+
return 'concept';
|
|
225
|
+
if (magnitude > 5)
|
|
226
|
+
return 'entity';
|
|
227
|
+
if (magnitude > 2)
|
|
228
|
+
return 'object';
|
|
229
|
+
return 'item';
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return 'unknown';
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Calculate taxonomy-based similarity boost
|
|
237
|
+
*/
|
|
238
|
+
async calculateTaxonomyBoost(sourceType, targetType) {
|
|
239
|
+
// Define valid relationship patterns in taxonomy
|
|
240
|
+
const validPatterns = {
|
|
241
|
+
'person': { 'concept': 0.9, 'skill': 0.85, 'organization': 0.8, 'person': 0.7 },
|
|
242
|
+
'concept': { 'concept': 0.9, 'example': 0.85, 'application': 0.8 },
|
|
243
|
+
'entity': { 'entity': 0.8, 'property': 0.85, 'action': 0.75 },
|
|
244
|
+
'object': { 'object': 0.7, 'property': 0.8, 'location': 0.75 },
|
|
245
|
+
'document': { 'topic': 0.9, 'author': 0.85, 'document': 0.7 },
|
|
246
|
+
'tool': { 'output': 0.9, 'input': 0.85, 'user': 0.8 },
|
|
247
|
+
'unknown': { 'unknown': 0.5 } // Fallback
|
|
248
|
+
};
|
|
249
|
+
// Get boost from taxonomy patterns
|
|
250
|
+
const patterns = validPatterns[sourceType] || validPatterns['unknown'];
|
|
251
|
+
const boost = patterns[targetType] || 0.3; // Low score for unrecognized patterns
|
|
252
|
+
return boost;
|
|
253
|
+
}
|
|
254
|
+
calculateCosineSimilarity(vectorA, vectorB) {
|
|
255
|
+
if (vectorA.length !== vectorB.length)
|
|
256
|
+
return 0;
|
|
257
|
+
let dotProduct = 0;
|
|
258
|
+
let normA = 0;
|
|
259
|
+
let normB = 0;
|
|
260
|
+
for (let i = 0; i < vectorA.length; i++) {
|
|
261
|
+
dotProduct += vectorA[i] * vectorB[i];
|
|
262
|
+
normA += vectorA[i] * vectorA[i];
|
|
263
|
+
normB += vectorB[i] * vectorB[i];
|
|
264
|
+
}
|
|
265
|
+
const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
|
|
266
|
+
return magnitude ? dotProduct / magnitude : 0;
|
|
267
|
+
}
|
|
268
|
+
calculateFrequencyScore(sourceId, targetId, relationType) {
|
|
269
|
+
const relationshipKey = `${sourceId}:${relationType}:${targetId}`;
|
|
270
|
+
const stats = this.relationshipStats.get(relationshipKey);
|
|
271
|
+
if (!stats || stats.count <= 1)
|
|
272
|
+
return 0;
|
|
273
|
+
// Frequency boost diminishes with each occurrence
|
|
274
|
+
const frequencyBoost = Math.log(stats.count) * this.config.frequencyDecay;
|
|
275
|
+
return Math.min(this.config.maxFrequencyBoost, frequencyBoost);
|
|
276
|
+
}
|
|
277
|
+
calculateTemporalScore(sourceId, targetId, relationType) {
|
|
278
|
+
const relationshipKey = `${sourceId}:${relationType}:${targetId}`;
|
|
279
|
+
const stats = this.relationshipStats.get(relationshipKey);
|
|
280
|
+
if (!stats)
|
|
281
|
+
return 1.0; // New relationship - full temporal score
|
|
282
|
+
const daysSinceUpdate = (Date.now() - stats.lastUpdated) / (1000 * 60 * 60 * 24);
|
|
283
|
+
const decayFactor = Math.pow(1 - this.config.temporalDecayRate, daysSinceUpdate);
|
|
284
|
+
// Relationships older than temporal window get minimum score
|
|
285
|
+
if (daysSinceUpdate > this.config.temporalWindow) {
|
|
286
|
+
return this.config.minWeight / this.config.baseWeight;
|
|
287
|
+
}
|
|
288
|
+
return Math.max(0.1, decayFactor);
|
|
289
|
+
}
|
|
290
|
+
calculateContextScore(metadata) {
|
|
291
|
+
if (!metadata)
|
|
292
|
+
return 0;
|
|
293
|
+
let contextScore = 0;
|
|
294
|
+
// Boost for explicit importance
|
|
295
|
+
if (metadata.importance) {
|
|
296
|
+
contextScore += Math.min(0.5, metadata.importance);
|
|
297
|
+
}
|
|
298
|
+
// Boost for confidence
|
|
299
|
+
if (metadata.confidence) {
|
|
300
|
+
contextScore += Math.min(0.3, metadata.confidence);
|
|
301
|
+
}
|
|
302
|
+
// Boost for source quality
|
|
303
|
+
if (metadata.sourceQuality) {
|
|
304
|
+
contextScore += Math.min(0.2, metadata.sourceQuality);
|
|
305
|
+
}
|
|
306
|
+
return contextScore;
|
|
307
|
+
}
|
|
308
|
+
async updateRelationshipLearning(sourceId, targetId, relationType, weight) {
|
|
309
|
+
const relationshipKey = `${sourceId}:${relationType}:${targetId}`;
|
|
310
|
+
let stats = this.relationshipStats.get(relationshipKey);
|
|
311
|
+
if (!stats) {
|
|
312
|
+
stats = {
|
|
313
|
+
count: 0,
|
|
314
|
+
totalWeight: 0,
|
|
315
|
+
averageWeight: this.config.baseWeight,
|
|
316
|
+
lastUpdated: Date.now(),
|
|
317
|
+
semanticScore: 0,
|
|
318
|
+
frequencyScore: 0,
|
|
319
|
+
temporalScore: 1.0,
|
|
320
|
+
confidenceScore: this.config.baseWeight
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
// Update statistics with learning rate
|
|
324
|
+
stats.count++;
|
|
325
|
+
stats.totalWeight += weight;
|
|
326
|
+
stats.averageWeight = stats.averageWeight * (1 - this.config.learningRate) +
|
|
327
|
+
weight * this.config.learningRate;
|
|
328
|
+
stats.lastUpdated = Date.now();
|
|
329
|
+
// Update confidence based on consistency
|
|
330
|
+
const weightVariance = Math.abs(weight - stats.averageWeight);
|
|
331
|
+
const consistencyScore = 1 - Math.min(1, weightVariance);
|
|
332
|
+
stats.confidenceScore = stats.confidenceScore * (1 - this.config.learningRate) +
|
|
333
|
+
consistencyScore * this.config.learningRate;
|
|
334
|
+
this.relationshipStats.set(relationshipKey, stats);
|
|
335
|
+
this.metrics.adaptiveAdjustments++;
|
|
336
|
+
}
|
|
337
|
+
getConfidenceScore(sourceId, targetId, relationType) {
|
|
338
|
+
const relationshipKey = `${sourceId}:${relationType}:${targetId}`;
|
|
339
|
+
const stats = this.relationshipStats.get(relationshipKey);
|
|
340
|
+
return stats ? stats.confidenceScore : this.config.baseWeight;
|
|
341
|
+
}
|
|
342
|
+
getScoringMethodsUsed() {
|
|
343
|
+
const methods = [];
|
|
344
|
+
if (this.config.enableSemanticScoring)
|
|
345
|
+
methods.push('semantic');
|
|
346
|
+
if (this.config.enableFrequencyAmplification)
|
|
347
|
+
methods.push('frequency');
|
|
348
|
+
if (this.config.enableTemporalDecay)
|
|
349
|
+
methods.push('temporal');
|
|
350
|
+
if (this.config.enableAdaptiveLearning)
|
|
351
|
+
methods.push('adaptive');
|
|
352
|
+
return methods;
|
|
353
|
+
}
|
|
354
|
+
storeDetailedScoring(sourceId, targetId, relationType, scoring) {
|
|
355
|
+
// Store detailed scoring for analysis and debugging
|
|
356
|
+
// In production, this might be sent to analytics system
|
|
357
|
+
}
|
|
358
|
+
updateMetrics(weight, computationTime) {
|
|
359
|
+
this.metrics.relationshipsScored++;
|
|
360
|
+
this.metrics.computationTimeMs =
|
|
361
|
+
(this.metrics.computationTimeMs * (this.metrics.relationshipsScored - 1) + computationTime) /
|
|
362
|
+
this.metrics.relationshipsScored;
|
|
363
|
+
// Update score averages (simplified)
|
|
364
|
+
// In practice, we'd track these more precisely
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Get intelligent verb scoring statistics
|
|
368
|
+
*/
|
|
369
|
+
getStats() {
|
|
370
|
+
let totalConfidence = 0;
|
|
371
|
+
let highConfidenceCount = 0;
|
|
372
|
+
for (const stats of this.relationshipStats.values()) {
|
|
373
|
+
totalConfidence += stats.confidenceScore;
|
|
374
|
+
if (stats.confidenceScore >= this.config.confidenceThreshold * 2) {
|
|
375
|
+
highConfidenceCount++;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const totalRelationships = this.relationshipStats.size;
|
|
379
|
+
const averageConfidence = totalRelationships > 0 ? totalConfidence / totalRelationships : 0;
|
|
380
|
+
const learningEfficiency = this.metrics.adaptiveAdjustments / Math.max(1, this.metrics.relationshipsScored);
|
|
381
|
+
return {
|
|
382
|
+
...this.metrics,
|
|
383
|
+
totalRelationships,
|
|
384
|
+
averageConfidence,
|
|
385
|
+
highConfidenceRelationships: highConfidenceCount,
|
|
386
|
+
learningEfficiency
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Export relationship statistics for analysis
|
|
391
|
+
*/
|
|
392
|
+
exportRelationshipStats() {
|
|
393
|
+
return Array.from(this.relationshipStats.entries()).map(([key, metrics]) => ({
|
|
394
|
+
relationship: key,
|
|
395
|
+
metrics
|
|
396
|
+
}));
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Import relationship statistics from previous sessions
|
|
400
|
+
*/
|
|
401
|
+
importRelationshipStats(stats) {
|
|
402
|
+
for (const { relationship, metrics } of stats) {
|
|
403
|
+
this.relationshipStats.set(relationship, metrics);
|
|
404
|
+
}
|
|
405
|
+
this.log(`Imported ${stats.length} relationship statistics`);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Get learning statistics for monitoring and debugging
|
|
409
|
+
* Required for BrainyData.getVerbScoringStats()
|
|
410
|
+
*/
|
|
411
|
+
getLearningStats() {
|
|
412
|
+
const relationships = Array.from(this.relationshipStats.entries());
|
|
413
|
+
const totalRelationships = relationships.length;
|
|
414
|
+
const feedbackCount = relationships.reduce((sum, [, stats]) => sum + stats.count, 0);
|
|
415
|
+
const averageWeight = relationships.reduce((sum, [, stats]) => sum + stats.averageWeight, 0) / totalRelationships || 0;
|
|
416
|
+
const averageConfidence = Math.min(averageWeight + 0.2, 1.0);
|
|
417
|
+
const topRelationships = relationships
|
|
418
|
+
.map(([key, stats]) => ({
|
|
419
|
+
relationship: key,
|
|
420
|
+
count: stats.count,
|
|
421
|
+
averageWeight: stats.averageWeight
|
|
422
|
+
}))
|
|
423
|
+
.sort((a, b) => b.count - a.count)
|
|
424
|
+
.slice(0, 10);
|
|
425
|
+
return {
|
|
426
|
+
totalRelationships,
|
|
427
|
+
averageConfidence,
|
|
428
|
+
feedbackCount,
|
|
429
|
+
topRelationships
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Export learning data for backup or analysis
|
|
434
|
+
* Required for BrainyData.exportVerbScoringLearningData()
|
|
435
|
+
*/
|
|
436
|
+
exportLearningData() {
|
|
437
|
+
const data = {
|
|
438
|
+
config: this.config,
|
|
439
|
+
stats: Array.from(this.relationshipStats.entries()).map(([key, stats]) => ({
|
|
440
|
+
relationship: key,
|
|
441
|
+
...stats
|
|
442
|
+
})),
|
|
443
|
+
exportedAt: new Date().toISOString(),
|
|
444
|
+
version: '1.0'
|
|
445
|
+
};
|
|
446
|
+
return JSON.stringify(data, null, 2);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Import learning data from backup
|
|
450
|
+
* Required for BrainyData.importVerbScoringLearningData()
|
|
451
|
+
*/
|
|
452
|
+
importLearningData(jsonData) {
|
|
453
|
+
try {
|
|
454
|
+
const data = JSON.parse(jsonData);
|
|
455
|
+
if (data.stats && Array.isArray(data.stats)) {
|
|
456
|
+
for (const stat of data.stats) {
|
|
457
|
+
if (stat.relationship) {
|
|
458
|
+
this.relationshipStats.set(stat.relationship, {
|
|
459
|
+
count: stat.count || 1,
|
|
460
|
+
totalWeight: stat.totalWeight || stat.averageWeight || 0.5,
|
|
461
|
+
averageWeight: stat.averageWeight || 0.5,
|
|
462
|
+
lastUpdated: stat.lastUpdated || Date.now(),
|
|
463
|
+
semanticScore: stat.semanticScore || 0.5,
|
|
464
|
+
frequencyScore: stat.frequencyScore || 0.5,
|
|
465
|
+
temporalScore: stat.temporalScore || 1.0,
|
|
466
|
+
confidenceScore: stat.confidenceScore || 0.5
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
this.log(`Imported learning data: ${this.relationshipStats.size} relationships`);
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
console.error('Failed to import learning data:', error);
|
|
475
|
+
throw new Error(`Failed to import learning data: ${error}`);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Provide feedback on a relationship's weight
|
|
480
|
+
* Required for BrainyData.provideVerbScoringFeedback()
|
|
481
|
+
*/
|
|
482
|
+
async provideFeedback(sourceId, targetId, relationType, feedback, feedbackType = 'correction') {
|
|
483
|
+
const key = `${sourceId}-${relationType}-${targetId}`;
|
|
484
|
+
const stats = this.relationshipStats.get(key) || {
|
|
485
|
+
count: 0,
|
|
486
|
+
totalWeight: 0,
|
|
487
|
+
averageWeight: 0.5,
|
|
488
|
+
lastUpdated: Date.now(),
|
|
489
|
+
semanticScore: 0.5,
|
|
490
|
+
frequencyScore: 0.5,
|
|
491
|
+
temporalScore: 1.0,
|
|
492
|
+
confidenceScore: 0.5
|
|
493
|
+
};
|
|
494
|
+
// Update statistics based on feedback
|
|
495
|
+
if (feedbackType === 'correction') {
|
|
496
|
+
// Direct correction - heavily weight the feedback
|
|
497
|
+
stats.averageWeight = stats.averageWeight * 0.3 + feedback * 0.7;
|
|
498
|
+
}
|
|
499
|
+
else if (feedbackType === 'validation') {
|
|
500
|
+
// Validation - slightly adjust towards feedback
|
|
501
|
+
stats.averageWeight = stats.averageWeight * 0.8 + feedback * 0.2;
|
|
502
|
+
}
|
|
503
|
+
else {
|
|
504
|
+
// Enhancement - minor adjustment
|
|
505
|
+
stats.averageWeight = stats.averageWeight * 0.9 + feedback * 0.1;
|
|
506
|
+
}
|
|
507
|
+
stats.count++;
|
|
508
|
+
stats.totalWeight += feedback;
|
|
509
|
+
stats.lastUpdated = Date.now();
|
|
510
|
+
this.relationshipStats.set(key, stats);
|
|
511
|
+
this.metrics.adaptiveAdjustments++;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Compute intelligent scores for a verb relationship
|
|
515
|
+
* Used internally during verb creation
|
|
516
|
+
*/
|
|
517
|
+
async computeVerbScores(sourceNoun, targetNoun, relationType) {
|
|
518
|
+
const reasoning = [];
|
|
519
|
+
let totalScore = 0;
|
|
520
|
+
let components = 0;
|
|
521
|
+
// Semantic scoring
|
|
522
|
+
if (this.config.enableSemanticScoring && sourceNoun?.vector && targetNoun?.vector) {
|
|
523
|
+
const similarity = this.calculateCosineSimilarity(sourceNoun.vector, targetNoun.vector);
|
|
524
|
+
const semanticScore = Math.max(similarity, this.config.semanticThreshold);
|
|
525
|
+
totalScore += semanticScore * this.config.semanticWeight;
|
|
526
|
+
components++;
|
|
527
|
+
reasoning.push(`Semantic similarity: ${(similarity * 100).toFixed(1)}%`);
|
|
528
|
+
}
|
|
529
|
+
// Frequency scoring
|
|
530
|
+
const key = `${sourceNoun?.id}-${relationType}-${targetNoun?.id}`;
|
|
531
|
+
const stats = this.relationshipStats.get(key);
|
|
532
|
+
if (this.config.enableFrequencyAmplification && stats) {
|
|
533
|
+
const frequencyScore = Math.min(1 + (stats.count - 1) * 0.1, this.config.maxFrequencyBoost);
|
|
534
|
+
totalScore += frequencyScore * 0.3;
|
|
535
|
+
components++;
|
|
536
|
+
reasoning.push(`Frequency boost: ${frequencyScore.toFixed(2)}x`);
|
|
537
|
+
}
|
|
538
|
+
// Temporal decay scoring
|
|
539
|
+
if (this.config.enableTemporalDecay) {
|
|
540
|
+
reasoning.push(`Temporal decay applied (rate: ${this.config.temporalDecayRate})`);
|
|
541
|
+
}
|
|
542
|
+
// Calculate final weight
|
|
543
|
+
const weight = components > 0
|
|
544
|
+
? Math.min(Math.max(totalScore / components, this.config.minWeight), this.config.maxWeight)
|
|
545
|
+
: this.config.baseWeight;
|
|
546
|
+
const confidence = Math.min(weight + 0.2, 1.0);
|
|
547
|
+
return { weight, confidence, reasoning };
|
|
548
|
+
}
|
|
549
|
+
async onShutdown() {
|
|
550
|
+
const stats = this.getStats();
|
|
551
|
+
this.log(`Intelligent verb scoring shutdown: ${stats.relationshipsScored} relationships scored, ${Math.round(stats.averageConfidence * 100)}% avg confidence`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
//# sourceMappingURL=intelligentVerbScoringAugmentation.js.map
|