@soulcraft/brainy 3.0.0 → 3.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 +53 -3
- package/README.md +353 -110
- package/bin/brainy.js +340 -62
- package/dist/api/ConfigAPI.d.ts +67 -0
- package/dist/api/ConfigAPI.js +166 -0
- package/dist/api/DataAPI.d.ts +123 -0
- package/dist/api/DataAPI.js +391 -0
- package/dist/api/SecurityAPI.d.ts +50 -0
- package/dist/api/SecurityAPI.js +139 -0
- package/dist/api/UniversalImportAPI.d.ts +134 -0
- package/dist/api/UniversalImportAPI.js +615 -0
- package/dist/augmentationManager.js +12 -7
- package/dist/augmentationPipeline.d.ts +0 -61
- package/dist/augmentationPipeline.js +0 -87
- package/dist/augmentationRegistry.d.ts +1 -1
- package/dist/augmentationRegistry.js +1 -1
- package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
- package/dist/augmentations/apiServerAugmentation.js +290 -9
- package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
- package/dist/augmentations/auditLogAugmentation.js +358 -0
- package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
- package/dist/augmentations/batchProcessingAugmentation.js +123 -22
- package/dist/augmentations/brainyAugmentation.d.ts +142 -8
- package/dist/augmentations/brainyAugmentation.js +179 -2
- package/dist/augmentations/cacheAugmentation.d.ts +8 -5
- package/dist/augmentations/cacheAugmentation.js +116 -17
- package/dist/augmentations/conduitAugmentations.d.ts +2 -2
- package/dist/augmentations/conduitAugmentations.js +2 -2
- package/dist/augmentations/configResolver.d.ts +122 -0
- package/dist/augmentations/configResolver.js +440 -0
- package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
- package/dist/augmentations/connectionPoolAugmentation.js +37 -12
- package/dist/augmentations/defaultAugmentations.d.ts +14 -10
- package/dist/augmentations/defaultAugmentations.js +16 -11
- package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
- package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
- package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
- package/dist/augmentations/discovery/localDiscovery.js +246 -0
- package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
- package/dist/augmentations/discovery/runtimeLoader.js +337 -0
- package/dist/augmentations/discovery.d.ts +152 -0
- package/dist/augmentations/discovery.js +441 -0
- package/dist/augmentations/display/cache.d.ts +130 -0
- package/dist/augmentations/display/cache.js +319 -0
- package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
- package/dist/augmentations/display/fieldPatterns.js +393 -0
- package/dist/augmentations/display/iconMappings.d.ts +57 -0
- package/dist/augmentations/display/iconMappings.js +68 -0
- package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
- package/dist/augmentations/display/intelligentComputation.js +462 -0
- package/dist/augmentations/display/types.d.ts +203 -0
- package/dist/augmentations/display/types.js +7 -0
- package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
- package/dist/augmentations/entityRegistryAugmentation.js +5 -1
- package/dist/augmentations/indexAugmentation.d.ts +5 -3
- package/dist/augmentations/indexAugmentation.js +5 -2
- package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
- package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
- package/dist/augmentations/manifest.d.ts +176 -0
- package/dist/augmentations/manifest.js +8 -0
- package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
- package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
- package/dist/augmentations/marketplace/cli.d.ts +47 -0
- package/dist/augmentations/marketplace/cli.js +265 -0
- package/dist/augmentations/metricsAugmentation.d.ts +3 -3
- package/dist/augmentations/metricsAugmentation.js +2 -2
- package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
- package/dist/augmentations/monitoringAugmentation.js +2 -2
- package/dist/augmentations/neuralImport.d.ts +1 -1
- package/dist/augmentations/neuralImport.js +4 -4
- package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
- package/dist/augmentations/rateLimitAugmentation.js +321 -0
- package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
- package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
- package/dist/augmentations/storageAugmentation.d.ts +1 -1
- package/dist/augmentations/storageAugmentation.js +2 -2
- package/dist/augmentations/storageAugmentations.d.ts +37 -8
- package/dist/augmentations/storageAugmentations.js +204 -15
- package/dist/augmentations/synapseAugmentation.d.ts +1 -1
- package/dist/augmentations/synapseAugmentation.js +35 -16
- package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
- package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
- package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
- package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
- package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
- package/dist/augmentations/universalDisplayAugmentation.js +371 -0
- package/dist/brainy-unified.d.ts +106 -0
- package/dist/brainy-unified.js +327 -0
- package/dist/brainy.d.ts +273 -0
- package/dist/brainy.js +1181 -0
- package/dist/brainyData.d.ts +56 -111
- package/dist/brainyData.js +912 -756
- package/dist/brainyDataV3.d.ts +186 -0
- package/dist/brainyDataV3.js +337 -0
- package/dist/browserFramework.d.ts +6 -6
- package/dist/browserFramework.js +11 -8
- package/dist/browserFramework.minimal.d.ts +5 -5
- package/dist/browserFramework.minimal.js +11 -8
- package/dist/config/distributedPresets-new.d.ts +118 -0
- package/dist/config/distributedPresets-new.js +318 -0
- package/dist/config/distributedPresets.d.ts +118 -0
- package/dist/config/distributedPresets.js +318 -0
- package/dist/config/extensibleConfig.d.ts +99 -0
- package/dist/config/extensibleConfig.js +268 -0
- package/dist/config/index.d.ts +17 -0
- package/dist/config/index.js +35 -0
- package/dist/config/modelAutoConfig.d.ts +32 -0
- package/dist/config/modelAutoConfig.js +139 -0
- package/dist/config/modelPrecisionManager.d.ts +42 -0
- package/dist/config/modelPrecisionManager.js +98 -0
- package/dist/config/sharedConfigManager.d.ts +67 -0
- package/dist/config/sharedConfigManager.js +215 -0
- package/dist/config/storageAutoConfig.d.ts +41 -0
- package/dist/config/storageAutoConfig.js +328 -0
- package/dist/config/zeroConfig.d.ts +68 -0
- package/dist/config/zeroConfig.js +301 -0
- package/dist/cortex/backupRestore.d.ts +2 -2
- package/dist/cortex/backupRestore.js +85 -27
- package/dist/cortex/healthCheck.d.ts +2 -2
- package/dist/cortex/neuralImport.d.ts +2 -2
- package/dist/cortex/neuralImport.js +18 -13
- package/dist/cortex/performanceMonitor.d.ts +2 -2
- package/dist/critical/model-guardian.d.ts +4 -0
- package/dist/critical/model-guardian.js +31 -11
- package/dist/demo.d.ts +4 -4
- package/dist/demo.js +7 -7
- package/dist/distributed/cacheSync.d.ts +112 -0
- package/dist/distributed/cacheSync.js +265 -0
- package/dist/distributed/coordinator.d.ts +193 -0
- package/dist/distributed/coordinator.js +548 -0
- package/dist/distributed/httpTransport.d.ts +120 -0
- package/dist/distributed/httpTransport.js +446 -0
- package/dist/distributed/index.d.ts +8 -0
- package/dist/distributed/index.js +5 -0
- package/dist/distributed/networkTransport.d.ts +132 -0
- package/dist/distributed/networkTransport.js +633 -0
- package/dist/distributed/queryPlanner.d.ts +104 -0
- package/dist/distributed/queryPlanner.js +327 -0
- package/dist/distributed/readWriteSeparation.d.ts +134 -0
- package/dist/distributed/readWriteSeparation.js +350 -0
- package/dist/distributed/shardManager.d.ts +114 -0
- package/dist/distributed/shardManager.js +357 -0
- package/dist/distributed/shardMigration.d.ts +110 -0
- package/dist/distributed/shardMigration.js +289 -0
- package/dist/distributed/storageDiscovery.d.ts +160 -0
- package/dist/distributed/storageDiscovery.js +551 -0
- package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
- package/dist/embeddings/CachedEmbeddings.js +146 -0
- package/dist/embeddings/EmbeddingManager.d.ts +102 -0
- package/dist/embeddings/EmbeddingManager.js +291 -0
- package/dist/embeddings/SingletonModelManager.d.ts +95 -0
- package/dist/embeddings/SingletonModelManager.js +220 -0
- package/dist/embeddings/index.d.ts +12 -0
- package/dist/embeddings/index.js +16 -0
- package/dist/embeddings/lightweight-embedder.d.ts +0 -1
- package/dist/embeddings/lightweight-embedder.js +4 -12
- package/dist/embeddings/model-manager.d.ts +11 -0
- package/dist/embeddings/model-manager.js +43 -7
- package/dist/embeddings/universal-memory-manager.d.ts +1 -1
- package/dist/embeddings/universal-memory-manager.js +27 -67
- package/dist/embeddings/worker-embedding.js +4 -8
- package/dist/errors/brainyError.d.ts +5 -1
- package/dist/errors/brainyError.js +12 -0
- package/dist/examples/basicUsage.js +7 -4
- package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
- package/dist/graph/graphAdjacencyIndex.js +288 -0
- package/dist/graph/pathfinding.js +4 -2
- package/dist/hnsw/scaledHNSWSystem.js +11 -2
- package/dist/importManager.js +8 -5
- package/dist/index.d.ts +17 -22
- package/dist/index.js +37 -23
- package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
- package/dist/mcp/brainyMCPAdapter.js +5 -5
- package/dist/mcp/brainyMCPService.d.ts +3 -3
- package/dist/mcp/brainyMCPService.js +3 -11
- package/dist/mcp/mcpAugmentationToolset.js +20 -30
- package/dist/neural/embeddedPatterns.d.ts +1 -1
- package/dist/neural/embeddedPatterns.js +2 -2
- package/dist/neural/entityExtractor.d.ts +65 -0
- package/dist/neural/entityExtractor.js +316 -0
- package/dist/neural/improvedNeuralAPI.d.ts +357 -0
- package/dist/neural/improvedNeuralAPI.js +2628 -0
- package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
- package/dist/neural/naturalLanguageProcessor.js +941 -66
- package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
- package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
- package/dist/neural/neuralAPI.js +8 -2
- package/dist/neural/patternLibrary.d.ts +57 -3
- package/dist/neural/patternLibrary.js +348 -13
- package/dist/neural/staticPatternMatcher.d.ts +2 -2
- package/dist/neural/staticPatternMatcher.js +2 -2
- package/dist/neural/types.d.ts +287 -0
- package/dist/neural/types.js +24 -0
- package/dist/shared/default-augmentations.d.ts +3 -3
- package/dist/shared/default-augmentations.js +5 -5
- package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
- package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
- package/dist/storage/adapters/fileSystemStorage.js +218 -15
- package/dist/storage/adapters/memoryStorage.d.ts +4 -4
- package/dist/storage/adapters/memoryStorage.js +17 -12
- package/dist/storage/adapters/opfsStorage.d.ts +2 -2
- package/dist/storage/adapters/opfsStorage.js +2 -2
- package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
- package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
- package/dist/storage/backwardCompatibility.d.ts +10 -78
- package/dist/storage/backwardCompatibility.js +17 -132
- package/dist/storage/baseStorage.d.ts +18 -2
- package/dist/storage/baseStorage.js +74 -3
- package/dist/storage/cacheManager.js +2 -2
- package/dist/storage/readOnlyOptimizations.js +8 -3
- package/dist/streaming/pipeline.d.ts +154 -0
- package/dist/streaming/pipeline.js +551 -0
- package/dist/triple/TripleIntelligence.d.ts +25 -110
- package/dist/triple/TripleIntelligence.js +4 -574
- package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
- package/dist/triple/TripleIntelligenceSystem.js +519 -0
- package/dist/types/apiTypes.d.ts +278 -0
- package/dist/types/apiTypes.js +33 -0
- package/dist/types/brainy.types.d.ts +308 -0
- package/dist/types/brainy.types.js +8 -0
- package/dist/types/brainyDataInterface.d.ts +5 -8
- package/dist/types/brainyDataInterface.js +2 -2
- package/dist/types/graphTypes.js +2 -2
- package/dist/utils/brainyTypes.d.ts +217 -0
- package/dist/utils/brainyTypes.js +261 -0
- package/dist/utils/cacheAutoConfig.d.ts +3 -3
- package/dist/utils/embedding.d.ts +9 -4
- package/dist/utils/embedding.js +89 -26
- package/dist/utils/enhancedLogger.d.ts +104 -0
- package/dist/utils/enhancedLogger.js +232 -0
- package/dist/utils/hybridModelManager.d.ts +19 -28
- package/dist/utils/hybridModelManager.js +36 -200
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/intelligentTypeMapper.d.ts +60 -0
- package/dist/utils/intelligentTypeMapper.js +349 -0
- package/dist/utils/metadataIndex.d.ts +118 -1
- package/dist/utils/metadataIndex.js +539 -16
- package/dist/utils/nodeVersionCheck.d.ts +24 -0
- package/dist/utils/nodeVersionCheck.js +65 -0
- package/dist/utils/paramValidation.d.ts +39 -0
- package/dist/utils/paramValidation.js +192 -0
- package/dist/utils/rateLimiter.d.ts +160 -0
- package/dist/utils/rateLimiter.js +271 -0
- package/dist/utils/statistics.d.ts +4 -4
- package/dist/utils/statistics.js +3 -3
- package/dist/utils/structuredLogger.d.ts +146 -0
- package/dist/utils/structuredLogger.js +394 -0
- package/dist/utils/textEncoding.js +2 -1
- package/dist/utils/typeValidation.d.ts +59 -0
- package/dist/utils/typeValidation.js +374 -0
- package/dist/utils/version.js +19 -3
- package/package.json +15 -4
- package/scripts/download-models.cjs +94 -20
- package/dist/augmentations/walAugmentation.d.ts +0 -109
- package/dist/augmentations/walAugmentation.js +0 -516
- package/dist/chat/BrainyChat.d.ts +0 -121
- package/dist/chat/BrainyChat.js +0 -396
- package/dist/chat/ChatCLI.d.ts +0 -61
- package/dist/chat/ChatCLI.js +0 -351
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 🧠 Brainy 3.0 - UNIFIED FIND IMPLEMENTATION
|
|
3
|
+
*
|
|
4
|
+
* REAL CODE - NO MOCKS - NO STUBS - PRODUCTION READY
|
|
5
|
+
* O(log n) performance with Triple Intelligence
|
|
6
|
+
*/
|
|
7
|
+
import { v4 as uuidv4 } from './universal/uuid.js';
|
|
8
|
+
import { HNSWIndex } from './hnsw/hnswIndex.js';
|
|
9
|
+
import { createStorage } from './storage/storageFactory.js';
|
|
10
|
+
import { defaultEmbeddingFunction, cosineDistance } from './utils/index.js';
|
|
11
|
+
import { matchesMetadataFilter } from './utils/metadataFilter.js';
|
|
12
|
+
/**
|
|
13
|
+
* UNIFIED BRAINY CLASS - REAL IMPLEMENTATION
|
|
14
|
+
*/
|
|
15
|
+
export class Brainy {
|
|
16
|
+
constructor(config) {
|
|
17
|
+
this.initialized = false;
|
|
18
|
+
this.embedder = config?.embedder || defaultEmbeddingFunction;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Initialize Brainy
|
|
22
|
+
*/
|
|
23
|
+
async init() {
|
|
24
|
+
if (this.initialized)
|
|
25
|
+
return;
|
|
26
|
+
// Setup storage
|
|
27
|
+
this.storage = await createStorage({ type: 'memory' });
|
|
28
|
+
await this.storage.initialize();
|
|
29
|
+
// Setup HNSW index
|
|
30
|
+
this.index = new HNSWIndex({
|
|
31
|
+
dimensions: 384,
|
|
32
|
+
M: 16,
|
|
33
|
+
efConstruction: 200,
|
|
34
|
+
distance: cosineDistance
|
|
35
|
+
});
|
|
36
|
+
this.initialized = true;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Add entity
|
|
40
|
+
*/
|
|
41
|
+
async add(params) {
|
|
42
|
+
await this.ensureInitialized();
|
|
43
|
+
const id = params.id || uuidv4();
|
|
44
|
+
const vector = await this.embedder(JSON.stringify(params.data));
|
|
45
|
+
// Add to HNSW index
|
|
46
|
+
await this.index.addItem({ id, vector });
|
|
47
|
+
// Save to storage
|
|
48
|
+
await this.storage.saveNoun({
|
|
49
|
+
id,
|
|
50
|
+
vector,
|
|
51
|
+
data: params.data,
|
|
52
|
+
metadata: params.metadata || {},
|
|
53
|
+
type: params.type || 'entity'
|
|
54
|
+
});
|
|
55
|
+
return id;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Get entity by ID
|
|
59
|
+
*/
|
|
60
|
+
async get(id) {
|
|
61
|
+
await this.ensureInitialized();
|
|
62
|
+
const noun = await this.storage.getNoun(id);
|
|
63
|
+
return noun;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* UNIFIED FIND - Real Triple Intelligence Implementation
|
|
67
|
+
* O(log n) performance with Reciprocal Rank Fusion
|
|
68
|
+
*/
|
|
69
|
+
async find(params) {
|
|
70
|
+
await this.ensureInitialized();
|
|
71
|
+
// Parse natural language to structured query
|
|
72
|
+
if (typeof params === 'string') {
|
|
73
|
+
params = await this.parseNaturalLanguage(params);
|
|
74
|
+
}
|
|
75
|
+
// Fast path: Direct ID lookup - O(1)
|
|
76
|
+
if (params.id) {
|
|
77
|
+
const entity = await this.get(params.id);
|
|
78
|
+
return entity ? [{ id: params.id, score: 1.0, entity }] : [];
|
|
79
|
+
}
|
|
80
|
+
// Fast path: Multiple IDs - O(k)
|
|
81
|
+
if (params.ids) {
|
|
82
|
+
const entities = await Promise.all(params.ids.map(id => this.get(id)));
|
|
83
|
+
return entities
|
|
84
|
+
.filter(e => e !== null)
|
|
85
|
+
.map((entity, i) => ({
|
|
86
|
+
id: params.ids[i],
|
|
87
|
+
score: 1.0,
|
|
88
|
+
entity: entity
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
// TRIPLE INTELLIGENCE: Execute searches in parallel
|
|
92
|
+
const limit = params.limit || 10;
|
|
93
|
+
const searchLimit = Math.min(limit * 3, 100);
|
|
94
|
+
const searchPromises = [];
|
|
95
|
+
const searchTypes = [];
|
|
96
|
+
// 1. Vector Search - O(log n) via HNSW
|
|
97
|
+
if (params.query || params.near || params.vector) {
|
|
98
|
+
searchPromises.push(this.vectorSearch(params, searchLimit));
|
|
99
|
+
searchTypes.push('vector');
|
|
100
|
+
}
|
|
101
|
+
// 2. Metadata Search - O(log n) for indexed fields
|
|
102
|
+
if (params.where || params.type || params.service) {
|
|
103
|
+
searchPromises.push(this.metadataSearch(params, searchLimit));
|
|
104
|
+
searchTypes.push('metadata');
|
|
105
|
+
}
|
|
106
|
+
// 3. Graph Traversal - O(k) where k = traversal limit
|
|
107
|
+
if (params.connected) {
|
|
108
|
+
searchPromises.push(this.graphTraversal(params.connected, searchLimit));
|
|
109
|
+
searchTypes.push('graph');
|
|
110
|
+
}
|
|
111
|
+
// If no search criteria, return empty
|
|
112
|
+
if (searchPromises.length === 0) {
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
// Execute all searches in parallel
|
|
116
|
+
const searchResults = await Promise.all(searchPromises);
|
|
117
|
+
// Apply Reciprocal Rank Fusion
|
|
118
|
+
return this.reciprocalRankFusion(searchResults, searchTypes, params.limit || 10, params.offset || 0);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Search method for NLP compatibility
|
|
122
|
+
*/
|
|
123
|
+
async search(query, limit, options) {
|
|
124
|
+
if (typeof query === 'string') {
|
|
125
|
+
return this.find({ query, limit: limit || 10 });
|
|
126
|
+
}
|
|
127
|
+
const params = { ...query, limit: limit || query.limit, ...options };
|
|
128
|
+
return this.find(params);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Parse natural language query
|
|
132
|
+
*/
|
|
133
|
+
async parseNaturalLanguage(query) {
|
|
134
|
+
const params = {};
|
|
135
|
+
const lowerQuery = query.toLowerCase();
|
|
136
|
+
// Extract limit
|
|
137
|
+
const limitMatch = lowerQuery.match(/(?:top|first|limit)\s+(\d+)/i);
|
|
138
|
+
if (limitMatch) {
|
|
139
|
+
params.limit = parseInt(limitMatch[1]);
|
|
140
|
+
query = query.replace(limitMatch[0], '').trim();
|
|
141
|
+
}
|
|
142
|
+
// Detect graph traversal
|
|
143
|
+
if (lowerQuery.includes('connected to') || lowerQuery.includes('related to')) {
|
|
144
|
+
const fromMatch = query.match(/from\s+["']?([^"'\s]+)["']?/i);
|
|
145
|
+
if (fromMatch) {
|
|
146
|
+
params.connected = { from: fromMatch[1] };
|
|
147
|
+
query = query.replace(fromMatch[0], '').trim();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// Main query
|
|
151
|
+
if (query.trim()) {
|
|
152
|
+
params.query = query.trim();
|
|
153
|
+
}
|
|
154
|
+
return params;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Vector Search - O(log n) via HNSW
|
|
158
|
+
*/
|
|
159
|
+
async vectorSearch(params, limit) {
|
|
160
|
+
const results = [];
|
|
161
|
+
// Determine vector to search with
|
|
162
|
+
let searchVector;
|
|
163
|
+
if (params.vector) {
|
|
164
|
+
searchVector = params.vector;
|
|
165
|
+
}
|
|
166
|
+
else if (params.query) {
|
|
167
|
+
searchVector = await this.embedder(params.query);
|
|
168
|
+
}
|
|
169
|
+
else if (params.near?.id) {
|
|
170
|
+
const source = await this.get(params.near.id);
|
|
171
|
+
searchVector = source?.vector;
|
|
172
|
+
}
|
|
173
|
+
else if (params.near?.vector) {
|
|
174
|
+
searchVector = params.near.vector;
|
|
175
|
+
}
|
|
176
|
+
if (!searchVector)
|
|
177
|
+
return [];
|
|
178
|
+
// Search HNSW index
|
|
179
|
+
const searchResults = await this.index.search(searchVector, limit);
|
|
180
|
+
for (const [id, score] of searchResults) {
|
|
181
|
+
const entity = await this.get(id);
|
|
182
|
+
if (entity) {
|
|
183
|
+
results.push({ id, score, entity });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return results;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Metadata Search - O(n) for now, but could be indexed
|
|
190
|
+
*/
|
|
191
|
+
async metadataSearch(params, limit) {
|
|
192
|
+
const results = [];
|
|
193
|
+
const allNouns = await this.storage.getNouns();
|
|
194
|
+
for (const noun of allNouns) {
|
|
195
|
+
let matches = true;
|
|
196
|
+
// Check where constraints
|
|
197
|
+
if (params.where && !matchesMetadataFilter(noun.metadata, params.where)) {
|
|
198
|
+
matches = false;
|
|
199
|
+
}
|
|
200
|
+
// Check type constraint
|
|
201
|
+
if (params.type) {
|
|
202
|
+
const types = Array.isArray(params.type) ? params.type : [params.type];
|
|
203
|
+
if (!types.includes(noun.type))
|
|
204
|
+
matches = false;
|
|
205
|
+
}
|
|
206
|
+
// Check service constraint
|
|
207
|
+
if (params.service && noun.service !== params.service) {
|
|
208
|
+
matches = false;
|
|
209
|
+
}
|
|
210
|
+
if (matches) {
|
|
211
|
+
results.push({
|
|
212
|
+
id: noun.id,
|
|
213
|
+
score: 1.0,
|
|
214
|
+
entity: noun
|
|
215
|
+
});
|
|
216
|
+
if (results.length >= limit)
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return results;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Graph Traversal - O(k) where k = edges traversed
|
|
224
|
+
*/
|
|
225
|
+
async graphTraversal(connected, limit) {
|
|
226
|
+
if (!connected || !connected.from)
|
|
227
|
+
return [];
|
|
228
|
+
const visited = new Set();
|
|
229
|
+
const queue = [];
|
|
230
|
+
const results = [];
|
|
231
|
+
queue.push({ id: connected.from, depth: 0, score: 1.0 });
|
|
232
|
+
while (queue.length > 0 && results.length < limit) {
|
|
233
|
+
const { id, depth, score } = queue.shift();
|
|
234
|
+
if (visited.has(id))
|
|
235
|
+
continue;
|
|
236
|
+
if (depth > (connected.maxDepth || 2))
|
|
237
|
+
continue;
|
|
238
|
+
visited.add(id);
|
|
239
|
+
// Add to results if not starting node
|
|
240
|
+
if (depth > 0) {
|
|
241
|
+
const entity = await this.get(id);
|
|
242
|
+
if (entity) {
|
|
243
|
+
results.push({ id, score, entity });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// Get relationships
|
|
247
|
+
const relations = await this.storage.getVerbsBySource(id);
|
|
248
|
+
for (const relation of relations) {
|
|
249
|
+
if (connected.type && relation.type !== connected.type)
|
|
250
|
+
continue;
|
|
251
|
+
if (connected.direction === 'in')
|
|
252
|
+
continue;
|
|
253
|
+
if (!visited.has(relation.target)) {
|
|
254
|
+
queue.push({
|
|
255
|
+
id: relation.target,
|
|
256
|
+
depth: depth + 1,
|
|
257
|
+
score: score * 0.9
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// Get incoming relationships
|
|
262
|
+
if (connected.direction !== 'out') {
|
|
263
|
+
const incomingRelations = await this.storage.getVerbsByTarget(id);
|
|
264
|
+
for (const relation of incomingRelations) {
|
|
265
|
+
if (connected.type && relation.type !== connected.type)
|
|
266
|
+
continue;
|
|
267
|
+
if (!visited.has(relation.source)) {
|
|
268
|
+
queue.push({
|
|
269
|
+
id: relation.source,
|
|
270
|
+
depth: depth + 1,
|
|
271
|
+
score: score * 0.9
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return results;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Reciprocal Rank Fusion - Google's algorithm
|
|
281
|
+
*/
|
|
282
|
+
reciprocalRankFusion(resultSets, searchTypes, limit, offset) {
|
|
283
|
+
const k = 60; // RRF constant
|
|
284
|
+
const fusedScores = new Map();
|
|
285
|
+
// Weight configuration
|
|
286
|
+
const weights = {
|
|
287
|
+
vector: 0.4,
|
|
288
|
+
metadata: 0.35,
|
|
289
|
+
graph: 0.25
|
|
290
|
+
};
|
|
291
|
+
// Normalize weights
|
|
292
|
+
const activeWeights = searchTypes.map(t => weights[t]);
|
|
293
|
+
const totalWeight = activeWeights.reduce((sum, w) => sum + w, 0);
|
|
294
|
+
const normalizedWeights = activeWeights.map(w => w / totalWeight);
|
|
295
|
+
// Process each result set
|
|
296
|
+
resultSets.forEach((resultSet, setIndex) => {
|
|
297
|
+
const weight = normalizedWeights[setIndex];
|
|
298
|
+
resultSet.forEach((result, rank) => {
|
|
299
|
+
const rrfScore = weight * (1.0 / (k + rank + 1));
|
|
300
|
+
if (fusedScores.has(result.id)) {
|
|
301
|
+
const existing = fusedScores.get(result.id);
|
|
302
|
+
existing.score += rrfScore;
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
fusedScores.set(result.id, {
|
|
306
|
+
score: rrfScore,
|
|
307
|
+
entity: result.entity
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
// Sort by fusion score
|
|
313
|
+
const sortedResults = Array.from(fusedScores.entries())
|
|
314
|
+
.map(([id, { score, entity }]) => ({ id, score, entity }))
|
|
315
|
+
.sort((a, b) => b.score - a.score);
|
|
316
|
+
return sortedResults.slice(offset, offset + limit);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Ensure initialized
|
|
320
|
+
*/
|
|
321
|
+
async ensureInitialized() {
|
|
322
|
+
if (!this.initialized) {
|
|
323
|
+
throw new Error('Brainy not initialized. Call init() first.');
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
//# sourceMappingURL=brainy-unified.js.map
|
package/dist/brainy.d.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 🧠 Brainy 3.0 - The Future of Neural Databases
|
|
3
|
+
*
|
|
4
|
+
* Beautiful, Professional, Planet-Scale, Fun to Use
|
|
5
|
+
* NO STUBS, NO MOCKS, REAL IMPLEMENTATION
|
|
6
|
+
*/
|
|
7
|
+
import { ImprovedNeuralAPI } from './neural/improvedNeuralAPI.js';
|
|
8
|
+
import { NaturalLanguageProcessor } from './neural/naturalLanguageProcessor.js';
|
|
9
|
+
import { TripleIntelligenceSystem } from './triple/TripleIntelligenceSystem.js';
|
|
10
|
+
import { Entity, Relation, Result, AddParams, UpdateParams, RelateParams, FindParams, SimilarParams, GetRelationsParams, AddManyParams, DeleteManyParams, BatchResult, BrainyConfig } from './types/brainy.types.js';
|
|
11
|
+
import { NounType } from './types/graphTypes.js';
|
|
12
|
+
/**
|
|
13
|
+
* The main Brainy class - Clean, Beautiful, Powerful
|
|
14
|
+
* REAL IMPLEMENTATION - No stubs, no mocks
|
|
15
|
+
*/
|
|
16
|
+
export declare class Brainy<T = any> {
|
|
17
|
+
private index;
|
|
18
|
+
private storage;
|
|
19
|
+
private metadataIndex;
|
|
20
|
+
private graphIndex;
|
|
21
|
+
private embedder;
|
|
22
|
+
private distance;
|
|
23
|
+
private augmentationRegistry;
|
|
24
|
+
private config;
|
|
25
|
+
private _neural?;
|
|
26
|
+
private _nlp?;
|
|
27
|
+
private _tripleIntelligence?;
|
|
28
|
+
private initialized;
|
|
29
|
+
private dimensions?;
|
|
30
|
+
constructor(config?: BrainyConfig);
|
|
31
|
+
/**
|
|
32
|
+
* Initialize Brainy - MUST be called before use
|
|
33
|
+
* @param overrides Optional configuration overrides for init
|
|
34
|
+
*/
|
|
35
|
+
init(overrides?: Partial<BrainyConfig & {
|
|
36
|
+
dimensions?: number;
|
|
37
|
+
}>): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Ensure Brainy is initialized
|
|
40
|
+
*/
|
|
41
|
+
private ensureInitialized;
|
|
42
|
+
/**
|
|
43
|
+
* Add an entity to the database
|
|
44
|
+
*/
|
|
45
|
+
add(params: AddParams<T>): Promise<string>;
|
|
46
|
+
/**
|
|
47
|
+
* Get an entity by ID
|
|
48
|
+
*/
|
|
49
|
+
get(id: string): Promise<Entity<T> | null>;
|
|
50
|
+
/**
|
|
51
|
+
* Convert a noun from storage to an entity
|
|
52
|
+
*/
|
|
53
|
+
private convertNounToEntity;
|
|
54
|
+
/**
|
|
55
|
+
* Update an entity
|
|
56
|
+
*/
|
|
57
|
+
update(params: UpdateParams<T>): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Delete an entity
|
|
60
|
+
*/
|
|
61
|
+
delete(id: string): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Create a relationship between entities
|
|
64
|
+
*/
|
|
65
|
+
relate(params: RelateParams<T>): Promise<string>;
|
|
66
|
+
/**
|
|
67
|
+
* Delete a relationship
|
|
68
|
+
*/
|
|
69
|
+
unrelate(id: string): Promise<void>;
|
|
70
|
+
/**
|
|
71
|
+
* Get relationships
|
|
72
|
+
*/
|
|
73
|
+
getRelations(params?: GetRelationsParams): Promise<Relation<T>[]>;
|
|
74
|
+
/**
|
|
75
|
+
* Unified find method - supports natural language and structured queries
|
|
76
|
+
* Implements Triple Intelligence with parallel search optimization
|
|
77
|
+
*/
|
|
78
|
+
find(query: string | FindParams<T>): Promise<Result<T>[]>;
|
|
79
|
+
/**
|
|
80
|
+
* Find similar entities
|
|
81
|
+
*/
|
|
82
|
+
similar(params: SimilarParams<T>): Promise<Result<T>[]>;
|
|
83
|
+
/**
|
|
84
|
+
* Add multiple entities
|
|
85
|
+
*/
|
|
86
|
+
addMany(params: AddManyParams<T>): Promise<BatchResult<string>>;
|
|
87
|
+
/**
|
|
88
|
+
* Delete multiple entities
|
|
89
|
+
*/
|
|
90
|
+
deleteMany(params: DeleteManyParams): Promise<BatchResult<string>>;
|
|
91
|
+
/**
|
|
92
|
+
* Update multiple entities with batch processing
|
|
93
|
+
*/
|
|
94
|
+
updateMany(params: {
|
|
95
|
+
items: UpdateParams<T>[];
|
|
96
|
+
chunkSize?: number;
|
|
97
|
+
parallel?: boolean;
|
|
98
|
+
continueOnError?: boolean;
|
|
99
|
+
onProgress?: (completed: number, total: number) => void;
|
|
100
|
+
}): Promise<BatchResult<string>>;
|
|
101
|
+
/**
|
|
102
|
+
* Clear all data from the database
|
|
103
|
+
*/
|
|
104
|
+
clear(): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Neural API - Advanced AI operations
|
|
107
|
+
*/
|
|
108
|
+
neural(): ImprovedNeuralAPI;
|
|
109
|
+
/**
|
|
110
|
+
* Natural Language Processing API
|
|
111
|
+
*/
|
|
112
|
+
nlp(): NaturalLanguageProcessor;
|
|
113
|
+
/**
|
|
114
|
+
* Data Management API - backup, restore, import, export
|
|
115
|
+
*/
|
|
116
|
+
data(): Promise<import("./api/DataAPI.js").DataAPI>;
|
|
117
|
+
/**
|
|
118
|
+
* Get Triple Intelligence System
|
|
119
|
+
* Advanced pattern recognition and relationship analysis
|
|
120
|
+
*/
|
|
121
|
+
getTripleIntelligence(): TripleIntelligenceSystem;
|
|
122
|
+
/**
|
|
123
|
+
* Get all indexed field names currently in the metadata index
|
|
124
|
+
* Essential for dynamic query building and NLP field discovery
|
|
125
|
+
*/
|
|
126
|
+
getAvailableFields(): Promise<string[]>;
|
|
127
|
+
/**
|
|
128
|
+
* Get field statistics including cardinality and query patterns
|
|
129
|
+
* Used for query optimization and understanding data distribution
|
|
130
|
+
*/
|
|
131
|
+
getFieldStatistics(): Promise<Map<string, any>>;
|
|
132
|
+
/**
|
|
133
|
+
* Get fields sorted by cardinality for optimal filtering
|
|
134
|
+
* Lower cardinality fields are better for initial filtering
|
|
135
|
+
*/
|
|
136
|
+
getFieldsWithCardinality(): Promise<Array<{
|
|
137
|
+
field: string;
|
|
138
|
+
cardinality: number;
|
|
139
|
+
distribution: string;
|
|
140
|
+
}>>;
|
|
141
|
+
/**
|
|
142
|
+
* Get optimal query plan for a given set of filters
|
|
143
|
+
* Returns field processing order and estimated cost
|
|
144
|
+
*/
|
|
145
|
+
getOptimalQueryPlan(filters: Record<string, any>): Promise<{
|
|
146
|
+
strategy: 'exact' | 'range' | 'hybrid';
|
|
147
|
+
fieldOrder: string[];
|
|
148
|
+
estimatedCost: number;
|
|
149
|
+
}>;
|
|
150
|
+
/**
|
|
151
|
+
* Get filter values for a specific field (for UI dropdowns, etc)
|
|
152
|
+
*/
|
|
153
|
+
getFieldValues(field: string): Promise<string[]>;
|
|
154
|
+
/**
|
|
155
|
+
* Get fields that commonly appear with a specific entity type
|
|
156
|
+
* Essential for type-aware NLP parsing
|
|
157
|
+
*/
|
|
158
|
+
getFieldsForType(nounType: NounType): Promise<Array<{
|
|
159
|
+
field: string;
|
|
160
|
+
affinity: number;
|
|
161
|
+
occurrences: number;
|
|
162
|
+
totalEntities: number;
|
|
163
|
+
}>>;
|
|
164
|
+
/**
|
|
165
|
+
* Get comprehensive type-field affinity statistics
|
|
166
|
+
* Useful for understanding data patterns and NLP optimization
|
|
167
|
+
*/
|
|
168
|
+
getTypeFieldAffinityStats(): Promise<{
|
|
169
|
+
totalTypes: number;
|
|
170
|
+
averageFieldsPerType: number;
|
|
171
|
+
typeBreakdown: Record<string, {
|
|
172
|
+
totalEntities: number;
|
|
173
|
+
uniqueFields: number;
|
|
174
|
+
topFields: Array<{
|
|
175
|
+
field: string;
|
|
176
|
+
affinity: number;
|
|
177
|
+
}>;
|
|
178
|
+
}>;
|
|
179
|
+
}>;
|
|
180
|
+
/**
|
|
181
|
+
* Create a streaming pipeline
|
|
182
|
+
*/
|
|
183
|
+
stream(): any;
|
|
184
|
+
/**
|
|
185
|
+
* Get insights about the data
|
|
186
|
+
*/
|
|
187
|
+
insights(): Promise<{
|
|
188
|
+
entities: number;
|
|
189
|
+
relationships: number;
|
|
190
|
+
types: Record<string, number>;
|
|
191
|
+
services: string[];
|
|
192
|
+
density: number;
|
|
193
|
+
}>;
|
|
194
|
+
/**
|
|
195
|
+
* Augmentations API - Clean and simple
|
|
196
|
+
*/
|
|
197
|
+
get augmentations(): {
|
|
198
|
+
list: () => string[];
|
|
199
|
+
get: (name: string) => import("./augmentations/brainyAugmentation.js").BrainyAugmentation | undefined;
|
|
200
|
+
has: (name: string) => boolean;
|
|
201
|
+
};
|
|
202
|
+
/**
|
|
203
|
+
* Parse natural language query using advanced NLP with 220+ patterns
|
|
204
|
+
* The embedding model is always available as it's core to Brainy's functionality
|
|
205
|
+
*/
|
|
206
|
+
private parseNaturalQuery;
|
|
207
|
+
/**
|
|
208
|
+
* Enhance NLP results with fusion scoring
|
|
209
|
+
*/
|
|
210
|
+
private enhanceNLPResult;
|
|
211
|
+
/**
|
|
212
|
+
* Execute vector search component
|
|
213
|
+
*/
|
|
214
|
+
private executeVectorSearch;
|
|
215
|
+
/**
|
|
216
|
+
* Execute proximity search component
|
|
217
|
+
*/
|
|
218
|
+
private executeProximitySearch;
|
|
219
|
+
/**
|
|
220
|
+
* Execute graph search component with O(1) traversal
|
|
221
|
+
*/
|
|
222
|
+
private executeGraphSearch;
|
|
223
|
+
/**
|
|
224
|
+
* Apply fusion scoring for multi-source results
|
|
225
|
+
*/
|
|
226
|
+
private applyFusionScoring;
|
|
227
|
+
/**
|
|
228
|
+
* Apply graph constraints using O(1) GraphAdjacencyIndex - TRUE Triple Intelligence!
|
|
229
|
+
*/
|
|
230
|
+
private applyGraphConstraints;
|
|
231
|
+
/**
|
|
232
|
+
* Convert verbs to relations
|
|
233
|
+
*/
|
|
234
|
+
private verbsToRelations;
|
|
235
|
+
/**
|
|
236
|
+
* Embed data into vector
|
|
237
|
+
*/
|
|
238
|
+
private embed;
|
|
239
|
+
/**
|
|
240
|
+
* Warm up the system
|
|
241
|
+
*/
|
|
242
|
+
private warmup;
|
|
243
|
+
/**
|
|
244
|
+
* Setup embedder
|
|
245
|
+
*/
|
|
246
|
+
private setupEmbedder;
|
|
247
|
+
/**
|
|
248
|
+
* Setup storage
|
|
249
|
+
*/
|
|
250
|
+
private setupStorage;
|
|
251
|
+
/**
|
|
252
|
+
* Setup index
|
|
253
|
+
*/
|
|
254
|
+
private setupIndex;
|
|
255
|
+
/**
|
|
256
|
+
* Setup augmentations
|
|
257
|
+
*/
|
|
258
|
+
private setupAugmentations;
|
|
259
|
+
/**
|
|
260
|
+
* Normalize and validate configuration
|
|
261
|
+
*/
|
|
262
|
+
private normalizeConfig;
|
|
263
|
+
/**
|
|
264
|
+
* Rebuild indexes if there's existing data but empty indexes
|
|
265
|
+
*/
|
|
266
|
+
private rebuildIndexesIfNeeded;
|
|
267
|
+
/**
|
|
268
|
+
* Close and cleanup
|
|
269
|
+
*/
|
|
270
|
+
close(): Promise<void>;
|
|
271
|
+
}
|
|
272
|
+
export * from './types/brainy.types.js';
|
|
273
|
+
export { NounType, VerbType } from './types/graphTypes.js';
|