@soulcraft/brainy 2.15.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.
Files changed (204) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +249 -152
  3. package/dist/api/ConfigAPI.d.ts +67 -0
  4. package/dist/api/ConfigAPI.js +166 -0
  5. package/dist/api/DataAPI.d.ts +123 -0
  6. package/dist/api/DataAPI.js +391 -0
  7. package/dist/api/SecurityAPI.d.ts +50 -0
  8. package/dist/api/SecurityAPI.js +139 -0
  9. package/dist/api/UniversalImportAPI.d.ts +134 -0
  10. package/dist/api/UniversalImportAPI.js +615 -0
  11. package/dist/augmentationManager.js +12 -7
  12. package/dist/augmentationPipeline.d.ts +0 -61
  13. package/dist/augmentationPipeline.js +0 -87
  14. package/dist/augmentationRegistry.d.ts +1 -1
  15. package/dist/augmentationRegistry.js +1 -1
  16. package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
  17. package/dist/augmentations/apiServerAugmentation.js +288 -7
  18. package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
  19. package/dist/augmentations/auditLogAugmentation.js +358 -0
  20. package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
  21. package/dist/augmentations/batchProcessingAugmentation.js +123 -22
  22. package/dist/augmentations/brainyAugmentation.d.ts +87 -8
  23. package/dist/augmentations/brainyAugmentation.js +159 -2
  24. package/dist/augmentations/cacheAugmentation.d.ts +6 -5
  25. package/dist/augmentations/cacheAugmentation.js +113 -17
  26. package/dist/augmentations/conduitAugmentations.d.ts +2 -2
  27. package/dist/augmentations/conduitAugmentations.js +2 -2
  28. package/dist/augmentations/configResolver.d.ts +122 -0
  29. package/dist/augmentations/configResolver.js +440 -0
  30. package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
  31. package/dist/augmentations/connectionPoolAugmentation.js +37 -12
  32. package/dist/augmentations/defaultAugmentations.d.ts +9 -11
  33. package/dist/augmentations/defaultAugmentations.js +4 -11
  34. package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
  35. package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
  36. package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
  37. package/dist/augmentations/discovery/localDiscovery.js +246 -0
  38. package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
  39. package/dist/augmentations/discovery/runtimeLoader.js +337 -0
  40. package/dist/augmentations/discovery.d.ts +152 -0
  41. package/dist/augmentations/discovery.js +441 -0
  42. package/dist/augmentations/display/intelligentComputation.d.ts +1 -1
  43. package/dist/augmentations/display/intelligentComputation.js +4 -4
  44. package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
  45. package/dist/augmentations/entityRegistryAugmentation.js +5 -1
  46. package/dist/augmentations/indexAugmentation.d.ts +3 -3
  47. package/dist/augmentations/indexAugmentation.js +2 -2
  48. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +22 -6
  49. package/dist/augmentations/intelligentVerbScoringAugmentation.js +106 -23
  50. package/dist/augmentations/manifest.d.ts +176 -0
  51. package/dist/augmentations/manifest.js +8 -0
  52. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
  53. package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
  54. package/dist/augmentations/marketplace/cli.d.ts +47 -0
  55. package/dist/augmentations/marketplace/cli.js +265 -0
  56. package/dist/augmentations/metricsAugmentation.d.ts +3 -3
  57. package/dist/augmentations/metricsAugmentation.js +2 -2
  58. package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
  59. package/dist/augmentations/monitoringAugmentation.js +2 -2
  60. package/dist/augmentations/neuralImport.d.ts +1 -1
  61. package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
  62. package/dist/augmentations/rateLimitAugmentation.js +321 -0
  63. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
  64. package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
  65. package/dist/augmentations/storageAugmentation.d.ts +1 -1
  66. package/dist/augmentations/storageAugmentation.js +2 -2
  67. package/dist/augmentations/storageAugmentations.d.ts +37 -8
  68. package/dist/augmentations/storageAugmentations.js +204 -15
  69. package/dist/augmentations/synapseAugmentation.d.ts +1 -1
  70. package/dist/augmentations/synapseAugmentation.js +35 -16
  71. package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
  72. package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
  73. package/dist/augmentations/universalDisplayAugmentation.d.ts +2 -2
  74. package/dist/augmentations/universalDisplayAugmentation.js +2 -2
  75. package/dist/brainy-unified.d.ts +106 -0
  76. package/dist/brainy-unified.js +327 -0
  77. package/dist/brainy.d.ts +273 -0
  78. package/dist/brainy.js +1181 -0
  79. package/dist/brainyData.d.ts +29 -72
  80. package/dist/brainyData.js +350 -304
  81. package/dist/brainyDataV3.d.ts +186 -0
  82. package/dist/brainyDataV3.js +337 -0
  83. package/dist/browserFramework.d.ts +6 -6
  84. package/dist/browserFramework.js +11 -8
  85. package/dist/browserFramework.minimal.d.ts +5 -5
  86. package/dist/browserFramework.minimal.js +11 -8
  87. package/dist/config/index.d.ts +2 -2
  88. package/dist/config/index.js +3 -3
  89. package/dist/config/modelAutoConfig.d.ts +6 -7
  90. package/dist/config/modelAutoConfig.js +17 -76
  91. package/dist/cortex/backupRestore.d.ts +2 -2
  92. package/dist/cortex/backupRestore.js +85 -27
  93. package/dist/cortex/healthCheck.d.ts +2 -2
  94. package/dist/cortex/neuralImport.d.ts +2 -2
  95. package/dist/cortex/neuralImport.js +18 -13
  96. package/dist/cortex/performanceMonitor.d.ts +2 -2
  97. package/dist/critical/model-guardian.d.ts +4 -0
  98. package/dist/critical/model-guardian.js +31 -11
  99. package/dist/demo.d.ts +4 -4
  100. package/dist/demo.js +7 -7
  101. package/dist/distributed/cacheSync.d.ts +112 -0
  102. package/dist/distributed/cacheSync.js +265 -0
  103. package/dist/distributed/coordinator.d.ts +193 -0
  104. package/dist/distributed/coordinator.js +548 -0
  105. package/dist/distributed/httpTransport.d.ts +120 -0
  106. package/dist/distributed/httpTransport.js +446 -0
  107. package/dist/distributed/index.d.ts +8 -0
  108. package/dist/distributed/index.js +5 -0
  109. package/dist/distributed/networkTransport.d.ts +132 -0
  110. package/dist/distributed/networkTransport.js +633 -0
  111. package/dist/distributed/queryPlanner.d.ts +104 -0
  112. package/dist/distributed/queryPlanner.js +327 -0
  113. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  114. package/dist/distributed/readWriteSeparation.js +350 -0
  115. package/dist/distributed/shardManager.d.ts +114 -0
  116. package/dist/distributed/shardManager.js +357 -0
  117. package/dist/distributed/shardMigration.d.ts +110 -0
  118. package/dist/distributed/shardMigration.js +289 -0
  119. package/dist/distributed/storageDiscovery.d.ts +160 -0
  120. package/dist/distributed/storageDiscovery.js +551 -0
  121. package/dist/embeddings/EmbeddingManager.d.ts +0 -4
  122. package/dist/embeddings/EmbeddingManager.js +21 -26
  123. package/dist/errors/brainyError.d.ts +5 -1
  124. package/dist/errors/brainyError.js +12 -0
  125. package/dist/examples/basicUsage.js +3 -3
  126. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  127. package/dist/graph/graphAdjacencyIndex.js +288 -0
  128. package/dist/graph/pathfinding.js +4 -2
  129. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  130. package/dist/importManager.js +6 -3
  131. package/dist/index.d.ts +12 -21
  132. package/dist/index.js +14 -22
  133. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  134. package/dist/mcp/brainyMCPAdapter.js +5 -5
  135. package/dist/mcp/brainyMCPService.d.ts +3 -3
  136. package/dist/mcp/brainyMCPService.js +3 -11
  137. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  138. package/dist/neural/embeddedPatterns.d.ts +1 -1
  139. package/dist/neural/embeddedPatterns.js +2 -2
  140. package/dist/neural/entityExtractor.d.ts +65 -0
  141. package/dist/neural/entityExtractor.js +316 -0
  142. package/dist/neural/improvedNeuralAPI.js +90 -79
  143. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  144. package/dist/neural/naturalLanguageProcessor.js +941 -66
  145. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  146. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  147. package/dist/neural/neuralAPI.js +8 -2
  148. package/dist/neural/patternLibrary.d.ts +57 -3
  149. package/dist/neural/patternLibrary.js +348 -13
  150. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  151. package/dist/neural/staticPatternMatcher.js +2 -2
  152. package/dist/shared/default-augmentations.d.ts +3 -3
  153. package/dist/shared/default-augmentations.js +5 -5
  154. package/dist/storage/adapters/fileSystemStorage.d.ts +4 -0
  155. package/dist/storage/adapters/fileSystemStorage.js +54 -1
  156. package/dist/storage/adapters/memoryStorage.js +13 -8
  157. package/dist/storage/backwardCompatibility.d.ts +10 -78
  158. package/dist/storage/backwardCompatibility.js +17 -132
  159. package/dist/storage/baseStorage.d.ts +6 -0
  160. package/dist/storage/baseStorage.js +17 -0
  161. package/dist/storage/cacheManager.js +2 -2
  162. package/dist/storage/readOnlyOptimizations.js +8 -3
  163. package/dist/streaming/pipeline.d.ts +154 -0
  164. package/dist/streaming/pipeline.js +551 -0
  165. package/dist/triple/TripleIntelligence.d.ts +25 -110
  166. package/dist/triple/TripleIntelligence.js +4 -574
  167. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  168. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  169. package/dist/types/apiTypes.d.ts +278 -0
  170. package/dist/types/apiTypes.js +33 -0
  171. package/dist/types/brainy.types.d.ts +308 -0
  172. package/dist/types/brainy.types.js +8 -0
  173. package/dist/types/brainyDataInterface.d.ts +3 -3
  174. package/dist/types/brainyDataInterface.js +2 -2
  175. package/dist/types/graphTypes.js +2 -2
  176. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  177. package/dist/utils/embedding.js +8 -14
  178. package/dist/utils/enhancedLogger.d.ts +104 -0
  179. package/dist/utils/enhancedLogger.js +232 -0
  180. package/dist/utils/index.d.ts +1 -1
  181. package/dist/utils/index.js +1 -1
  182. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  183. package/dist/utils/intelligentTypeMapper.js +349 -0
  184. package/dist/utils/metadataIndex.d.ts +118 -1
  185. package/dist/utils/metadataIndex.js +539 -16
  186. package/dist/utils/paramValidation.d.ts +39 -0
  187. package/dist/utils/paramValidation.js +192 -0
  188. package/dist/utils/rateLimiter.d.ts +160 -0
  189. package/dist/utils/rateLimiter.js +271 -0
  190. package/dist/utils/statistics.d.ts +4 -4
  191. package/dist/utils/statistics.js +3 -3
  192. package/dist/utils/structuredLogger.d.ts +146 -0
  193. package/dist/utils/structuredLogger.js +394 -0
  194. package/dist/utils/textEncoding.js +2 -1
  195. package/dist/utils/typeValidation.d.ts +34 -0
  196. package/dist/utils/typeValidation.js +247 -0
  197. package/package.json +14 -6
  198. package/scripts/download-models.cjs +6 -15
  199. package/dist/augmentations/walAugmentation.d.ts +0 -111
  200. package/dist/augmentations/walAugmentation.js +0 -519
  201. package/dist/chat/BrainyChat.d.ts +0 -121
  202. package/dist/chat/BrainyChat.js +0 -396
  203. package/dist/chat/ChatCLI.d.ts +0 -61
  204. package/dist/chat/ChatCLI.js +0 -351
