@soulcraft/brainy 3.0.0 → 3.1.0

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 (270) hide show
  1. package/CHANGELOG.md +53 -3
  2. package/README.md +427 -111
  3. package/bin/brainy.js +340 -62
  4. package/dist/api/ConfigAPI.d.ts +67 -0
  5. package/dist/api/ConfigAPI.js +166 -0
  6. package/dist/api/DataAPI.d.ts +123 -0
  7. package/dist/api/DataAPI.js +391 -0
  8. package/dist/api/SecurityAPI.d.ts +50 -0
  9. package/dist/api/SecurityAPI.js +139 -0
  10. package/dist/api/UniversalImportAPI.d.ts +134 -0
  11. package/dist/api/UniversalImportAPI.js +615 -0
  12. package/dist/augmentationManager.js +12 -7
  13. package/dist/augmentationPipeline.d.ts +0 -61
  14. package/dist/augmentationPipeline.js +0 -87
  15. package/dist/augmentationRegistry.d.ts +1 -1
  16. package/dist/augmentationRegistry.js +1 -1
  17. package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
  18. package/dist/augmentations/apiServerAugmentation.js +290 -9
  19. package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
  20. package/dist/augmentations/auditLogAugmentation.js +358 -0
  21. package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
  22. package/dist/augmentations/batchProcessingAugmentation.js +123 -22
  23. package/dist/augmentations/brainyAugmentation.d.ts +142 -8
  24. package/dist/augmentations/brainyAugmentation.js +179 -2
  25. package/dist/augmentations/cacheAugmentation.d.ts +8 -5
  26. package/dist/augmentations/cacheAugmentation.js +116 -17
  27. package/dist/augmentations/conduitAugmentations.d.ts +2 -2
  28. package/dist/augmentations/conduitAugmentations.js +2 -2
  29. package/dist/augmentations/configResolver.d.ts +122 -0
  30. package/dist/augmentations/configResolver.js +440 -0
  31. package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
  32. package/dist/augmentations/connectionPoolAugmentation.js +37 -12
  33. package/dist/augmentations/defaultAugmentations.d.ts +14 -10
  34. package/dist/augmentations/defaultAugmentations.js +16 -11
  35. package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
  36. package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
  37. package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
  38. package/dist/augmentations/discovery/localDiscovery.js +246 -0
  39. package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
  40. package/dist/augmentations/discovery/runtimeLoader.js +337 -0
  41. package/dist/augmentations/discovery.d.ts +152 -0
  42. package/dist/augmentations/discovery.js +441 -0
  43. package/dist/augmentations/display/cache.d.ts +130 -0
  44. package/dist/augmentations/display/cache.js +319 -0
  45. package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
  46. package/dist/augmentations/display/fieldPatterns.js +393 -0
  47. package/dist/augmentations/display/iconMappings.d.ts +57 -0
  48. package/dist/augmentations/display/iconMappings.js +68 -0
  49. package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
  50. package/dist/augmentations/display/intelligentComputation.js +462 -0
  51. package/dist/augmentations/display/types.d.ts +203 -0
  52. package/dist/augmentations/display/types.js +7 -0
  53. package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
  54. package/dist/augmentations/entityRegistryAugmentation.js +5 -1
  55. package/dist/augmentations/indexAugmentation.d.ts +5 -3
  56. package/dist/augmentations/indexAugmentation.js +5 -2
  57. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
  58. package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
  59. package/dist/augmentations/manifest.d.ts +176 -0
  60. package/dist/augmentations/manifest.js +8 -0
  61. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
  62. package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
  63. package/dist/augmentations/marketplace/cli.d.ts +47 -0
  64. package/dist/augmentations/marketplace/cli.js +265 -0
  65. package/dist/augmentations/metricsAugmentation.d.ts +3 -3
  66. package/dist/augmentations/metricsAugmentation.js +2 -2
  67. package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
  68. package/dist/augmentations/monitoringAugmentation.js +2 -2
  69. package/dist/augmentations/neuralImport.d.ts +1 -1
  70. package/dist/augmentations/neuralImport.js +4 -4
  71. package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
  72. package/dist/augmentations/rateLimitAugmentation.js +321 -0
  73. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
  74. package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
  75. package/dist/augmentations/storageAugmentation.d.ts +1 -1
  76. package/dist/augmentations/storageAugmentation.js +2 -2
  77. package/dist/augmentations/storageAugmentations.d.ts +37 -8
  78. package/dist/augmentations/storageAugmentations.js +204 -15
  79. package/dist/augmentations/synapseAugmentation.d.ts +1 -1
  80. package/dist/augmentations/synapseAugmentation.js +35 -16
  81. package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
  82. package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
  83. package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
  84. package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
  85. package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
  86. package/dist/augmentations/universalDisplayAugmentation.js +371 -0
  87. package/dist/brainy-unified.d.ts +106 -0
  88. package/dist/brainy-unified.js +327 -0
  89. package/dist/brainy.d.ts +277 -0
  90. package/dist/brainy.js +1241 -0
  91. package/dist/brainyData.d.ts +56 -111
  92. package/dist/brainyData.js +912 -756
  93. package/dist/brainyDataV3.d.ts +186 -0
  94. package/dist/brainyDataV3.js +337 -0
  95. package/dist/config/distributedPresets-new.d.ts +118 -0
  96. package/dist/config/distributedPresets-new.js +318 -0
  97. package/dist/config/distributedPresets.d.ts +118 -0
  98. package/dist/config/distributedPresets.js +318 -0
  99. package/dist/config/extensibleConfig.d.ts +99 -0
  100. package/dist/config/extensibleConfig.js +268 -0
  101. package/dist/config/index.d.ts +17 -0
  102. package/dist/config/index.js +35 -0
  103. package/dist/config/modelAutoConfig.d.ts +32 -0
  104. package/dist/config/modelAutoConfig.js +139 -0
  105. package/dist/config/modelPrecisionManager.d.ts +42 -0
  106. package/dist/config/modelPrecisionManager.js +98 -0
  107. package/dist/config/sharedConfigManager.d.ts +67 -0
  108. package/dist/config/sharedConfigManager.js +215 -0
  109. package/dist/config/storageAutoConfig.d.ts +41 -0
  110. package/dist/config/storageAutoConfig.js +328 -0
  111. package/dist/config/zeroConfig.d.ts +68 -0
  112. package/dist/config/zeroConfig.js +301 -0
  113. package/dist/cortex/backupRestore.d.ts +2 -2
  114. package/dist/cortex/backupRestore.js +85 -27
  115. package/dist/cortex/healthCheck.d.ts +2 -2
  116. package/dist/cortex/neuralImport.d.ts +2 -2
  117. package/dist/cortex/neuralImport.js +18 -13
  118. package/dist/cortex/performanceMonitor.d.ts +2 -2
  119. package/dist/critical/model-guardian.d.ts +4 -0
  120. package/dist/critical/model-guardian.js +31 -11
  121. package/dist/demo.d.ts +4 -4
  122. package/dist/demo.js +7 -7
  123. package/dist/distributed/cacheSync.d.ts +112 -0
  124. package/dist/distributed/cacheSync.js +265 -0
  125. package/dist/distributed/coordinator.d.ts +193 -0
  126. package/dist/distributed/coordinator.js +548 -0
  127. package/dist/distributed/httpTransport.d.ts +120 -0
  128. package/dist/distributed/httpTransport.js +446 -0
  129. package/dist/distributed/index.d.ts +8 -0
  130. package/dist/distributed/index.js +5 -0
  131. package/dist/distributed/networkTransport.d.ts +132 -0
  132. package/dist/distributed/networkTransport.js +633 -0
  133. package/dist/distributed/queryPlanner.d.ts +104 -0
  134. package/dist/distributed/queryPlanner.js +327 -0
  135. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  136. package/dist/distributed/readWriteSeparation.js +350 -0
  137. package/dist/distributed/shardManager.d.ts +114 -0
  138. package/dist/distributed/shardManager.js +357 -0
  139. package/dist/distributed/shardMigration.d.ts +110 -0
  140. package/dist/distributed/shardMigration.js +289 -0
  141. package/dist/distributed/storageDiscovery.d.ts +160 -0
  142. package/dist/distributed/storageDiscovery.js +551 -0
  143. package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
  144. package/dist/embeddings/CachedEmbeddings.js +146 -0
  145. package/dist/embeddings/EmbeddingManager.d.ts +102 -0
  146. package/dist/embeddings/EmbeddingManager.js +291 -0
  147. package/dist/embeddings/SingletonModelManager.d.ts +95 -0
  148. package/dist/embeddings/SingletonModelManager.js +220 -0
  149. package/dist/embeddings/index.d.ts +12 -0
  150. package/dist/embeddings/index.js +16 -0
  151. package/dist/embeddings/lightweight-embedder.d.ts +0 -1
  152. package/dist/embeddings/lightweight-embedder.js +4 -12
  153. package/dist/embeddings/model-manager.d.ts +11 -0
  154. package/dist/embeddings/model-manager.js +43 -7
  155. package/dist/embeddings/universal-memory-manager.d.ts +1 -1
  156. package/dist/embeddings/universal-memory-manager.js +27 -67
  157. package/dist/embeddings/worker-embedding.js +4 -8
  158. package/dist/errors/brainyError.d.ts +5 -1
  159. package/dist/errors/brainyError.js +12 -0
  160. package/dist/examples/basicUsage.js +7 -4
  161. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  162. package/dist/graph/graphAdjacencyIndex.js +288 -0
  163. package/dist/graph/pathfinding.js +4 -2
  164. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  165. package/dist/importManager.js +8 -5
  166. package/dist/index.d.ts +17 -22
  167. package/dist/index.js +37 -23
  168. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  169. package/dist/mcp/brainyMCPAdapter.js +5 -5
  170. package/dist/mcp/brainyMCPService.d.ts +3 -3
  171. package/dist/mcp/brainyMCPService.js +3 -11
  172. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  173. package/dist/neural/embeddedPatterns.d.ts +1 -1
  174. package/dist/neural/embeddedPatterns.js +2 -2
  175. package/dist/neural/entityExtractor.d.ts +65 -0
  176. package/dist/neural/entityExtractor.js +316 -0
  177. package/dist/neural/improvedNeuralAPI.d.ts +357 -0
  178. package/dist/neural/improvedNeuralAPI.js +2628 -0
  179. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  180. package/dist/neural/naturalLanguageProcessor.js +941 -66
  181. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  182. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  183. package/dist/neural/neuralAPI.js +8 -2
  184. package/dist/neural/patternLibrary.d.ts +57 -3
  185. package/dist/neural/patternLibrary.js +348 -13
  186. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  187. package/dist/neural/staticPatternMatcher.js +2 -2
  188. package/dist/neural/types.d.ts +287 -0
  189. package/dist/neural/types.js +24 -0
  190. package/dist/shared/default-augmentations.d.ts +3 -3
  191. package/dist/shared/default-augmentations.js +5 -5
  192. package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
  193. package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
  194. package/dist/storage/adapters/fileSystemStorage.js +218 -15
  195. package/dist/storage/adapters/memoryStorage.d.ts +4 -4
  196. package/dist/storage/adapters/memoryStorage.js +17 -12
  197. package/dist/storage/adapters/opfsStorage.d.ts +2 -2
  198. package/dist/storage/adapters/opfsStorage.js +2 -2
  199. package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
  200. package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
  201. package/dist/storage/backwardCompatibility.d.ts +10 -78
  202. package/dist/storage/backwardCompatibility.js +17 -132
  203. package/dist/storage/baseStorage.d.ts +18 -2
  204. package/dist/storage/baseStorage.js +74 -3
  205. package/dist/storage/cacheManager.js +2 -2
  206. package/dist/storage/readOnlyOptimizations.js +8 -3
  207. package/dist/streaming/pipeline.d.ts +154 -0
  208. package/dist/streaming/pipeline.js +551 -0
  209. package/dist/triple/TripleIntelligence.d.ts +25 -110
  210. package/dist/triple/TripleIntelligence.js +4 -574
  211. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  212. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  213. package/dist/types/apiTypes.d.ts +278 -0
  214. package/dist/types/apiTypes.js +33 -0
  215. package/dist/types/brainy.types.d.ts +308 -0
  216. package/dist/types/brainy.types.js +8 -0
  217. package/dist/types/brainyDataInterface.d.ts +5 -8
  218. package/dist/types/brainyDataInterface.js +2 -2
  219. package/dist/types/graphTypes.js +2 -2
  220. package/dist/universal/crypto.d.ts +11 -1
  221. package/dist/universal/crypto.js +24 -93
  222. package/dist/universal/events.d.ts +3 -2
  223. package/dist/universal/events.js +6 -75
  224. package/dist/universal/fs.d.ts +2 -3
  225. package/dist/universal/fs.js +5 -211
  226. package/dist/universal/path.d.ts +3 -2
  227. package/dist/universal/path.js +22 -78
  228. package/dist/universal/uuid.d.ts +1 -1
  229. package/dist/universal/uuid.js +1 -1
  230. package/dist/utils/brainyTypes.d.ts +217 -0
  231. package/dist/utils/brainyTypes.js +261 -0
  232. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  233. package/dist/utils/embedding.d.ts +9 -4
  234. package/dist/utils/embedding.js +89 -26
  235. package/dist/utils/enhancedLogger.d.ts +104 -0
  236. package/dist/utils/enhancedLogger.js +232 -0
  237. package/dist/utils/hybridModelManager.d.ts +19 -28
  238. package/dist/utils/hybridModelManager.js +36 -200
  239. package/dist/utils/index.d.ts +1 -1
  240. package/dist/utils/index.js +1 -1
  241. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  242. package/dist/utils/intelligentTypeMapper.js +349 -0
  243. package/dist/utils/metadataIndex.d.ts +118 -1
  244. package/dist/utils/metadataIndex.js +539 -16
  245. package/dist/utils/nodeVersionCheck.d.ts +24 -0
  246. package/dist/utils/nodeVersionCheck.js +65 -0
  247. package/dist/utils/paramValidation.d.ts +39 -0
  248. package/dist/utils/paramValidation.js +192 -0
  249. package/dist/utils/rateLimiter.d.ts +160 -0
  250. package/dist/utils/rateLimiter.js +271 -0
  251. package/dist/utils/statistics.d.ts +4 -4
  252. package/dist/utils/statistics.js +3 -3
  253. package/dist/utils/structuredLogger.d.ts +146 -0
  254. package/dist/utils/structuredLogger.js +394 -0
  255. package/dist/utils/textEncoding.js +2 -1
  256. package/dist/utils/typeValidation.d.ts +59 -0
  257. package/dist/utils/typeValidation.js +374 -0
  258. package/dist/utils/version.js +19 -3
  259. package/package.json +15 -17
  260. package/scripts/download-models.cjs +94 -20
  261. package/dist/augmentations/walAugmentation.d.ts +0 -109
  262. package/dist/augmentations/walAugmentation.js +0 -516
  263. package/dist/browserFramework.d.ts +0 -15
  264. package/dist/browserFramework.js +0 -31
  265. package/dist/browserFramework.minimal.d.ts +0 -14
  266. package/dist/browserFramework.minimal.js +0 -31
  267. package/dist/chat/BrainyChat.d.ts +0 -121
  268. package/dist/chat/BrainyChat.js +0 -396
  269. package/dist/chat/ChatCLI.d.ts +0 -61
  270. package/dist/chat/ChatCLI.js +0 -351
