@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
@@ -1180,7 +1180,60 @@ export class FileSystemStorage extends BaseStorage {
1180
1180
  }
1181
1181
  }
1182
1182
  // Merge statistics from both locations
1183
- return StorageCompatibilityLayer.mergeStatistics(newStats, oldStats);
1183
+ return this.mergeStatistics(newStats, oldStats);
1184
+ }
1185
+ /**
1186
+ * Merge statistics from multiple sources
1187
+ */
1188
+ mergeStatistics(storageStats, localStats) {
1189
+ // Handle null cases
1190
+ if (!storageStats && !localStats) {
1191
+ return {
1192
+ nounCount: {},
1193
+ verbCount: {},
1194
+ metadataCount: {},
1195
+ hnswIndexSize: 0,
1196
+ totalNodes: 0,
1197
+ totalEdges: 0,
1198
+ lastUpdated: new Date().toISOString()
1199
+ };
1200
+ }
1201
+ if (!storageStats)
1202
+ return localStats;
1203
+ if (!localStats)
1204
+ return storageStats;
1205
+ // Merge noun counts by taking the maximum of each type
1206
+ const mergedNounCount = {
1207
+ ...storageStats.nounCount
1208
+ };
1209
+ for (const [type, count] of Object.entries(localStats.nounCount)) {
1210
+ mergedNounCount[type] = Math.max(mergedNounCount[type] || 0, count);
1211
+ }
1212
+ // Merge verb counts by taking the maximum of each type
1213
+ const mergedVerbCount = {
1214
+ ...storageStats.verbCount
1215
+ };
1216
+ for (const [type, count] of Object.entries(localStats.verbCount)) {
1217
+ mergedVerbCount[type] = Math.max(mergedVerbCount[type] || 0, count);
1218
+ }
1219
+ // Merge metadata counts by taking the maximum of each type
1220
+ const mergedMetadataCount = {
1221
+ ...storageStats.metadataCount
1222
+ };
1223
+ for (const [type, count] of Object.entries(localStats.metadataCount)) {
1224
+ mergedMetadataCount[type] = Math.max(mergedMetadataCount[type] || 0, count);
1225
+ }
1226
+ return {
1227
+ nounCount: mergedNounCount,
1228
+ verbCount: mergedVerbCount,
1229
+ metadataCount: mergedMetadataCount,
1230
+ hnswIndexSize: Math.max(storageStats.hnswIndexSize || 0, localStats.hnswIndexSize || 0),
1231
+ totalNodes: Math.max(storageStats.totalNodes || 0, localStats.totalNodes || 0),
1232
+ totalEdges: Math.max(storageStats.totalEdges || 0, localStats.totalEdges || 0),
1233
+ totalMetadata: Math.max(storageStats.totalMetadata || 0, localStats.totalMetadata || 0),
1234
+ operations: storageStats.operations || localStats.operations,
1235
+ lastUpdated: new Date().toISOString()
1236
+ };
1184
1237
  }
1185
1238
  }
1186
1239
  //# sourceMappingURL=fileSystemStorage.js.map
@@ -35,7 +35,8 @@ export class MemoryStorage extends BaseStorage {
35
35
  id: noun.id,
36
36
  vector: [...noun.vector],
37
37
  connections: new Map(),
38
- level: noun.level || 0
38
+ level: noun.level || 0,
39
+ metadata: noun.metadata
39
40
  };
40
41
  // Copy connections