@@ -12,12 +12,11 @@ import { enforceNodeVersion } from './utils/nodeVersionCheck.js';
12
12
  import { createNamespacedMetadata, updateNamespacedMetadata, markDeleted, markRestored, isDeleted, getUserMetadata } from './utils/metadataNamespace.js';
13
13
  import { PeriodicCleanup } from './utils/periodicCleanup.js';
14
14
  import { NounType, VerbType } from './types/graphTypes.js';
15
- import { validateNounType } from './utils/typeValidation.js';
16
- import { createServerSearchAugmentations } from './augmentations/serverSearchAugmentations.js';
17
- import { augmentationPipeline } from './augmentationPipeline.js';
15
+ import { validateNounType, validateSearchQuery, validateSearchOptions, validateDataInput } from './utils/typeValidation.js';
16
+ import { BrainyError } from './errors/brainyError.js';
18
17
  import { prodLog } from './utils/logger.js';
19
18
  import { prepareJsonForVectorization, extractFieldFromJson } from './utils/jsonProcessing.js';
20
- import { DistributedConfigManager, HashPartitioner, OperationalModeFactory, DomainDetector } from './distributed/index.js';
19
+ import { DistributedConfigManager, HashPartitioner, OperationalModeFactory, DomainDetector, DistributedCoordinator, ShardManager, CacheSync, ReadWriteSeparation } from './distributed/index.js';
21
20
  import { CacheAutoConfigurator } from './utils/cacheAutoConfig.js';
22
21
  import { RequestDeduplicator } from './utils/requestDeduplicator.js';
23
22
  import { AugmentationRegistry } from './augmentations/brainyAugmentation.js';
@@ -30,9 +29,7 @@ import { createDefaultAugmentations } from './augmentations/defaultAugmentations
30
29
  // import { RealtimeStreamingAugmentation } from './augmentations/realtimeStreamingAugmentation.js'
31
30
  import { IntelligentVerbScoringAugmentation } from './augmentations/intelligentVerbScoringAugmentation.js';
32
31
  import { ImprovedNeuralAPI } from './neural/improvedNeuralAPI.js';