@@ -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
@@ -172,7 +178,12 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
172
178
  * Save noun metadata to storage
173
179
  * This method should be implemented by each specific adapter
174
180
  */
175
- abstract saveNounMetadata(id: string, metadata: any): Promise<void>;
181
+ saveNounMetadata(id: string, metadata: any): Promise<void>;
182
+ /**
183
+ * Internal method for saving noun metadata
184
+ * This method should be implemented by each specific adapter
185
+ */
186
+ protected abstract saveNounMetadata_internal(id: string, metadata: any): Promise<void>;
176
187
  /**
177
188
  * Get noun metadata from storage
178
189
  * This method should be implemented by each specific adapter
@@ -182,7 +193,12 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
182
193
  * Save verb metadata to storage
183
194
  * This method should be implemented by each specific adapter
184
195
  */
185
- abstract saveVerbMetadata(id: string, metadata: any): Promise<void>;
196
+ saveVerbMetadata(id: string, metadata: any): Promise<void>;
197
+ /**
198
+ * Internal method for saving verb metadata
199
+ * This method should be implemented by each specific adapter
200
+ */
201
+ protected abstract saveVerbMetadata_internal(id: string, metadata: any): Promise<void>;
186
202
  /**
187
203
  * Get verb metadata from storage
188
204
  * This method should be implemented by each specific adapter
@@ -2,7 +2,9 @@
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';
7
+ import { validateNounType, validateVerbType } from '../utils/typeValidation.js';
6
8
  // Common directory/prefix names
7
9
  // Option A: Entity-Based Directory Structure
8
10
  export const ENTITIES_DIR = 'entities';
@@ -71,6 +73,11 @@ export class BaseStorage extends BaseStorageAdapter {
71
73
  */