41
42
  for (const [level, connections] of noun.connections.entries()) {
@@ -59,7 +60,8 @@ export class MemoryStorage extends BaseStorage {
59
60
  id: noun.id,
60
61
  vector: [...noun.vector],
61
62
  connections: new Map(),
62
- level: noun.level || 0
63
+ level: noun.level || 0,
64
+ metadata: noun.metadata
63
65
  };
64
66
  // Copy connections
65
67
  for (const [level, connections] of noun.connections.entries()) {
@@ -89,12 +91,14 @@ export class MemoryStorage extends BaseStorage {
89
91
  const matchingIds = [];
90
92
  // Iterate through all nouns to find matches
91
93
  for (const [nounId, noun] of this.nouns.entries()) {
92
- // Get the metadata to check filters
93
- const metadata = await this.getMetadata(nounId);
94
- if (!metadata)
95
- continue;
94
+ // Check the noun's embedded metadata field
95
+ const nounMetadata = noun.metadata || {};
96
+ // Also check separate metadata store for backward compatibility
97
+ const separateMetadata = await this.getMetadata(nounId);
98
+ // Merge both metadata sources (noun.metadata takes precedence)
99
+ const metadata = { ...separateMetadata, ...nounMetadata };
96
100
  // Filter by noun type if specified
97
- if (nounTypes && !nounTypes.includes(metadata.noun)) {
101
+ if (nounTypes && metadata.noun && !nounTypes.includes(metadata.noun)) {
98
102
  continue;
99
103
  }
100
104
  // Filter by service if specified
@@ -133,7 +137,8 @@ export class MemoryStorage extends BaseStorage {
133
137
  id: noun.id,
134
138
  vector: [...noun.vector],
135
139
  connections: new Map(),
136
- level: noun.level || 0
140
+ level: noun.level || 0,
141
+ metadata: noun.metadata
137
142
  };
138
143
  // Copy connections
139
144
  for (const [level, connections] of noun.connections.entries()) {
@@ -1,84 +1,16 @@
1
1
  /**
2
- * Backward Compatibility Layer for Storage Migration
3
- *
4
- * Handles the transition from 'index' to '_system' directory
5
- * Ensures services running different versions can coexist
6
- */
7
- import { StatisticsData } from '../coreTypes.js';
8
- export interface MigrationMetadata {
9
- schemaVersion: number;
10
- migrationStarted?: string;
11
- migrationCompleted?: string;
12
- lastUpdatedBy?: string;
13
- }
14
- /**
15
- * Backward compatibility strategy for directory migration
2
+ * Storage backward compatibility layer for legacy data migrations
16
3
  */
17
4
  export declare class StorageCompatibilityLayer {
18
- private migrationMetadata;
19
- /**
20
- * Determines the read strategy based on what's available
21
- * @returns Priority-ordered list of directories to try
22
- */
23
- static getReadPriority(): string[];
24
- /**
25
- * Determines write strategy based on migration state
26
- * @param migrationComplete Whether migration is complete
27
- * @returns List of directories to write to
28
- */
29
- static getWriteTargets(migrationComplete?: boolean): string[];
30
- /**
31
- * Check if we should perform migration based on service coordination
32
- * @param existingStats Statistics from storage
33
- * @returns Whether to initiate migration
34
- */
35
- static shouldMigrate(existingStats: StatisticsData | null): boolean;
36
- /**
37
- * Creates migration metadata
38
- */
39
- static createMigrationMetadata(): MigrationMetadata;
40
- /**
41
- * Merge statistics from multiple locations (deduplication)
42
- */
43
- static mergeStatistics(primary: StatisticsData | null, fallback: StatisticsData | null): StatisticsData | null;
44
- /**
45
- * Determines if dual-write is needed based on environment
46
- * @param storageType The type of storage being used
47
- * @returns Whether to write to both old and new locations
48
- */
49
- static needsDualWrite(storageType: string): boolean;
50
- /**
51
- * Grace period for migration (30 days default)
52
- * After this period, services can stop reading from old location
53
- */
54
- static getMigrationGracePeriodMs(): number;
55
- /**
56
- * Check if migration grace period has expired
57
- */
58
- static isGracePeriodExpired(migrationStarted: string): boolean;
59
- /**
60
- * Log migration events for monitoring
61
- */
62
5
  static logMigrationEvent(event: string, details?: any): void;
6
+ static migrateIfNeeded(storagePath: string): Promise<void>;
63
7
  }
64
- /**
65
- * Storage paths helper for migration
66
- */
67
- export declare class StoragePaths {
68
- /**
69
- * Get the statistics file path for a given directory
70
- */
71
- static getStatisticsPath(baseDir: string, filename?: string): string;
72
- /**
73
- * Get distributed config path
74
- */
75
- static getDistributedConfigPath(baseDir: string): string;
76
- /**
77
- * Check if a path is using the old structure
78
- */
79
- static isLegacyPath(path: string): boolean;
80
- /**
81
- * Convert legacy path to new structure
82
- */
83
- static modernizePath(path: string): string;
8
+ export interface StoragePaths {
9
+ nouns: string;
10
+ verbs: string;
11
+ metadata: string;
12
+ index: string;
13
+ system: string;
14
+ statistics: string;
84
15
  }
16
+ export declare function getDefaultStoragePaths(basePath: string): StoragePaths;
@@ -1,141 +1,26 @@
1
1
  /**
2
- * Backward Compatibility Layer for Storage Migration
3
- *
4
- * Handles the transition from 'index' to '_system' directory
5
- * Ensures services running different versions can coexist
6
- */
7
- /**
8
- * Backward compatibility strategy for directory migration
2
+ * Storage backward compatibility layer for legacy data migrations
9
3
  */
10
4
  export class StorageCompatibilityLayer {
11
- constructor() {
12
- this.migrationMetadata = null;
13
- }
14
- /**
15
- * Determines the read strategy based on what's available
16
- * @returns Priority-ordered list of directories to try
17
- */
18
- static getReadPriority() {
19
- return ['_system', 'index']; // Try new location first, fallback to old
20
- }
21
- /**
22
- * Determines write strategy based on migration state
23
- * @param migrationComplete Whether migration is complete
24
- * @returns List of directories to write to
25
- */
26
- static getWriteTargets(migrationComplete = false) {
27
- if (migrationComplete) {
28
- return ['_system']; // Only write to new location
29
- }
30
- // During migration, write to both for compatibility
31
- return ['_system', 'index'];
32
- }
33
- /**
34
- * Check if we should perform migration based on service coordination
35
- * @param existingStats Statistics from storage
36
- * @returns Whether to initiate migration
37
- */
38
- static shouldMigrate(existingStats) {
39
- if (!existingStats)
40
- return true; // No data yet, use new structure
41
- // Check if we have migration metadata in stats
42
- const migrationData = existingStats.migrationMetadata;
43
- if (!migrationData)
44
- return true; // No migration data, start migration
45
- // Check schema version
46
- if (migrationData.schemaVersion < 2)
47
- return true;
48
- // Already migrated
49
- return false;
50
- }
51
- /**
52
- * Creates migration metadata
53
- */
54
- static createMigrationMetadata() {
55
- return {
56
- schemaVersion: 2,
57
- migrationStarted: new Date().toISOString(),
58
- lastUpdatedBy: process.env.HOSTNAME || process.env.INSTANCE_ID || 'unknown'
59
- };
60
- }
61
- /**
62
- * Merge statistics from multiple locations (deduplication)
63
- */
64
- static mergeStatistics(primary, fallback) {
65
- if (!primary && !fallback)
66
- return null;
67
- if (!fallback)
68
- return primary;
69
- if (!primary)
70
- return fallback;
71
- // Return the most recently updated
72
- const primaryTime = new Date(primary.lastUpdated).getTime();
73
- const fallbackTime = new Date(fallback.lastUpdated).getTime();
74
- return primaryTime >= fallbackTime ? primary : fallback;
75
- }
76
- /**
77
- * Determines if dual-write is needed based on environment
78
- * @param storageType The type of storage being used
79
- * @returns Whether to write to both old and new locations
80
- */
81
- static needsDualWrite(storageType) {
82
- // Only need dual-write for shared storage systems
83
- const sharedStorageTypes = ['s3', 'r2', 'gcs', 'filesystem'];
84
- return sharedStorageTypes.includes(storageType.toLowerCase());
85
- }
86
- /**
87
- * Grace period for migration (30 days default)
88
- * After this period, services can stop reading from old location
89
- */
90
- static getMigrationGracePeriodMs() {
91
- const days = parseInt(process.env.BRAINY_MIGRATION_GRACE_DAYS || '30', 10);
92
- return days * 24 * 60 * 60 * 1000;
93
- }
94
- /**
95
- * Check if migration grace period has expired
96
- */
97
- static isGracePeriodExpired(migrationStarted) {
98
- const startTime = new Date(migrationStarted).getTime();
99
- const now = Date.now();
100
- const gracePeriod = this.getMigrationGracePeriodMs();
101
- return (now - startTime) > gracePeriod;
102
- }
103
- /**
104
- * Log migration events for monitoring
105
- */
106
5
  static logMigrationEvent(event, details) {
107
- if (process.env.NODE_ENV !== 'test') {
108
- console.log(`[Brainy Storage Migration] ${event}`, details || '');
6
+ // Simplified logging for migration events
7
+ if (process.env.DEBUG_MIGRATION) {
8
+ console.log(`[Migration] ${event}`, details);
109
9
  }
110
10
  }
111
- }
112
- /**
113
- * Storage paths helper for migration
114
- */
115
- export class StoragePaths {
116
- /**
117
- * Get the statistics file path for a given directory
118
- */
119
- static getStatisticsPath(baseDir, filename = 'statistics') {
120
- return `${baseDir}/${filename}.json`;
121
- }
122
- /**
123
- * Get distributed config path
124
- */
125
- static getDistributedConfigPath(baseDir) {
126
- return `${baseDir}/distributed_config.json`;
127
- }
128
- /**
129
- * Check if a path is using the old structure
130
- */
131
- static isLegacyPath(path) {
132
- return path.includes('/index/') || path.endsWith('/index');
133
- }
134
- /**
135
- * Convert legacy path to new structure
136
- */
137
- static modernizePath(path) {
138
- return path.replace('/index/', '/_system/').replace('/index', '/_system');
11
+ static async migrateIfNeeded(storagePath) {
12
+ // No-op for now - can be extended later if needed
139
13
  }
140
14
  }
15
+ // Helper to get default paths
16
+ export function getDefaultStoragePaths(basePath) {
17
+ return {
18
+ nouns: `${basePath}/nouns`,
19
+ verbs: `${basePath}/verbs`,
20
+ metadata: `${basePath}/metadata`,
21
+ index: `${basePath}/index`,
22
+ system: `${basePath}/system`,
23
+ statistics: `${basePath}/statistics.json`
24
+ };
25
+ }
141
26
  //# sourceMappingURL=backwardCompatibility.js.map
@@ -2,6 +2,7 @@
2
2
  * Base Storage Adapter
3
3
  * Provides common functionality for all storage adapters
4
4
  */
5
+ import { GraphAdjacencyIndex } from '../graph/graphAdjacencyIndex.js';
5
6
  import { GraphVerb, HNSWNoun, HNSWVerb, StatisticsData } from '../coreTypes.js';
6
7
  import { BaseStorageAdapter } from './adapters/baseStorageAdapter.js';
7
8
  export declare const ENTITIES_DIR = "entities";
@@ -31,6 +32,7 @@ export declare function getDirectoryPath(entityType: 'noun' | 'verb', dataType:
31
32
  */
32
33
  export declare abstract class BaseStorage extends BaseStorageAdapter {
33
34
  protected isInitialized: boolean;
35
+ protected graphIndex?: GraphAdjacencyIndex;
34
36
  protected readOnly: boolean;
35
37
  /**
36
38
  * Initialize the storage adapter
@@ -143,6 +145,10 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
143
145
  * Delete a verb from storage
144
146
  */
145
147
  deleteVerb(id: string): Promise<void>;
148
+ /**
149
+ * Get graph index (lazy initialization)
150
+ */
151
+ getGraphIndex(): Promise<GraphAdjacencyIndex>;
146
152
  /**
147
153
  * Clear all data from storage
148
154
  * This method should be implemented by each specific adapter
@@ -2,6 +2,7 @@
2
2
  * Base Storage Adapter
3
3
  * Provides common functionality for all storage adapters
4
4
  */
5
+ import { GraphAdjacencyIndex } from '../graph/graphAdjacencyIndex.js';
5
6
  import { BaseStorageAdapter } from './adapters/baseStorageAdapter.js';
6
7
  import { validateNounType, validateVerbType } from '../utils/typeValidation.js';
7
8
  // Common directory/prefix names
@@ -520,6 +521,22 @@ export class BaseStorage extends BaseStorageAdapter {
520
521
  await this.ensureInitialized();
521
522
  return this.deleteVerb_internal(id);
522
523
  }
524
+ /**
525
+ * Get graph index (lazy initialization)
526
+ */
527
+ async getGraphIndex() {
528
+ if (!this.graphIndex) {
529
+ console.log('Initializing GraphAdjacencyIndex...');
530
+ this.graphIndex = new GraphAdjacencyIndex(this);
531
+ // Check if we need to rebuild from existing data
532
+ const sampleVerbs = await this.getVerbs({ pagination: { limit: 1 } });
533
+ if (sampleVerbs.items.length > 0) {
534
+ console.log('Found existing verbs, rebuilding graph index...');
535
+ await this.graphIndex.rebuild();
536
+ }
537
+ }
538
+ return this.graphIndex;
539
+ }
523
540
  /**
524
541
  * Save noun metadata to storage
525
542
  * This method should be implemented by each specific adapter
@@ -120,7 +120,7 @@ export class CacheManager {
120
120
  (this.storageStatistics.totalNodes || 0) + (this.storageStatistics.totalEdges || 0) : 0;
121
121
  // Determine if we're dealing with a large dataset (>100K items)
122
122
  const isLargeDataset = totalItems > 100000;
123
- // Check if we're in read-only mode (from parent BrainyData instance)
123
+ // Check if we're in read-only mode (from parent Brainy instance)
124
124
  const isReadOnly = this.options?.readOnly || false;
125
125
  // In Node.js, use available system memory with enhanced allocation
126
126
  if (this.environment === Environment.NODE) {
@@ -220,7 +220,7 @@ export class CacheManager {
220
220
  (this.storageStatistics.totalNodes || 0) + (this.storageStatistics.totalEdges || 0) : 0;
221
221
  // Determine if we're dealing with a large dataset (>100K items)
222
222
  const isLargeDataset = totalItems > 100000;
223
- // Check if we're in read-only mode (from parent BrainyData instance)
223
+ // Check if we're in read-only mode (from parent Brainy instance)
224
224
  const isReadOnly = this.options?.readOnly || false;
225
225
  // Get memory information based on environment
226
226
  const memoryInfo = await this.detectAvailableMemory();
@@ -309,9 +309,14 @@ export class ReadOnlyOptimizations {
309
309
  * Load segment data from storage
310
310
  */
311
311
  async loadSegmentFromStorage(segment) {
312
- // This would integrate with your S3 storage adapter
313
- // For now, return a placeholder
314
- console.log(`Loading segment ${segment.id} from storage`);
312
+ // Load segment from memory-mapped buffer if available
313
+ const cached = this.memoryMappedBuffers.get(segment.id);
314
+ if (cached) {
315
+ return cached;
316
+ }
317
+ // This feature requires actual storage backend integration (S3, file system, etc)
318
+ // Return empty buffer as this is an optional optimization feature
319
+ console.warn(`Segment loading optimization not available for segment ${segment.id}. Using standard storage.`);
315
320
  return new ArrayBuffer(0);
316
321
  }
317
322
  /**
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Streaming Pipeline System for Brainy
3
+ *
4
+ * Real implementation of streaming data pipelines with:
5
+ * - Async iterators for streaming
6
+ * - Backpressure handling
7
+ * - Auto-scaling workers
8
+ * - Checkpointing for recovery
9
+ * - Error boundaries
10
+ */
11
+ import { Brainy } from '../brainy.js';
12
+ /**
13
+ * Pipeline stage types
14
+ */
15
+ export type StageType = 'source' | 'transform' | 'filter' | 'batch' | 'sink' | 'branch' | 'merge' | 'window' | 'reduce';
16
+ /**
17
+ * Pipeline execution options
18
+ */
19
+ export interface PipelineOptions {
20
+ workers?: number | 'auto';
21
+ checkpoint?: boolean | string;
22
+ monitoring?: boolean;
23
+ maxThroughput?: number;
24
+ backpressure?: 'drop' | 'buffer' | 'pause';
25
+ retries?: number;
26
+ errorHandler?: (error: Error, item: any) => void;
27
+ bufferSize?: number;
28
+ }
29
+ /**
30
+ * Base interface for pipeline stages
31
+ */
32
+ export interface PipelineStage<T = any, R = any> {
33
+ type: StageType;
34
+ name: string;
35
+ process(input: AsyncIterable<T>): AsyncIterable<R>;
36
+ }
37
+ /**
38
+ * Streaming Pipeline Builder
39
+ */
40
+ export declare class Pipeline<T = any> {
41
+ private brainyInstance?;
42
+ private stages;
43
+ private running;
44
+ private abortController?;
45
+ private metrics;
46
+ constructor(brainyInstance?: (Brainy | Brainy<any>) | undefined);
47
+ /**
48
+ * Add a data source
49
+ */
50
+ source<S>(generator: AsyncIterable<S> | (() => AsyncIterable<S>) | AsyncGeneratorFunction): Pipeline<S>;
51
+ /**
52
+ * Transform data
53
+ */
54
+ map<R>(fn: (item: T) => R | Promise<R>): Pipeline<R>;
55
+ /**
56
+ * Filter data
57
+ */
58
+ filter(predicate: (item: T) => boolean | Promise<boolean>): Pipeline<T>;
59
+ /**
60
+ * Batch items for efficiency
61
+ */
62
+ batch(size: number, timeoutMs?: number): Pipeline<T[]>;
63
+ /**
64
+ * Sink data to a destination
65
+ */
66
+ sink(handler: (item: T) => Promise<void> | void): Pipeline<void>;
67
+ /**
68
+ * Sink data to Brainy
69
+ */
70
+ toBrainy(options?: {
71
+ type?: string;
72
+ metadata?: any;
73
+ batchSize?: number;
74
+ }): Pipeline<void>;
75
+ /**
76
+ * Sink with rate limiting
77
+ */
78
+ throttledSink(handler: (item: T) => Promise<void> | void, rateLimit: number): Pipeline<void>;
79
+ /**
80
+ * Parallel sink with worker pool
81
+ */
82
+ parallelSink(handler: (item: T) => Promise<void> | void, workers?: number): Pipeline<void>;
83
+ /**
84
+ * Collect all results
85
+ */
86
+ collect(): Promise<T[]>;
87
+ /**
88
+ * Window operations for time-based processing
89
+ */
90
+ window(size: number, type?: 'tumbling' | 'sliding'): Pipeline<T[]>;
91
+ /**
92
+ * Flatmap operation - map and flatten results
93
+ */
94
+ flatMap<R>(fn: (item: T) => R[] | Promise<R[]>): Pipeline<R>;
95
+ /**
96
+ * Tap into the pipeline for side effects without modifying data
97
+ */
98
+ tap(fn: (item: T) => void | Promise<void>): Pipeline<T>;
99
+ /**
100
+ * Retry failed operations
101
+ */
102
+ retry<R>(fn: (item: T) => R | Promise<R>, maxRetries?: number, backoff?: number): Pipeline<R>;
103
+ /**
104
+ * Buffer with backpressure handling
105
+ */
106
+ buffer(size: number, strategy?: 'drop' | 'block'): Pipeline<T>;
107
+ /**
108
+ * Fork the pipeline into multiple branches
109
+ */
110
+ fork(...branches: Array<(pipeline: Pipeline<T>) => Pipeline<any>>): Pipeline<T>;
111
+ /**
112
+ * Reduce operation
113
+ */
114
+ reduce<R>(reducer: (acc: R, item: T) => R, initial: R): Pipeline<R>;
115
+ /**
116
+ * Run the pipeline with metrics tracking
117
+ */
118
+ run(options?: PipelineOptions): Promise<void>;
119
+ /**
120
+ * Start the pipeline (alias for run)
121
+ */
122
+ start(options?: PipelineOptions): Promise<void>;
123
+ /**
124
+ * Stop the pipeline
125
+ */
126
+ stop(): void;
127
+ /**
128
+ * Monitor pipeline metrics
129
+ */
130
+ monitor(dashboard?: string): Pipeline<T>;
131
+ }
132
+ /**
133
+ * Pipeline factory function
134
+ */
135
+ export declare function createPipeline(brain?: Brainy): Pipeline;
136
+ /**
137
+ * Backward compatibility exports
138
+ */
139
+ export declare const pipeline: Pipeline<any>;
140
+ export declare enum ExecutionMode {
141
+ SEQUENTIAL = "sequential",
142
+ PARALLEL = "parallel",
143
+ FIRST_SUCCESS = "firstSuccess",
144
+ FIRST_RESULT = "firstResult",
145
+ THREADED = "threaded"
146
+ }
147
+ export type PipelineResult<T> = {
148
+ success: boolean;
149
+ data: T;
150
+ error?: string;
151
+ };
152
+ export type StreamlinedPipelineOptions = PipelineOptions;
153
+ export type StreamlinedPipelineResult<T> = PipelineResult<T>;
154
+ export { ExecutionMode as StreamlinedExecutionMode };