33
- import { TripleIntelligenceEngine } from './triple/TripleIntelligence.js';
34
32
  export class BrainyData {
35
- // REMOVED: HealthMonitor is now handled by MonitoringAugmentation
36
33
  // Statistics collector
37
34
  // REMOVED: StatisticsCollector is now handled by MetricsAugmentation
38
35
  // Clean augmentation accessors for internal use
@@ -54,6 +51,11 @@ export class BrainyData {
54
51
  get monitoring() {
55
52
  return this.augmentations.get('monitoring');
56
53
  }
54
+ // ================================================================
55
+ // SECTION 1: CONFIGURATION & PROPERTIES
56
+ // ================================================================
57
+ // Configuration getters, dimensions, and system properties
58
+ // These provide access to core system configuration and status
57
59
  /**
58
60
  * Get the vector dimensions
59
61
  */
@@ -80,6 +82,11 @@ export class BrainyData {
80
82
  get initialized() {
81
83
  return this.isInitialized;
82
84
  }
85
+ // ================================================================
86
+ // SECTION 2: CONSTRUCTOR & INITIALIZATION
87
+ // ================================================================
88
+ // Constructor, initialization logic, and system setup
89
+ // Handles zero-config setup and system bootstrapping
83
90
  /**
84
91
  * Create a new vector database
85
92
  * @param config - Zero-config string ('production', 'development', 'minimal'),
@@ -127,6 +134,17 @@ export class BrainyData {
127
134
  this.partitioner = null;
128
135
  this.operationalMode = null;
129
136
  this.domainDetector = null;
137
+ // REMOVED: HealthMonitor is now handled by MonitoringAugmentation
138
+ // New distributed components for 3.0
139
+ this.networkTransport = null;
140
+ this.coordinator = null;
141
+ this.shardManager = null;
142
+ this.cacheSync = null;
143
+ this.readWriteSeparation = null;
144
+ this.httpTransport = null; // HTTPTransport from dynamic import
145
+ this.storageDiscovery = null; // StorageDiscovery from dynamic import
146
+ this.queryPlanner = null; // DistributedQueryPlanner from dynamic import
147
+ this.shardMigrationManager = null; // ShardMigrationManager from dynamic import
130
148
  // Enforce Node.js version requirement for ONNX stability
131
149
  if (typeof process !== 'undefined' && process.version && !process.env.BRAINY_SKIP_VERSION_CHECK) {
132
150
  enforceNodeVersion();
@@ -405,7 +423,7 @@ export class BrainyData {
405
423
  await this.storage.init();
406
424
  }
407
425
  else {
408
- throw new Error('Failed to resolve storage');
426
+ throw BrainyError.storage('Failed to resolve storage');
409
427
  }
410
428
  }
411
429
  /**
@@ -439,7 +457,7 @@ export class BrainyData {
439
457
  */
440
458
  async initializePeriodicCleanup() {
441
459
  if (!this.storage) {
442
- throw new Error('Cannot initialize periodic cleanup: storage not available');
460
+ throw BrainyError.storage('Cannot initialize periodic cleanup: storage not available');
443
461
  }
444
462
  // Skip cleanup if in read-only or frozen mode
445
463
  if (this.readOnly || this.frozen) {
@@ -860,16 +878,12 @@ export class BrainyData {
860
878
  */
861
879
  getCurrentAugmentation() {
862
880
  try {
863
- // Get all registered augmentations
864
- const augmentationTypes = augmentationPipeline.getAvailableAugmentationTypes();
865
- // Check each type of augmentation
866
- for (const type of augmentationTypes) {
867
- const augmentations = augmentationPipeline.getAugmentationsByType(type);
868
- // Find the first augmentation (all registered augmentations are considered enabled)
869
- for (const augmentation of augmentations) {
870
- if (augmentation) {
871
- return augmentation.name;
872
- }
881
+ // Get all registered augmentations from the new API
882
+ const allAugmentations = this.augmentations.getAll();
883
+ // Find the first enabled augmentation
884
+ for (const augmentation of allAugmentations) {
885
+ if (augmentation && augmentation.config?.enabled !== false) {
886
+ return augmentation.name;
873
887
  }
874
888
  }
875
889
  return 'default';
@@ -1028,16 +1042,6 @@ export class BrainyData {
1028
1042
  offset += limit;
1029
1043
  }
1030
1044
  }
1031
- // Connect to remote server if configured with autoConnect
1032
- if (this.remoteServerConfig && this.remoteServerConfig.autoConnect) {
1033
- try {
1034
- await this.connectToRemoteServer(this.remoteServerConfig.url, this.remoteServerConfig.protocols);
1035
- }
1036
- catch (remoteError) {
1037
- console.warn('Failed to auto-connect to remote server:', remoteError);
1038
- // Continue initialization even if remote connection fails
1039
- }
1040
- }
1041
1045
  // Initialize statistics collector with existing data
1042
1046
  try {
1043
1047
  const existingStats = await this.storage.getStatistics();
@@ -1146,6 +1150,8 @@ export class BrainyData {
1146
1150
  // Create operational mode based on role
1147
1151
  const role = this.configManager.getRole();
1148
1152
  this.operationalMode = OperationalModeFactory.createMode(role);
1153
+ // Initialize NEW distributed components for 3.0
1154
+ await this.initializeDistributedComponents(sharedConfig);
1149
1155
  // Validate that role matches the configured mode
1150
1156
  // Don't override explicitly set readOnly/writeOnly
1151
1157
  if (role === 'reader' && !this.readOnly) {
@@ -1206,75 +1212,212 @@ export class BrainyData {
1206
1212
  }
1207
1213
  }
1208
1214
  /**
1209
- * Get distributed health status
1210
- * @returns Health status if distributed mode is enabled
1215
+ * Initialize NEW distributed components for Brainy 3.0
1216
+ * This enables true multi-node operation with consensus and sharding
1217
+ */
1218
+ async initializeDistributedComponents(sharedConfig) {
1219
+ // Extract distributed configuration with type safety
1220
+ const distConfig = typeof this.distributedConfig === 'object' && this.distributedConfig !== null
1221
+ ? this.distributedConfig
1222
+ : {};
1223
+ // Generate or use node ID
1224
+ const nodeId = distConfig.instanceId || sharedConfig.nodeId ||
1225
+ `node-${Math.random().toString(36).substring(2, 11)}`;
1226
+ // Use zero-config discovery if storage is available
1227
+ if (this.storage && distConfig.useStorageDiscovery !== false) {
1228
+ // Use storage-based discovery for true zero-config
1229
+ const { StorageDiscovery } = await import('./distributed/storageDiscovery.js');
1230
+ this.storageDiscovery = new StorageDiscovery(this.storage, nodeId);
1231
+ // Start discovery and join cluster
1232
+ const port = distConfig.port || 0; // 0 = auto-detect
1233
+ const cluster = await this.storageDiscovery.start(port);
1234
+ // Use discovered nodes as seeds
1235
+ distConfig.peers = cluster.nodes.map((n) => `${n.address}:${n.port}`);
1236
+ }
1237
+ // Initialize HTTP transport (replaces NetworkTransport)
1238
+ const { HTTPTransport } = await import('./distributed/httpTransport.js');
1239
+ this.httpTransport = new HTTPTransport(nodeId);
1240
+ // Start HTTP transport
1241
+ const actualPort = await this.httpTransport.start();
1242
+ console.log(`[${nodeId}] HTTP transport listening on port ${actualPort}`);
1243
+ // Initialize coordinator for consensus
1244
+ this.coordinator = new DistributedCoordinator({
1245
+ nodeId,
1246
+ heartbeatInterval: distConfig.heartbeatInterval || 1000,
1247
+ electionTimeout: distConfig.electionTimeout || 5000,
1248
+ nodes: distConfig.peers || []
1249
+ });
1250
+ // Start coordinator with HTTP transport adapter
1251
+ const transportAdapter = {
1252
+ send: (nodeId, message) => this.httpTransport.call(nodeId, 'coordinator', message),
1253
+ broadcast: (message) => this.httpTransport.broadcast('coordinator', message),
1254
+ on: (event, handler) => {
1255
+ // Register handler for coordinator messages
1256
+ if (event === 'message') {
1257
+ this.httpTransport.registerHandler('coordinator', handler);
1258
+ }
1259
+ }
1260
+ };
1261
+ await this.coordinator.start(transportAdapter);
1262
+ // Initialize shard manager
1263
+ this.shardManager = new ShardManager({
1264
+ shardCount: distConfig.shardCount || 8,
1265
+ replicationFactor: distConfig.replicationFactor || 3,
1266
+ virtualNodes: distConfig.virtualNodes || 100,
1267
+ autoRebalance: distConfig.autoRebalance !== false
1268
+ });
1269
+ // Initialize cache synchronization
1270
+ this.cacheSync = new CacheSync({
1271
+ nodeId,
1272
+ syncInterval: distConfig.syncInterval || 5000
1273
+ });
1274
+ // Initialize read/write separation
1275
+ // Note: This requires all components to be initialized
1276
+ this.readWriteSeparation = new ReadWriteSeparation({
1277
+ nodeId,
1278
+ role: this.readOnly ? 'replica' : this.writeOnly ? 'primary' : 'auto',
1279
+ primaryUrl: distConfig.primaryUrl || '',
1280
+ replicaUrls: distConfig.replicaUrls || [],
1281
+ syncInterval: distConfig.syncInterval || 5000,
1282
+ readPreference: distConfig.readPreference || 'nearest',
1283
+ consistencyLevel: distConfig.consistencyLevel || 'eventual'
1284
+ }, this.coordinator, this.shardManager, this.cacheSync);
1285
+ // Initialize query planner for distributed queries
1286
+ const { DistributedQueryPlanner } = await import('./distributed/queryPlanner.js');
1287
+ this.queryPlanner = new DistributedQueryPlanner(nodeId, this.coordinator, this.shardManager, this.httpTransport, this.storage, this._tripleEngine);
1288
+ // Set up coordinator event handlers
1289
+ this.coordinator.on('leaderElected', (leaderId) => {
1290
+ if (leaderId === nodeId) {
1291
+ console.log(`[${nodeId}] Became the leader`);
1292
+ // Update read/write separation if needed
1293
+ if (this.readWriteSeparation) {
1294
+ this.readWriteSeparation.setPrimary(true);
1295
+ }
1296
+ }
1297
+ else {
1298
+ console.log(`[${nodeId}] Following leader: ${leaderId}`);
1299
+ if (this.readWriteSeparation) {
1300
+ this.readWriteSeparation.setPrimary(false);
1301
+ }
1302
+ }
1303
+ });
1304
+ // Set up distributed operation handlers
1305
+ this.setupDistributedOperations();
1306
+ if (this.loggingConfig?.verbose) {
1307
+ console.log(`[${nodeId}] Distributed components initialized`);
1308
+ console.log(`- Network: ${this.networkTransport ? 'Ready' : 'Not initialized'}`);
1309
+ console.log(`- Coordinator: ${this.coordinator.getState().state}`);
1310
+ console.log(`- Shards: ${this.shardManager.getTotalShards()} total`);
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Execute a query on local shards
1211
1315
  */
1212
- getHealthStatus() {
1213
- return this.monitoring?.getHealthStatus() || null;
1316
+ async executeLocalQuery(query, shards) {
1317
+ // For now, just do a regular find
1318
+ // In production, this would filter by shard assignments
1319
+ const results = await this.find(query.text || query.query, query.k || 10);
1320
+ return results;
1214
1321
  }
1215
1322
  /**
1216
- * Connect to a remote Brainy server for search operations
1217
- * @param serverUrl WebSocket URL of the remote Brainy server
1218
- * @param protocols Optional WebSocket protocols to use
1219
- * @returns The connection object
1323
+ * Set up distributed operation handlers
1220
1324
  */
1221
- async connectToRemoteServer(serverUrl, protocols) {
1222
- await this.ensureInitialized();
1223
- try {
1224
- // Create server search augmentations
1225
- const { conduit, connection } = await createServerSearchAugmentations(serverUrl, {
1226
- protocols,
1227
- localDb: this
1325
+ setupDistributedOperations() {
1326
+ // Set up handlers for HTTP transport if available
1327
+ if (this.httpTransport) {
1328
+ // Handle distributed query requests
1329
+ this.httpTransport.registerHandler('query', async (data) => {
1330
+ const { query, shards } = data;
1331
+ try {
1332
+ // Execute query on specified shards
1333
+ const results = await this.executeLocalQuery(query, shards);
1334
+ return { success: true, results, count: results.length };
1335
+ }
1336
+ catch (error) {
1337
+ return { success: false, error: error.message };
1338
+ }
1339
+ });
1340
+ // Handle migration batch receives
1341
+ this.httpTransport.registerHandler('receiveMigrationBatch', async (data) => {
1342
+ if (this.shardMigrationManager) {
1343
+ await this.shardMigrationManager.receiveMigrationBatch(data);
1344
+ }
1345
+ return { success: true };
1346
+ });
1347
+ // Handle migration validation
1348
+ this.httpTransport.registerHandler('validateMigration', async (data) => {
1349
+ if (this.shardMigrationManager) {
1350
+ return await this.shardMigrationManager.validateMigration(data);
1351
+ }
1352
+ return { valid: false, error: 'No migration manager' };
1228
1353
  });
1229
- // TODO: Store conduit and connection (post-2.0.0 feature)
1230
- // this.serverSearchConduit = conduit
1231
- // this.serverConnection = connection
1232
- return connection;
1233
1354
  }
1234
- catch (error) {
1235
- console.error('Failed to connect to remote server:', error);
1236
- throw new Error(`Failed to connect to remote server: ${error}`);
1355
+ // Set up legacy NetworkTransport handlers if still used
1356
+ if (this.networkTransport) {
1357
+ const handlers = this.networkTransport.messageHandlers;
1358
+ // Handle distributed add requests
1359
+ handlers.set('DISTRIBUTED_ADD', async (msg) => {
1360
+ const { data, type, metadata } = msg.data;
1361
+ try {
1362
+ const id = await this.localAdd(data, type, metadata);
1363
+ return { success: true, id };
1364
+ }
1365
+ catch (error) {
1366
+ return { success: false, error: error.message };
1367
+ }
1368
+ });
1369
+ // Handle distributed find requests
1370
+ handlers.set('DISTRIBUTED_FIND', async (msg) => {
1371
+ const { query, shardId } = msg.data;
1372
+ try {
1373
+ const results = await this.localFind(query, shardId);
1374
+ return { success: true, results };
1375
+ }
1376
+ catch (error) {
1377
+ return { success: false, error: error.message };
1378
+ }
1379
+ });
1380
+ // Handle cache sync messages
1381
+ handlers.set('CACHE_SYNC', async (msg) => {
1382
+ if (this.cacheSync) {
1383
+ await this.cacheSync.handleSyncMessage(msg.data);
1384
+ }
1385
+ return { success: true };
1386
+ });
1237
1387
  }
1238
1388
  }
1239
- // REMOVED: addItem() - Use addNoun() instead (cleaner 2.0 API)
1240
- // REMOVED: addToBoth() - Remote server functionality moved to post-2.0.0
1241
1389
  /**
1242
- * Add a vector to the remote server
1243
- * @param id ID of the vector to add
1244
- * @param vector Vector to add
1245
- * @param metadata Optional metadata to associate with the vector
1246
- * @returns True if successful, false otherwise
1247
- * @private
1390
+ * Local add operation (without distribution)
1248
1391
  */
1249
- async addToRemote(id, vector, metadata) {
1250
- if (!this.isConnectedToRemoteServer()) {
1251
- return false;
1252
- }
1392
+ async localAdd(data, type, metadata) {
1393
+ // Use the existing addNoun method but bypass distribution checks
1394
+ const tempDistributed = this.shardManager;
1395
+ this.shardManager = null; // Temporarily disable to prevent recursion
1253
1396
  try {
1254
- // TODO: Remote server operations (post-2.0.0 feature)
1255
- // if (!this.serverSearchConduit || !this.serverConnection) {
1256
- // throw new Error(
1257
- // 'Server search conduit or connection is not initialized'
1258
- // )
1259
- // }
1260
- // TODO: Add to remote server
1261
- // const addResult = await this.serverSearchConduit.addToBoth(
1262
- // this.serverConnection.connectionId,
1263
- // vector,
1264
- // metadata
1265
- // )
1266
- throw new Error('Remote server functionality not yet implemented in Brainy 2.0.0');
1267
- // TODO: Handle remote add result (post-2.0.0 feature)
1268
- // if (!addResult.success) {
1269
- // throw new Error(`Remote add failed: ${addResult.error}`)
1270
- // }
1271
- return true;
1397
+ const id = await this.addNoun(data, type, metadata);
1398
+ return id;
1272
1399
  }
1273
- catch (error) {
1274
- console.error('Failed to add to remote server:', error);
1275
- throw new Error(`Failed to add to remote server: ${error}`);
1400
+ finally {
1401
+ this.shardManager = tempDistributed; // Restore
1276
1402
  }
1277
1403
  }
1404
+ /**
1405
+ * Local find operation (potentially for a specific shard)
1406
+ */
1407
+ async localFind(query, shardId) {
1408
+ // TODO: Implement shard-aware find
1409
+ // For now, just use regular find
1410
+ return this.find(query);
1411
+ }
1412
+ /**
1413
+ * Get distributed health status
1414
+ * @returns Health status if distributed mode is enabled
1415
+ */
1416
+ getHealthStatus() {
1417
+ return this.monitoring?.getHealthStatus() || null;
1418
+ }
1419
+ // REMOVED: addItem() - Use addNoun() instead (cleaner 2.0 API)
1420
+ // REMOVED: addToBoth() - Remote server functionality moved to post-2.0.0
1278
1421
  /**
1279
1422
  * Add multiple vectors or data items to the database
1280
1423
  * @param items Array of items to add
@@ -1387,20 +1530,6 @@ export class BrainyData {
1387
1530
  throw new Error(`Failed to add batch of items: ${error}`);
1388
1531
  }
1389
1532
  }
1390
- /**
1391
- * Add multiple vectors or data items to both local and remote databases
1392
- * @param items Array of items to add (with required types)
1393
- * @param options Additional options
1394
- * @returns Array of IDs for the added items
1395
- */
1396
- async addBatchToBoth(items, options = {}) {
1397
- // Check if connected to a remote server
1398
- if (!this.isConnectedToRemoteServer()) {
1399
- throw new Error('Not connected to a remote server. Call connectToRemoteServer() first.');
1400
- }
1401
- // Add to local with addToRemote option
1402
- return this.addNouns(items, { ...options, addToRemote: true });
1403
- }
1404
1533
  /**
1405
1534
  * Filter search results by service
1406
1535
  * @param results Search results to filter
@@ -1679,6 +1808,12 @@ export class BrainyData {
1679
1808
  * @param options Simple search options (metadata filters only)
1680
1809
  * @returns Vector search results
1681
1810
  */
1811
+ // ================================================================
1812
+ // SECTION 3: SEARCH & DISCOVERY
1813
+ // ================================================================
1814
+ // Vector search, semantic search, and content discovery operations
1815
+ // Includes find(), search(), searchLocal(), findSimilar() and related methods
1816
+ // Powers the Triple Intelligence search combining vector + graph + field queries
1682
1817
  /**
1683
1818
  * 🔍 Simple Vector Similarity Search - Clean wrapper around find()
1684
1819
  *
@@ -1700,19 +1835,22 @@ export class BrainyData {
1700
1835
  * })
1701
1836
  */
1702
1837
  async search(queryVectorOrData, options = {}) {
1703
- // Build metadata filter from options
1704
- const metadataFilter = { ...options.metadata };
1838
+ // Comprehensive input validation
1839
+ const validatedQuery = validateSearchQuery(queryVectorOrData, 'queryVectorOrData');
1840
+ const validatedOptions = validateSearchOptions(options, 'options');
1841
+ // Build metadata filter from validated options
1842
+ const metadataFilter = { ...validatedOptions.metadata };
1705
1843
  // Add noun type filtering
1706
- if (options.nounTypes && options.nounTypes.length > 0) {
1707
- metadataFilter.nounType = { in: options.nounTypes };
1844
+ if (validatedOptions.nounTypes && validatedOptions.nounTypes.length > 0) {
1845
+ metadataFilter.nounType = { in: validatedOptions.nounTypes };
1708
1846
  }
1709
1847
  // Add item ID filtering
1710
- if (options.itemIds && options.itemIds.length > 0) {
1711
- metadataFilter.id = { in: options.itemIds };
1848
+ if (validatedOptions.itemIds && validatedOptions.itemIds.length > 0) {
1849
+ metadataFilter.id = { in: validatedOptions.itemIds };
1712
1850
  }
1713
1851
  // Build simple TripleQuery for vector similarity
1714
1852
  const tripleQuery = {
1715
- like: queryVectorOrData
1853
+ like: validatedQuery
1716
1854
  };
1717
1855
  // Add metadata filter if we have conditions
1718
1856
  if (Object.keys(metadataFilter).length > 0) {
@@ -1720,17 +1858,17 @@ export class BrainyData {
1720
1858
  }
1721
1859
  // Extract find() options
1722
1860
  const findOptions = {
1723
- limit: options.limit,
1724
- offset: options.offset,
1725
- cursor: options.cursor,
1726
- excludeDeleted: options.excludeDeleted,
1727
- timeout: options.timeout
1861
+ limit: validatedOptions.limit,
1862
+ offset: validatedOptions.offset,
1863
+ cursor: validatedOptions.cursor,
1864
+ excludeDeleted: validatedOptions.excludeDeleted,
1865
+ timeout: validatedOptions.timeout
1728
1866
  };
1729
1867
  // Call find() with structured query - this is the key simplification!
1730
1868
  let results = await this.find(tripleQuery, findOptions);
1731
1869
  // Apply threshold filtering if specified
1732
- if (options.threshold !== undefined) {
1733
- results = results.filter(r => (r.fusionScore || r.score || 0) >= options.threshold);
1870
+ if (validatedOptions.threshold !== undefined) {
1871
+ results = results.filter(r => (r.fusionScore || r.score || 0) >= validatedOptions.threshold);
1734
1872
  }
1735
1873
  // Convert to SearchResult format
1736
1874
  return results.map(r => ({
@@ -1843,11 +1981,9 @@ export class BrainyData {
1843
1981
  if (options.searchMode === 'local') {
1844
1982
  return this.searchLocal(queryVectorOrData, k, options);
1845
1983
  }
1846
- else if (options.searchMode === 'remote') {
1847
- return this.searchRemote(queryVectorOrData, k, options);
1848
- }
1849
- else if (options.searchMode === 'combined') {
1850
- return this.searchCombined(queryVectorOrData, k, options);
1984
+ else if (options.searchMode === 'remote' || options.searchMode === 'combined') {
1985
+ // Remote and combined search modes not supported - fall back to local
1986
+ return this.searchLocal(queryVectorOrData, k, options);
1851
1987
  }
1852
1988
  // Generate deduplication key for concurrent request handling
1853
1989
  const dedupeKey = RequestDeduplicator.getSearchKey(typeof queryVectorOrData === 'string' ? queryVectorOrData : JSON.stringify(queryVectorOrData), k, options);
@@ -3135,6 +3271,12 @@ export class BrainyData {
3135
3271
  searchMemoryUsage: this.cache?.getMemoryUsage() || 0
3136
3272
  };
3137
3273
  }
3274
+ // ================================================================
3275
+ // SECTION 8: CACHE & PERFORMANCE
3276
+ // ================================================================
3277
+ // Caching, performance optimization, and memory management
3278
+ // Includes clearCache(), performance tuning, and optimization utilities
3279
+ // Cache management for improved response times and resource efficiency
3138
3280
  /**
3139
3281
  * Clear search cache manually (useful for testing or memory management)
3140
3282
  */
@@ -3303,6 +3445,12 @@ export class BrainyData {
3303
3445
  // Ignore errors in size calculation
3304
3446
  }
3305
3447
  }
3448
+ // ================================================================
3449
+ // SECTION 7: STATISTICS & MONITORING
3450
+ // ================================================================
3451
+ // Analytics, monitoring, and metrics collection operations
3452
+ // Includes getStatistics(), getServiceStatistics(), performance monitoring
3453
+ // System health reporting and data analytics for optimization
3306
3454
  /**
3307
3455
  * Get statistics about the current state of the database
3308
3456
  * @param options Additional options for retrieving statistics
@@ -4065,102 +4213,6 @@ export class BrainyData {
4065
4213
  throw new Error(`Failed to search with text query: ${error}`);
4066
4214
  }
4067
4215
  }
4068
- /**
4069
- * Search a remote Brainy server for similar vectors
4070
- * @param queryVectorOrData Query vector or data to search for
4071
- * @param k Number of results to return
4072
- * @param options Additional options
4073
- * @returns Array of search results
4074
- */
4075
- async searchRemote(queryVectorOrData, k = 10, options = {}) {
4076
- // TODO: Remote server search will be implemented in post-2.0.0 release
4077
- await this.ensureInitialized();
4078
- this.checkWriteOnly();
4079
- throw new Error('Remote server search functionality not yet implemented in Brainy 2.0.0');
4080
- }
4081
- /**
4082
- * Search both local and remote Brainy instances, combining the results
4083
- * @param queryVectorOrData Query vector or data to search for
4084
- * @param k Number of results to return
4085
- * @param options Additional options
4086
- * @returns Array of search results
4087
- */
4088
- async searchCombined(queryVectorOrData, k = 10, options = {}) {
4089
- await this.ensureInitialized();
4090
- // Check if database is in write-only mode
4091
- this.checkWriteOnly();
4092
- // Check if connected to a remote server
4093
- if (!this.isConnectedToRemoteServer()) {
4094
- // If not connected to a remote server, just search locally
4095
- return this.searchLocal(queryVectorOrData, k, options);
4096
- }
4097
- try {
4098
- // Default to searching local first
4099
- const localFirst = options.localFirst !== false;
4100
- if (localFirst) {
4101
- // Search local first
4102
- const localResults = await this.searchLocal(queryVectorOrData, k, options);
4103
- // If we have enough local results, return them
4104
- if (localResults.length >= k) {
4105
- return localResults;
4106
- }
4107
- // Otherwise, search remote for additional results
4108
- const remoteResults = await this.searchRemote(queryVectorOrData, k - localResults.length, { ...options, storeResults: true });
4109
- // Combine results, removing duplicates
4110
- const combinedResults = [...localResults];
4111
- const localIds = new Set(localResults.map((r) => r.id));
4112
- for (const result of remoteResults) {
4113
- if (!localIds.has(result.id)) {
4114
- combinedResults.push(result);
4115
- }
4116
- }
4117
- return combinedResults;
4118
- }
4119
- else {
4120
- // Search remote first
4121
- const remoteResults = await this.searchRemote(queryVectorOrData, k, {
4122
- ...options,
4123
- storeResults: true
4124
- });
4125
- // If we have enough remote results, return them
4126
- if (remoteResults.length >= k) {
4127
- return remoteResults;
4128
- }
4129
- // Otherwise, search local for additional results
4130
- const localResults = await this.searchLocal(queryVectorOrData, k - remoteResults.length, options);
4131
- // Combine results, removing duplicates
4132
- const combinedResults = [...remoteResults];
4133
- const remoteIds = new Set(remoteResults.map((r) => r.id));
4134
- for (const result of localResults) {
4135
- if (!remoteIds.has(result.id)) {
4136
- combinedResults.push(result);
4137
- }
4138
- }
4139
- return combinedResults;
4140
- }
4141
- }
4142
- catch (error) {
4143
- console.error('Failed to perform combined search:', error);
4144
- throw new Error(`Failed to perform combined search: ${error}`);
4145
- }
4146
- }
4147
- /**
4148
- * Check if the instance is connected to a remote server
4149
- * @returns True if connected to a remote server, false otherwise
4150
- */
4151
- isConnectedToRemoteServer() {
4152
- // TODO: Remote server connections will be implemented in post-2.0.0 release
4153
- return false;
4154
- }
4155
- /**
4156
- * Disconnect from the remote server
4157
- * @returns True if successfully disconnected, false if not connected
4158
- */
4159
- async disconnectFromRemoteServer() {
4160
- // TODO: Remote server disconnection will be implemented in post-2.0.0 release
4161
- console.warn('disconnectFromRemoteServer: Remote server functionality not yet implemented in Brainy 2.0.0');
4162
- return false;
4163
- }
4164
4216
  /**
4165
4217
  * Ensure the database is initialized
4166
4218
  */
@@ -4289,10 +4341,6 @@ export class BrainyData {
4289
4341
  // Continue with shutdown even if statistics flush fails
4290
4342
  }
4291
4343
  }
4292
- // Disconnect from remote server if connected
4293
- if (this.isConnectedToRemoteServer()) {
4294
- await this.disconnectFromRemoteServer();
4295
- }
4296
4344
  // Clean up worker pools to release resources
4297
4345
  cleanupWorkerPools();
4298
4346
  // Additional cleanup could be added here in the future
@@ -4853,6 +4901,12 @@ export class BrainyData {
4853
4901
  // 6. update() - Update noun data/metadata with index sync
4854
4902
  // 7. delete() - Smart delete with soft delete default (enhanced original)
4855
4903
  // ========================================
4904
+ // ================================================================
4905
+ // SECTION 6: IMPORT & DATA INGESTION
4906
+ // ================================================================
4907
+ // Bulk data import and processing operations
4908
+ // Includes import(), importSparseData() with neural type detection
4909
+ // Smart parsing of CSV, JSON, YAML and automatic relationship extraction
4856
4910
  /**
4857
4911
  * Neural Import - Smart bulk data import with semantic type detection
4858
4912
  * Uses transformer embeddings to automatically detect and classify data types
@@ -4906,6 +4960,12 @@ export class BrainyData {
4906
4960
  * @param metadata Additional metadata
4907
4961
  * @returns Created noun ID
4908
4962
  */
4963
+ // ================================================================
4964
+ // SECTION 4: NOUN OPERATIONS (CRUD)
4965
+ // ================================================================
4966
+ // Create, Read, Update, Delete operations for noun entities
4967
+ // Includes addNoun(), addNouns(), getNoun(), getNouns(), updateNoun(), deleteNoun()
4968
+ // Core data storage and retrieval operations with metadata management
4909
4969
  /**
4910
4970
  * Add a noun to the database with required type
4911
4971
  * Clean 2.0 API - primary method for adding data
@@ -4926,33 +4986,62 @@ export class BrainyData {
4926
4986
  await this.ensureInitialized();
4927
4987
  // Check if database is in read-only mode
4928
4988
  this.checkReadOnly();
4929
- // Validate input is not null or undefined
4930
- if (vectorOrData === null || vectorOrData === undefined) {
4931
- throw new Error('Input cannot be null or undefined');
4989
+ // Distributed routing for add operations
4990
+ if (this.shardManager && this.networkTransport && !options.id) {
4991
+ // Generate ID early for consistent shard routing
4992
+ const id = uuidv4();
4993
+ // Determine which shard this data belongs to
4994
+ const shardAssignment = this.shardManager.getShardForKey(id);
4995
+ // If this shard is owned by another node, forward the request
4996
+ if (shardAssignment && shardAssignment.nodeId &&
4997
+ shardAssignment.nodeId !== this.networkTransport.nodeId) {
4998
+ try {
4999
+ const response = await this.networkTransport.sendToNode(shardAssignment.nodeId, 'DISTRIBUTED_ADD', {
5000
+ data: vectorOrData,
5001
+ type: nounType,
5002
+ metadata: enrichedMetadata,
5003
+ id // Use the generated ID
5004
+ });
5005
+ if (response.success) {
5006
+ return response.id;
5007
+ }
5008
+ else {
5009
+ throw new Error(`Remote add failed: ${response.error}`);
5010
+ }
5011
+ }
5012
+ catch (error) {
5013
+ console.warn(`Failed to forward add to ${shardAssignment.nodeId}, falling back to local add:`, error);
5014
+ // Fall through to local add
5015
+ }
5016
+ }
5017
+ // If we're here, either we own the shard or forwarding failed
5018
+ options.id = id; // Use the generated ID for local add
4932
5019
  }
5020
+ // Comprehensive input validation
5021
+ const validatedData = validateDataInput(vectorOrData, 'vectorOrData');
4933
5022
  try {
4934
5023
  let vector;
4935
- if (Array.isArray(vectorOrData)) {
4936
- for (let i = 0; i < vectorOrData.length; i++) {
4937
- if (typeof vectorOrData[i] !== 'number') {
5024
+ if (Array.isArray(validatedData)) {
5025
+ for (let i = 0; i < validatedData.length; i++) {
5026
+ if (typeof validatedData[i] !== 'number') {
4938
5027
  throw new Error('Vector contains non-numeric values');
4939
5028
  }
4940
5029
  }
4941
5030
  }
4942
5031
  // Check if input is already a vector
4943
- if (Array.isArray(vectorOrData) && !options.forceEmbed) {
5032
+ if (Array.isArray(validatedData) && !options.forceEmbed) {
4944
5033
  // Input is already a vector (and we've validated it contains only numbers)
4945
- vector = vectorOrData;
5034
+ vector = validatedData;
4946
5035
  }
4947
5036
  else {
4948
5037
  // Input needs to be vectorized
4949
5038
  try {
4950
5039
  // Check if input is a JSON object and process it specially
4951
- if (typeof vectorOrData === 'object' &&
4952
- vectorOrData !== null &&
4953
- !Array.isArray(vectorOrData)) {
5040
+ if (typeof validatedData === 'object' &&
5041
+ validatedData !== null &&
5042
+ !Array.isArray(validatedData)) {
4954
5043
  // Process JSON object for better vectorization
4955
- const preparedText = prepareJsonForVectorization(vectorOrData, {
5044
+ const preparedText = prepareJsonForVectorization(validatedData, {
4956
5045
  // Prioritize common name/title fields if they exist
4957
5046
  priorityFields: [
4958
5047
  'name',
@@ -4971,17 +5060,17 @@ export class BrainyData {
4971
5060
  // 2. addNoun(object) - vectorize object text, store object as metadata
4972
5061
  // 3. addNoun(object, metadata) - vectorize object text, store provided metadata
4973
5062
  if (!enrichedMetadata || Object.keys(enrichedMetadata).length === 1) { // Only has 'noun' key
4974
- enrichedMetadata = { ...vectorOrData, noun: validatedType };
5063
+ enrichedMetadata = { ...validatedData, noun: validatedType };
4975
5064
  }
4976
5065
  // Track field names for this JSON document
4977
5066
  const service = this.getServiceName(options);
4978
5067
  if (this.storage) {
4979
- await this.storage.trackFieldNames(vectorOrData, service);
5068
+ await this.storage.trackFieldNames(validatedData, service);
4980
5069
  }
4981
5070
  }
4982
5071
  else {
4983
5072
  // Use standard embedding for non-JSON data
4984
- vector = await this.embeddingFunction(vectorOrData);
5073
+ vector = await this.embeddingFunction(validatedData);
4985
5074
  }
4986
5075
  }
4987
5076
  catch (embedError) {
@@ -5166,15 +5255,6 @@ export class BrainyData {
5166
5255
  const vectorCount = await this.getNounCount();
5167
5256
  this.monitoring.updateVectorCount(vectorCount);
5168
5257
  }
5169
- // If addToRemote is true and we're connected to a remote server, add to remote as well
5170
- if (options.addToRemote && this.isConnectedToRemoteServer()) {
5171
- try {
5172
- await this.addToRemote(id, vector, enrichedMetadata);
5173
- }
5174
- catch (remoteError) {
5175
- console.warn(`Failed to add to remote server: ${remoteError}. Continuing with local add.`);
5176
- }
5177
- }
5178
5258
  // Invalidate search cache since data has changed
5179
5259
  this.cache?.invalidateOnDataChange('add');
5180
5260
  // Determine processing mode
@@ -5214,6 +5294,12 @@ export class BrainyData {
5214
5294
  throw new Error(`Failed to add vector: ${error}`);
5215
5295
  }
5216
5296
  }
5297
+ // ================================================================
5298
+ // SECTION 5: GRAPH OPERATIONS (VERBS)
5299
+ // ================================================================
5300
+ // Relationship and graph operations for verb entities
5301
+ // Includes addVerb(), addVerbs(), getVerb(), getVerbs(), relationship queries
5302
+ // Manages typed connections between nouns with metadata and weights
5217
5303
  /**
5218
5304
  * Add Verb - Unified relationship creation between nouns
5219
5305
  * Creates typed relationships with proper vector embeddings from metadata
@@ -5240,10 +5326,10 @@ export class BrainyData {
5240
5326
  const sourceNoun = this.index.getNouns().get(sourceId);
5241
5327
  const targetNoun = this.index.getNouns().get(targetId);
5242
5328
  if (!sourceNoun) {
5243
- throw new Error(`Source noun with ID ${sourceId} does not exist`);
5329
+ throw BrainyError.notFound(`Source noun with ID ${sourceId}`);
5244
5330
  }
5245
5331
  if (!targetNoun) {
5246
- throw new Error(`Target noun with ID ${targetId} does not exist`);
5332
+ throw BrainyError.notFound(`Target noun with ID ${targetId}`);
5247
5333
  }
5248
5334
  // Create embeddable text from verb type and metadata for searchability
5249
5335
  let embeddingText = `${verbType} relationship`;
@@ -5809,7 +5895,7 @@ export class BrainyData {
5809
5895
  // For data updates, we need to regenerate the vector
5810
5896
  const existingNoun = this.index.getNouns().get(id);
5811
5897
  if (!existingNoun) {
5812
- throw new Error(`Noun with ID ${id} does not exist`);
5898
+ throw BrainyError.notFound(`Noun with ID ${id}`);
5813
5899
  }
5814
5900
  // Get existing metadata from storage (not just from index)
5815
5901
  const existingMetadata = await this.storage.getMetadata(id) || {};
@@ -5898,7 +5984,7 @@ export class BrainyData {
5898
5984
  // Check if a vector exists
5899
5985
  const noun = this.index.getNouns().get(id);
5900
5986
  if (!noun) {
5901
- throw new Error(`Vector with ID ${id} does not exist`);
5987
+ throw BrainyError.notFound(`Vector with ID ${id}`);
5902
5988
  }
5903
5989
  // Get existing metadata to preserve namespaces
5904
5990
  const existing = await this.storage.getMetadata(id) || {};
@@ -6028,60 +6114,9 @@ export class BrainyData {
6028
6114
  const { limit = 10, offset = 0, cursor, mode = 'auto', maxDepth = 2, parallel = true, timeout, excludeDeleted = true } = options || {};
6029
6115
  // Validate and cap limit for safety
6030
6116
  const safeLimit = Math.min(limit, 10000);
6031
- if (!this._tripleEngine) {
6032
- this._tripleEngine = new TripleIntelligenceEngine(this);
6033
- }
6034
- // 🎆 NATURAL LANGUAGE AUTO-BREAKDOWN
6035
- // If query is a string, auto-convert to structured Triple Intelligence query
6036
- let processedQuery;
6037
- if (typeof query === 'string') {
6038
- // Use Brainy's sophisticated natural language processing
6039
- processedQuery = await this.processNaturalLanguage(query);
6040
- }
6041
- else {
6042
- processedQuery = query;
6043
- }
6044
- // Apply pagination options
6045
- processedQuery.limit = safeLimit;
6046
- // Handle cursor-based pagination
6047
- if (cursor) {
6048
- const decodedCursor = this.decodeCursor(cursor);
6049
- processedQuery.offset = decodedCursor.offset;
6050
- }
6051
- else if (offset > 0) {
6052
- processedQuery.offset = offset;
6053
- }
6054
- // Add soft-delete filter using POSITIVE match (O(1) hash lookup)
6055
- // We use _brainy.deleted to avoid conflicts with user metadata
6056
- if (excludeDeleted) {
6057
- if (!processedQuery.where) {
6058
- processedQuery.where = {};
6059
- }
6060
- // Use namespaced field for O(1) hash lookup in metadata index
6061
- processedQuery.where['_brainy.deleted'] = false; // or { equals: false }
6062
- }
6063
- // Apply mode-specific optimizations
6064
- if (mode !== 'auto') {
6065
- processedQuery.mode = mode;
6066
- }
6067
- // Apply graph traversal depth limit
6068
- if (processedQuery.connected) {
6069
- processedQuery.connected.maxDepth = Math.min(processedQuery.connected.maxDepth || maxDepth, maxDepth);
6070
- }
6071
- // Execute with Triple Intelligence engine
6072
- const results = await this._tripleEngine.find(processedQuery);
6073
- // Generate next cursor if we hit the limit
6074
- if (results.length === safeLimit) {
6075
- const nextCursor = this.encodeCursor({
6076
- offset: (offset || 0) + safeLimit,
6077
- timestamp: Date.now()
6078
- });
6079
- // Attach cursor to last result for convenience
6080
- if (results.length > 0) {
6081
- results[results.length - 1].nextCursor = nextCursor;
6082
- }
6083
- }
6084
- return results;
6117
+ // Triple Intelligence now requires Brainy, not BrainyData
6118
+ // BrainyData is deprecated - use Brainy.find() instead
6119
+ throw new Error('Triple Intelligence search is not available in BrainyData. Please use Brainy.find() instead.');
6085
6120
  }
6086
6121
  /**
6087
6122
  * 🧠 NATURAL LANGUAGE PROCESSING - Auto-breakdown using all Brainy features
@@ -6231,7 +6266,7 @@ export class BrainyData {
6231
6266
  * @returns The BrainyData instance for chaining
6232
6267
  */
6233
6268
  unregister(name) {
6234
- augmentationPipeline.unregister(name);
6269
+ // Deprecated: use brain.augmentations instead
6235
6270
  return this;
6236
6271
  }
6237
6272
  /**
@@ -6242,7 +6277,8 @@ export class BrainyData {
6242
6277
  * @returns True if augmentation was found and enabled
6243
6278
  */
6244
6279
  enableAugmentation(name) {
6245
- return augmentationPipeline.enableAugmentation(name);
6280
+ // Deprecated: use brain.augmentations instead
6281
+ return false;
6246
6282
  }
6247
6283
  /**
6248
6284
  * Disable an augmentation by name
@@ -6252,7 +6288,8 @@ export class BrainyData {
6252
6288
  * @returns True if augmentation was found and disabled
6253
6289
  */
6254
6290
  disableAugmentation(name) {
6255
- return augmentationPipeline.disableAugmentation(name);
6291
+ // Deprecated: use brain.augmentations instead
6292
+ return false;
6256
6293
  }
6257
6294
  /**
6258
6295
  * Check if an augmentation is enabled
@@ -6261,7 +6298,8 @@ export class BrainyData {
6261
6298
  * @returns True if augmentation is found and enabled, false otherwise
6262
6299
  */
6263
6300
  isAugmentationEnabled(name) {
6264
- return augmentationPipeline.isAugmentationEnabled(name);
6301
+ // Deprecated: use brain.augmentations instead
6302
+ return false;
6265
6303
  }
6266
6304
  /**
6267
6305
  * Get all augmentations with their enabled status
@@ -6285,7 +6323,8 @@ export class BrainyData {
6285
6323
  * @returns Number of augmentations enabled
6286
6324
  */
6287
6325
  enableAugmentationType(type) {
6288
- return augmentationPipeline.enableAugmentationType(type);
6326
+ // Deprecated: use brain.augmentations instead
6327
+ return 0;
6289
6328
  }
6290
6329
  /**
6291
6330
  * Disable all augmentations of a specific type
@@ -6294,7 +6333,8 @@ export class BrainyData {
6294
6333
  * @returns Number of augmentations disabled
6295
6334
  */
6296
6335
  disableAugmentationType(type) {
6297
- return augmentationPipeline.disableAugmentationType(type);
6336
+ // Deprecated: use brain.augmentations instead
6337
+ return 0;
6298
6338
  }
6299
6339
  // ===== Enhanced Clear Methods (2.0.0 API) =====
6300
6340
  /**
@@ -6385,6 +6425,12 @@ export class BrainyData {
6385
6425
  throw new Error(`Failed to clear all data: ${error}`);
6386
6426
  }
6387
6427
  }
6428
+ // ================================================================
6429
+ // SECTION 9: UTILITIES & CLEANUP
6430
+ // ================================================================
6431
+ // System utilities, cleanup operations, and maintenance functions
6432
+ // Includes clearAll(), database maintenance, and system shutdown operations
6433
+ // Essential maintenance and administrative functionality
6388
6434
  /**
6389
6435
  * Clear all data from the database (alias for clear)
6390
6436
  * @param options Options including force flag to skip confirmation