72
74
  async saveNoun(noun) {
73
75
  await this.ensureInitialized();
76
+ // Validate noun type before saving - storage boundary protection
77
+ const metadata = await this.getNounMetadata(noun.id);
78
+ if (metadata?.noun) {
79
+ validateNounType(metadata.noun);
80
+ }
74
81
  return this.saveNoun_internal(noun);
75
82
  }
76
83
  /**
@@ -101,6 +108,10 @@ export class BaseStorage extends BaseStorageAdapter {
101
108
  */
102
109
  async saveVerb(verb) {
103
110
  await this.ensureInitialized();
111
+ // Validate verb type before saving - storage boundary protection
112
+ if (verb.verb) {
113
+ validateVerbType(verb.verb);
114
+ }
104
115
  // Extract the lightweight HNSWVerb data
105
116
  const hnswVerb = {
106
117
  id: verb.id,
@@ -123,9 +134,31 @@ export class BaseStorage extends BaseStorageAdapter {
123
134
  createdBy: verb.createdBy,
124
135
  embedding: verb.embedding
125
136
  };
126
- // Save both the HNSWVerb and metadata
127
- await this.saveVerb_internal(hnswVerb);
128
- await this.saveVerbMetadata(verb.id, metadata);
137
+ // Save both the HNSWVerb and metadata atomically
138
+ try {
139
+ console.log(`[DEBUG] Saving verb ${verb.id}: sourceId=${verb.sourceId}, targetId=${verb.targetId}`);
140
+ // Save the HNSWVerb first
141
+ await this.saveVerb_internal(hnswVerb);
142
+ console.log(`[DEBUG] Successfully saved HNSWVerb file for ${verb.id}`);
143
+ // Then save the metadata
144
+ await this.saveVerbMetadata(verb.id, metadata);
145
+ console.log(`[DEBUG] Successfully saved metadata file for ${verb.id}`);
146
+ }
147
+ catch (error) {
148
+ console.error(`[ERROR] Failed to save verb ${verb.id}:`, error);
149
+ // Attempt cleanup - remove verb file if metadata failed
150
+ try {
151
+ const verbExists = await this.getVerb_internal(verb.id);
152
+ if (verbExists) {
153
+ console.log(`[CLEANUP] Attempting to remove orphaned verb file ${verb.id}`);
154
+ await this.deleteVerb_internal(verb.id);
155
+ }
156
+ }
157
+ catch (cleanupError) {
158
+ console.error(`[ERROR] Failed to cleanup orphaned verb ${verb.id}:`, cleanupError);
159
+ }
160
+ throw new Error(`Failed to save verb ${verb.id}: ${error instanceof Error ? error.message : String(error)}`);
161
+ }
129
162
  }
130
163
  /**
131
164
  * Get a verb from storage
@@ -488,6 +521,44 @@ export class BaseStorage extends BaseStorageAdapter {
488
521
  await this.ensureInitialized();
489
522
  return this.deleteVerb_internal(id);
490
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
+ }
540
+ /**
541
+ * Save noun metadata to storage
542
+ * This method should be implemented by each specific adapter
543
+ */
544
+ async saveNounMetadata(id, metadata) {
545
+ // Validate noun type in metadata - storage boundary protection
546
+ if (metadata?.noun) {
547
+ validateNounType(metadata.noun);
548
+ }
549
+ return this.saveNounMetadata_internal(id, metadata);
550
+ }
551
+ /**
552
+ * Save verb metadata to storage
553
+ * This method should be implemented by each specific adapter
554
+ */
555
+ async saveVerbMetadata(id, metadata) {
556
+ // Validate verb type in metadata - storage boundary protection
557
+ if (metadata?.verb) {
558
+ validateVerbType(metadata.verb);
559
+ }
560
+ return this.saveVerbMetadata_internal(id, metadata);
561
+ }
491
562
  /**
492
563
  * Helper method to convert a Map to a plain object for serialization
493
564
  */
@@ -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 };