@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
@@ -0,0 +1,615 @@
1
+ /**
2
+ * Universal Neural Import API
3
+ *
4
+ * ALWAYS uses neural matching to map ANY data to our strict NounTypes and VerbTypes
5
+ * Never falls back to rules - neural matching is MANDATORY
6
+ *
7
+ * Handles:
8
+ * - Strings (text, JSON, CSV, YAML, Markdown)
9
+ * - Files (local paths, any format)
10
+ * - URLs (web pages, APIs, documents)
11
+ * - Objects (structured data)
12
+ * - Binary data (images, PDFs via extraction)
13
+ */
14
+ import { getBrainyTypes } from '../augmentations/typeMatching/brainyTypes.js';
15
+ import { NeuralImportAugmentation } from '../augmentations/neuralImport.js';
16
+ export class UniversalImportAPI {
17
+ constructor(brain) {
18
+ this.embedCache = new Map();
19
+ this.brain = brain;
20
+ this.neuralImport = new NeuralImportAugmentation({
21
+ confidenceThreshold: 0.0, // Accept ALL confidence levels - never reject
22
+ enableWeights: true,
23
+ skipDuplicates: false // Process everything
24
+ });
25
+ }
26
+ /**
27
+ * Initialize the neural import system
28
+ */
29
+ async init() {
30
+ this.typeMatcher = await getBrainyTypes();
31
+ // Neural import initializes itself
32
+ }
33
+ /**
34
+ * Universal import - handles ANY data source
35
+ * ALWAYS uses neural matching, NEVER falls back
36
+ */
37
+ async import(source) {
38
+ const startTime = Date.now();
39
+ // Normalize source
40
+ const normalizedSource = this.normalizeSource(source);
41
+ // Extract data based on source type
42
+ const extractedData = await this.extractData(normalizedSource);
43
+ // Neural processing - MANDATORY
44
+ const neuralResults = await this.neuralProcess(extractedData);
45
+ // Store in brain
46
+ const result = await this.storeInBrain(neuralResults);
47
+ result.stats.processingTimeMs = Date.now() - startTime;
48
+ return result;
49
+ }
50
+ /**
51
+ * Import from URL - fetches and processes
52
+ */
53
+ async importFromURL(url) {
54
+ const response = await fetch(url);
55
+ const contentType = response.headers.get('content-type') || 'text/plain';
56
+ let data;
57
+ if (contentType.includes('json')) {
58
+ data = await response.json();
59
+ }
60
+ else if (contentType.includes('text') || contentType.includes('html')) {
61
+ data = await response.text();
62
+ }
63
+ else {
64
+ // Binary data
65
+ const buffer = await response.arrayBuffer();
66
+ data = new Uint8Array(buffer);
67
+ }
68
+ return this.import({
69
+ type: 'url',
70
+ data,
71
+ format: contentType,
72
+ metadata: { url, fetchedAt: Date.now() }
73
+ });
74
+ }
75
+ /**
76
+ * Import from file - reads and processes
77
+ * Note: In browser environment, use File API instead
78
+ */
79
+ async importFromFile(filePath) {
80
+ // Read the actual file content
81
+ const { readFileSync } = await import('fs');
82
+ const ext = filePath.split('.').pop()?.toLowerCase() || 'txt';
83
+ try {
84
+ const fileContent = readFileSync(filePath, 'utf-8');
85
+ return this.import({
86
+ type: 'file',
87
+ data: fileContent, // Actual file content
88
+ format: ext,
89
+ metadata: {
90
+ path: filePath,
91
+ importedAt: Date.now(),
92
+ fileSize: fileContent.length
93
+ }
94
+ });
95
+ }
96
+ catch (error) {
97
+ throw new Error(`Failed to read file ${filePath}: ${error.message}`);
98
+ }
99
+ }
100
+ /**
101
+ * Normalize any input to ImportSource
102
+ */
103
+ normalizeSource(source) {
104
+ // Already normalized
105
+ if (source && typeof source === 'object' && 'type' in source && 'data' in source) {
106
+ return source;
107
+ }
108
+ // String input
109
+ if (typeof source === 'string') {
110
+ // Check if it's a URL
111
+ if (source.startsWith('http://') || source.startsWith('https://')) {
112
+ return { type: 'url', data: source };
113
+ }
114
+ // Check if it looks like a file path
115
+ if (source.includes('/') || source.includes('\\') || source.includes('.')) {
116
+ // Assume it's a file path reference
117
+ return { type: 'file', data: source };
118
+ }
119
+ // Treat as raw string data
120
+ return { type: 'string', data: source };
121
+ }
122
+ // Object/Array input
123
+ if (typeof source === 'object') {
124
+ return { type: 'object', data: source };
125
+ }
126
+ // Default to string
127
+ return { type: 'string', data: String(source) };
128
+ }
129
+ /**
130
+ * Extract structured data from source
131
+ */
132
+ async extractData(source) {
133
+ switch (source.type) {
134
+ case 'url':
135
+ // URL is in data field, need to fetch
136
+ return this.extractFromURL(source.data);
137
+ case 'file':
138
+ // File path is in data field, need to read
139
+ return this.extractFromFile(source.data);
140
+ case 'string':
141
+ return this.extractFromString(source.data, source.format);
142
+ case 'object':
143
+ return Array.isArray(source.data) ? source.data : [source.data];
144
+ case 'binary':
145
+ return this.extractFromBinary(source.data, source.format);
146
+ default:
147
+ // Unknown type, treat as object
148
+ return [source.data];
149
+ }
150
+ }
151
+ /**
152
+ * Extract data from URL
153
+ */
154
+ async extractFromURL(url) {
155
+ const result = await this.importFromURL(url);
156
+ return result.entities.map(e => e.data);
157
+ }
158
+ /**
159
+ * Extract data from file
160
+ */
161
+ async extractFromFile(filePath) {
162
+ const result = await this.importFromFile(filePath);
163
+ return result.entities.map(e => e.data);
164
+ }
165
+ /**
166
+ * Extract data from string based on format
167
+ */
168
+ extractFromString(data, format) {
169
+ // Try to detect format if not provided
170
+ const detectedFormat = format || this.detectFormat(data);
171
+ switch (detectedFormat) {
172
+ case 'json':
173
+ try {
174
+ const parsed = JSON.parse(data);
175
+ return Array.isArray(parsed) ? parsed : [parsed];
176
+ }
177
+ catch {
178
+ // Not valid JSON, treat as text
179
+ return this.extractFromText(data);
180
+ }
181
+ case 'csv':
182
+ return this.parseCSV(data);
183
+ case 'yaml':
184
+ case 'yml':
185
+ return this.parseYAML(data);
186
+ case 'markdown':
187
+ case 'md':
188
+ return this.parseMarkdown(data);
189
+ case 'xml':
190
+ case 'html':
191
+ return this.parseHTML(data);
192
+ default:
193
+ return this.extractFromText(data);
194
+ }
195
+ }
196
+ /**
197
+ * Extract from binary data (images, PDFs, etc)
198
+ */
199
+ async extractFromBinary(data, format) {
200
+ // For now, create a single entity representing the binary data
201
+ // In production, would use OCR, image recognition, PDF extraction, etc.
202
+ return [{
203
+ type: 'binary',
204
+ format: format || 'unknown',
205
+ size: data.length,
206
+ hash: await this.hashBinary(data),
207
+ extractedAt: Date.now()
208
+ }];
209
+ }
210
+ /**
211
+ * Extract entities from plain text
212
+ */
213
+ extractFromText(text) {
214
+ // Split into meaningful chunks
215
+ const chunks = [];
216
+ // Split by paragraphs
217
+ const paragraphs = text.split(/\n\n+/);
218
+ for (const para of paragraphs) {
219
+ if (para.trim()) {
220
+ chunks.push({
221
+ text: para.trim(),
222
+ type: 'paragraph',
223
+ length: para.length
224
+ });
225
+ }
226
+ }
227
+ // If no paragraphs, split by sentences
228
+ if (chunks.length === 0) {
229
+ const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
230
+ for (const sentence of sentences) {
231
+ if (sentence.trim()) {
232
+ chunks.push({
233
+ text: sentence.trim(),
234
+ type: 'sentence',
235
+ length: sentence.length
236
+ });
237
+ }
238
+ }
239
+ }
240
+ return chunks;
241
+ }
242
+ /**
243
+ * Neural processing - CORE of the system
244
+ * ALWAYS uses embeddings and neural matching
245
+ */
246
+ async neuralProcess(data) {
247
+ const entities = new Map();
248
+ const relationships = new Map();
249
+ for (const item of data) {
250
+ // Generate embedding for the item
251
+ const embedding = await this.generateEmbedding(item);
252
+ // Neural type matching - MANDATORY
253
+ const nounMatch = await this.typeMatcher.matchNounType(item);
254
+ // Never reject based on confidence - we ALWAYS accept the best match
255
+ const entityId = this.generateId(item);
256
+ entities.set(entityId, {
257
+ id: entityId,
258
+ type: nounMatch.type, // Always use the neural match
259
+ data: item,
260
+ vector: embedding,
261
+ confidence: nounMatch.confidence,
262
+ metadata: {
263
+ ...item,
264
+ _neuralMatch: nounMatch,
265
+ _importedAt: Date.now()
266
+ }
267
+ });
268
+ // Detect relationships using neural matching
269
+ await this.detectNeuralRelationships(item, entityId, entities, relationships);
270
+ }
271
+ return { entities, relationships };
272
+ }
273
+ /**
274
+ * Generate embedding for any data
275
+ */
276
+ async generateEmbedding(data) {
277
+ // Convert to string for embedding
278
+ const text = this.dataToText(data);
279
+ // Check cache
280
+ if (this.embedCache.has(text)) {
281
+ return this.embedCache.get(text);
282
+ }
283
+ // Generate new embedding
284
+ const embedding = await this.brain.embed(text);
285
+ // Cache it
286
+ this.embedCache.set(text, embedding);
287
+ return embedding;
288
+ }
289
+ /**
290
+ * Convert any data to text for embedding
291
+ */
292
+ dataToText(data) {
293
+ if (typeof data === 'string')
294
+ return data;
295
+ if (typeof data === 'object') {
296
+ // Extract meaningful text from object
297
+ const parts = [];
298
+ // Priority fields
299
+ const priorityFields = ['name', 'title', 'description', 'text', 'content', 'label', 'value'];
300
+ for (const field of priorityFields) {
301
+ if (data[field]) {
302
+ parts.push(String(data[field]));
303
+ }
304
+ }
305
+ // Add other fields
306
+ for (const [key, value] of Object.entries(data)) {
307
+ if (!priorityFields.includes(key) && value) {
308
+ if (typeof value === 'string' || typeof value === 'number') {
309
+ parts.push(`${key}: ${value}`);
310
+ }
311
+ }
312
+ }
313
+ return parts.join(' ');
314
+ }
315
+ return JSON.stringify(data);
316
+ }
317
+ /**
318
+ * Detect relationships using neural matching
319
+ */
320
+ async detectNeuralRelationships(item, sourceId, entities, relationships) {
321
+ if (typeof item !== 'object')
322
+ return;
323
+ // Look for references to other entities
324
+ for (const [key, value] of Object.entries(item)) {
325
+ // Check if this looks like a reference
326
+ if (this.looksLikeReference(key, value)) {
327
+ // Find or predict target entity
328
+ const targetId = String(value);
329
+ // Neural verb type matching
330
+ const verbMatch = await this.typeMatcher.matchVerbType(item, // source object
331
+ { id: targetId }, // target (we may not have full data)
332
+ key // field name as context
333
+ );
334
+ // Always create relationship with neural match
335
+ const relationId = `${sourceId}_${verbMatch.type}_${targetId}`;
336
+ relationships.set(relationId, {
337
+ id: relationId,
338
+ from: sourceId,
339
+ to: targetId,
340
+ type: verbMatch.type,
341
+ weight: verbMatch.confidence, // Use confidence as weight
342
+ confidence: verbMatch.confidence,
343
+ metadata: {
344
+ field: key,
345
+ _neuralMatch: verbMatch,
346
+ _importedAt: Date.now()
347
+ }
348
+ });
349
+ }
350
+ // Handle arrays of references
351
+ if (Array.isArray(value)) {
352
+ for (const item of value) {
353
+ if (this.looksLikeReference(key, item)) {
354
+ const targetId = String(item);
355
+ const verbMatch = await this.typeMatcher.matchVerbType(item, { id: targetId }, key);
356
+ const relationId = `${sourceId}_${verbMatch.type}_${targetId}`;
357
+ relationships.set(relationId, {
358
+ id: relationId,
359
+ from: sourceId,
360
+ to: targetId,
361
+ type: verbMatch.type,
362
+ weight: verbMatch.confidence,
363
+ confidence: verbMatch.confidence,
364
+ metadata: {
365
+ field: key,
366
+ array: true,
367
+ _neuralMatch: verbMatch,
368
+ _importedAt: Date.now()
369
+ }
370
+ });
371
+ }
372
+ }
373
+ }
374
+ }
375
+ }
376
+ /**
377
+ * Check if a field looks like a reference
378
+ */
379
+ looksLikeReference(key, value) {
380
+ // Field name patterns that suggest references
381
+ const refPatterns = [
382
+ /[Ii]d$/, // ends with Id or id
383
+ /_id$/, // ends with _id
384
+ /^parent/i, // starts with parent
385
+ /^child/i, // starts with child
386
+ /^related/i, // starts with related
387
+ /^ref/i, // starts with ref
388
+ /^link/i, // starts with link
389
+ /^target/i, // starts with target
390
+ /^source/i, // starts with source
391
+ ];
392
+ // Check if field name matches patterns
393
+ const fieldLooksLikeRef = refPatterns.some(pattern => pattern.test(key));
394
+ // Check if value looks like an ID
395
+ const valueLooksLikeId = (typeof value === 'string' ||
396
+ typeof value === 'number') && String(value).length > 0;
397
+ return fieldLooksLikeRef && valueLooksLikeId;
398
+ }
399
+ /**
400
+ * Store processed data in brain
401
+ */
402
+ async storeInBrain(neuralResults) {
403
+ const result = {
404
+ entities: [],
405
+ relationships: [],
406
+ stats: {
407
+ totalProcessed: neuralResults.entities.size + neuralResults.relationships.size,
408
+ entitiesCreated: 0,
409
+ relationshipsCreated: 0,
410
+ averageConfidence: 0,
411
+ processingTimeMs: 0
412
+ }
413
+ };
414
+ let totalConfidence = 0;
415
+ // Store entities
416
+ for (const entity of neuralResults.entities.values()) {
417
+ const id = await this.brain.add({
418
+ data: entity.data,
419
+ type: entity.type,
420
+ metadata: entity.metadata,
421
+ vector: entity.vector
422
+ });
423
+ // Update entity ID for relationship mapping
424
+ entity.id = id;
425
+ result.entities.push({
426
+ ...entity,
427
+ id
428
+ });
429
+ result.stats.entitiesCreated++;
430
+ totalConfidence += entity.confidence;
431
+ }
432
+ // Store relationships
433
+ for (const relation of neuralResults.relationships.values()) {
434
+ // Map to actual entity IDs
435
+ const sourceEntity = Array.from(neuralResults.entities.values())
436
+ .find(e => e.id === relation.from);
437
+ const targetEntity = Array.from(neuralResults.entities.values())
438
+ .find(e => e.id === relation.to);
439
+ if (sourceEntity && targetEntity) {
440
+ const id = await this.brain.relate({
441
+ from: sourceEntity.id,
442
+ to: targetEntity.id,
443
+ type: relation.type,
444
+ weight: relation.weight,
445
+ metadata: relation.metadata
446
+ });
447
+ result.relationships.push({
448
+ ...relation,
449
+ id,
450
+ from: sourceEntity.id,
451
+ to: targetEntity.id
452
+ });
453
+ result.stats.relationshipsCreated++;
454
+ totalConfidence += relation.confidence;
455
+ }
456
+ }
457
+ // Calculate average confidence
458
+ const totalItems = result.stats.entitiesCreated + result.stats.relationshipsCreated;
459
+ result.stats.averageConfidence = totalItems > 0 ? totalConfidence / totalItems : 0;
460
+ return result;
461
+ }
462
+ // Helper methods for parsing different formats
463
+ detectFormat(data) {
464
+ const trimmed = data.trim();
465
+ // JSON
466
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) ||
467
+ (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
468
+ return 'json';
469
+ }
470
+ // CSV (has commas and newlines)
471
+ if (trimmed.includes(',') && trimmed.includes('\n')) {
472
+ return 'csv';
473
+ }
474
+ // YAML (has colons and indentation)
475
+ if (trimmed.includes(':') && (trimmed.includes('\n ') || trimmed.includes('\n\t'))) {
476
+ return 'yaml';
477
+ }
478
+ // Markdown (has headers)
479
+ if (trimmed.includes('#') || trimmed.includes('```')) {
480
+ return 'markdown';
481
+ }
482
+ // HTML/XML
483
+ if (trimmed.includes('<') && trimmed.includes('>')) {
484
+ return trimmed.toLowerCase().includes('<!doctype html') ? 'html' : 'xml';
485
+ }
486
+ return 'text';
487
+ }
488
+ parseCSV(data) {
489
+ // Reuse the CSV parser from neural import
490
+ const lines = data.split('\n').filter(l => l.trim());
491
+ if (lines.length === 0)
492
+ return [];
493
+ const headers = lines[0].split(',').map(h => h.trim());
494
+ const results = [];
495
+ for (let i = 1; i < lines.length; i++) {
496
+ const values = lines[i].split(',').map(v => v.trim());
497
+ const obj = {};
498
+ headers.forEach((header, index) => {
499
+ obj[header] = values[index] || '';
500
+ });
501
+ results.push(obj);
502
+ }
503
+ return results;
504
+ }
505
+ parseYAML(data) {
506
+ // Simple YAML parser
507
+ const results = [];
508
+ const lines = data.split('\n');
509
+ let current = null;
510
+ for (const line of lines) {
511
+ const trimmed = line.trim();
512
+ if (!trimmed || trimmed.startsWith('#'))
513
+ continue;
514
+ if (trimmed.startsWith('- ')) {
515
+ // Array item
516
+ const value = trimmed.substring(2);
517
+ if (!current) {
518
+ results.push(value);
519
+ }
520
+ else {
521
+ if (!current._items)
522
+ current._items = [];
523
+ current._items.push(value);
524
+ }
525
+ }
526
+ else if (trimmed.includes(':')) {
527
+ // Key-value
528
+ const [key, ...valueParts] = trimmed.split(':');
529
+ const value = valueParts.join(':').trim();
530
+ if (!current) {
531
+ current = {};
532
+ results.push(current);
533
+ }
534
+ current[key.trim()] = value;
535
+ }
536
+ }
537
+ return results.length > 0 ? results : [{ text: data }];
538
+ }
539
+ parseMarkdown(data) {
540
+ const results = [];
541
+ const lines = data.split('\n');
542
+ let current = null;
543
+ let inCodeBlock = false;
544
+ for (const line of lines) {
545
+ if (line.startsWith('```')) {
546
+ inCodeBlock = !inCodeBlock;
547
+ if (inCodeBlock && current) {
548
+ current.code = '';
549
+ }
550
+ continue;
551
+ }
552
+ if (inCodeBlock && current) {
553
+ current.code += line + '\n';
554
+ }
555
+ else if (line.startsWith('#')) {
556
+ // Header
557
+ const level = line.match(/^#+/)?.[0].length || 1;
558
+ const text = line.replace(/^#+\s*/, '');
559
+ current = {
560
+ type: 'heading',
561
+ level,
562
+ text
563
+ };
564
+ results.push(current);
565
+ }
566
+ else if (line.trim()) {
567
+ // Paragraph
568
+ if (!current || current.type !== 'paragraph') {
569
+ current = {
570
+ type: 'paragraph',
571
+ text: ''
572
+ };
573
+ results.push(current);
574
+ }
575
+ current.text += line + ' ';
576
+ }
577
+ }
578
+ return results;
579
+ }
580
+ parseHTML(data) {
581
+ // Simple HTML text extraction
582
+ const text = data
583
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') // Remove scripts
584
+ .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '') // Remove styles
585
+ .replace(/<[^>]+>/g, ' ') // Remove tags
586
+ .replace(/\s+/g, ' ') // Normalize whitespace
587
+ .trim();
588
+ return this.extractFromText(text);
589
+ }
590
+ generateId(data) {
591
+ // Generate deterministic ID based on content
592
+ const text = this.dataToText(data);
593
+ const hash = this.simpleHash(text);
594
+ return `import_${hash}_${Date.now()}`;
595
+ }
596
+ simpleHash(text) {
597
+ let hash = 0;
598
+ for (let i = 0; i < text.length; i++) {
599
+ const char = text.charCodeAt(i);
600
+ hash = ((hash << 5) - hash) + char;
601
+ hash = hash & hash;
602
+ }
603
+ return Math.abs(hash).toString(36);
604
+ }
605
+ async hashBinary(data) {
606
+ // Simple binary hash
607
+ let hash = 0;
608
+ for (let i = 0; i < Math.min(data.length, 1000); i++) {
609
+ hash = ((hash << 5) - hash) + data[i];
610
+ hash = hash & hash;
611
+ }
612
+ return Math.abs(hash).toString(36);
613
+ }
614
+ }
615
+ //# sourceMappingURL=UniversalImportAPI.js.map
@@ -16,7 +16,8 @@ export class AugmentationManager {
16
16
  * @returns Array of augmentation information
17
17
  */
18
18
  list() {
19
- return this.pipeline.listAugmentationsWithStatus();
19
+ // Deprecated: use brain.augmentations instead
20
+ return [];
20
21
  }
21
22
  /**
22
23
  * Get information about a specific augmentation
@@ -42,7 +43,8 @@ export class AugmentationManager {
42
43
  * @returns True if successfully enabled
43
44
  */
44
45
  enable(name) {
45
- return this.pipeline.enableAugmentation(name);
46
+ // Deprecated: use brain.augmentations instead
47
+ return false;
46
48
  }
47
49
  /**
48
50
  * Disable a specific augmentation
@@ -50,7 +52,8 @@ export class AugmentationManager {
50
52
  * @returns True if successfully disabled
51
53
  */
52
54
  disable(name) {
53
- return this.pipeline.disableAugmentation(name);
55
+ // Deprecated: use brain.augmentations instead
56
+ return false;
54
57
  }
55
58
  /**
56
59
  * Remove an augmentation from the pipeline
@@ -58,7 +61,7 @@ export class AugmentationManager {
58
61
  * @returns True if successfully removed
59
62
  */
60
63
  remove(name) {
61
- this.pipeline.unregister(name);
64
+ // Deprecated: use brain.augmentations instead
62
65
  return true;
63
66
  }
64
67
  /**
@@ -67,7 +70,8 @@ export class AugmentationManager {
67
70
  * @returns Number of augmentations enabled
68
71
  */
69
72
  enableType(type) {
70
- return this.pipeline.enableAugmentationType(type);
73
+ // Deprecated: use brain.augmentations instead
74
+ return 0;
71
75
  }
72
76
  /**
73
77
  * Disable all augmentations of a specific type
@@ -75,7 +79,8 @@ export class AugmentationManager {
75
79
  * @returns Number of augmentations disabled
76
80
  */
77
81
  disableType(type) {
78
- return this.pipeline.disableAugmentationType(type);
82
+ // Deprecated: use brain.augmentations instead
83
+ return 0;
79
84
  }
80
85
  /**
81
86
  * Get all augmentations of a specific type
@@ -104,7 +109,7 @@ export class AugmentationManager {
104
109
  * @param augmentation The augmentation to register
105
110
  */
106
111
  register(augmentation) {
107
- this.pipeline.register(augmentation);
112
+ // Deprecated: use brain.augmentations instead
108
113
  }
109
114
  }
110
115
  // Export types for external use