@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,349 @@
1
+ /**
2
+ * Intelligent Type Mapper
3
+ * Maps generic/invalid type names to specific semantic types based on data analysis
4
+ * Prevents semantic degradation from overuse of generic types
5
+ */
6
+ import { NounType, VerbType } from '../types/graphTypes.js';
7
+ /**
8
+ * Common aliases that users might use
9
+ */
10
+ const GENERIC_ALIASES = new Set([
11
+ 'entity',
12
+ 'item',
13
+ 'object',
14
+ 'node',
15
+ 'record',
16
+ 'entry',
17
+ 'data',
18
+ 'resource'
19
+ ]);
20
+ /**
21
+ * Field signatures for type inference
22
+ */
23
+ const TYPE_SIGNATURES = {
24
+ // Person indicators
25
+ person: {
26
+ required: [],
27
+ indicators: ['email', 'firstName', 'lastName', 'name', 'phone', 'username', 'userId'],
28
+ patterns: [/@/, /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i],
29
+ weight: 10
30
+ },
31
+ // User account indicators
32
+ user: {
33
+ required: [],
34
+ indicators: ['username', 'password', 'accountId', 'loginTime', 'permissions', 'role'],
35
+ patterns: [],
36
+ weight: 9
37
+ },
38
+ // Organization indicators
39
+ organization: {
40
+ required: [],
41
+ indicators: ['companyName', 'orgName', 'ein', 'vatNumber', 'employees', 'headquarters'],
42
+ patterns: [],
43
+ weight: 8
44
+ },
45
+ // Product indicators
46
+ product: {
47
+ required: [],
48
+ indicators: ['price', 'sku', 'barcode', 'inventory', 'cost', 'productId', 'inStock'],
49
+ patterns: [/^\$?\d+\.?\d*$/, /^[A-Z0-9-]+$/],
50
+ weight: 8
51
+ },
52
+ // Document indicators
53
+ document: {
54
+ required: [],
55
+ indicators: ['content', 'text', 'body', 'title', 'author', 'markdown', 'html'],
56
+ patterns: [],
57
+ weight: 7
58
+ },
59
+ // Message indicators
60
+ message: {
61
+ required: [],
62
+ indicators: ['from', 'to', 'subject', 'body', 'sentAt', 'messageId', 'threadId'],
63
+ patterns: [],
64
+ weight: 7
65
+ },
66
+ // Task indicators
67
+ task: {
68
+ required: [],
69
+ indicators: ['dueDate', 'assignee', 'status', 'priority', 'completed', 'taskId'],
70
+ patterns: [],
71
+ weight: 7
72
+ },
73
+ // Event indicators
74
+ event: {
75
+ required: [],
76
+ indicators: ['startTime', 'endTime', 'date', 'location', 'attendees', 'eventType'],
77
+ patterns: [],
78
+ weight: 6
79
+ },
80
+ // Location indicators
81
+ location: {
82
+ required: [],
83
+ indicators: ['latitude', 'longitude', 'address', 'city', 'country', 'zipCode', 'coordinates'],
84
+ patterns: [/^-?\d+\.\d+$/, /^\d{5}(-\d{4})?$/],
85
+ weight: 6
86
+ },
87
+ // File indicators
88
+ file: {
89
+ required: [],
90
+ indicators: ['filename', 'filepath', 'extension', 'mimeType', 'fileSize', 'checksum'],
91
+ patterns: [/\.[a-z0-9]+$/i],
92
+ weight: 5
93
+ },
94
+ // Dataset indicators
95
+ dataset: {
96
+ required: [],
97
+ indicators: ['schema', 'rows', 'columns', 'records', 'dataType', 'format'],
98
+ patterns: [],
99
+ weight: 5
100
+ },
101
+ // Media indicators
102
+ media: {
103
+ required: [],
104
+ indicators: ['url', 'thumbnail', 'duration', 'resolution', 'codec', 'bitrate'],
105
+ patterns: [/\.(jpg|jpeg|png|gif|mp4|mp3|wav|avi)$/i],
106
+ weight: 5
107
+ },
108
+ // Project indicators
109
+ project: {
110
+ required: [],
111
+ indicators: ['deadline', 'budget', 'team', 'milestones', 'deliverables', 'projectId'],
112
+ patterns: [],
113
+ weight: 5
114
+ },
115
+ // Service indicators
116
+ service: {
117
+ required: [],
118
+ indicators: ['endpoint', 'apiKey', 'serviceUrl', 'port', 'protocol', 'healthCheck'],
119
+ patterns: [/^https?:\/\//, /:\d+$/],
120
+ weight: 4
121
+ }
122
+ };
123
+ /**
124
+ * Intelligent Type Mapper
125
+ */
126
+ export class IntelligentTypeMapper {
127
+ constructor() {
128
+ this.typeCache = new Map();
129
+ this.inferenceStats = {
130
+ total: 0,
131
+ inferred: 0,
132
+ defaulted: 0,
133
+ cached: 0
134
+ };
135
+ }
136
+ /**
137
+ * Map a noun type, with intelligent inference for generic types
138
+ */
139
+ mapNounType(inputType, data) {
140
+ // Check if it's already a valid type
141
+ if (this.isValidNounType(inputType)) {
142
+ return inputType;
143
+ }
144
+ // Check cache for this exact input
145
+ const cacheKey = `${inputType}-${JSON.stringify(data || {}).substring(0, 100)}`;
146
+ if (this.typeCache.has(cacheKey)) {
147
+ this.inferenceStats.cached++;
148
+ return this.typeCache.get(cacheKey);
149
+ }
150
+ this.inferenceStats.total++;
151
+ // If it's a generic alias and we have data, try to infer
152
+ if (GENERIC_ALIASES.has(inputType.toLowerCase()) && data) {
153
+ const inferred = this.inferTypeFromData(data);
154
+ if (inferred) {
155
+ this.inferenceStats.inferred++;
156
+ this.typeCache.set(cacheKey, inferred);
157
+ return inferred;
158
+ }
159
+ }
160
+ // Handle specific common mappings
161
+ const directMapping = this.getDirectMapping(inputType);
162
+ if (directMapping) {
163
+ this.typeCache.set(cacheKey, directMapping);
164
+ return directMapping;
165
+ }
166
+ // Default to 'thing' for truly unknown types
167
+ this.inferenceStats.defaulted++;
168
+ const defaultType = NounType.Thing;
169
+ this.typeCache.set(cacheKey, defaultType);
170
+ return defaultType;
171
+ }
172
+ /**
173
+ * Map a verb type
174
+ */
175
+ mapVerbType(inputType) {
176
+ // Check if it's already valid
177
+ if (this.isValidVerbType(inputType)) {
178
+ return inputType;
179
+ }
180
+ // Common verb mappings
181
+ const verbMappings = {
182
+ 'related': VerbType.RelatedTo,
183
+ 'relates': VerbType.RelatedTo,
184
+ 'has': VerbType.Contains,
185
+ 'includes': VerbType.Contains,
186
+ 'belongsTo': VerbType.PartOf,
187
+ 'in': VerbType.LocatedAt,
188
+ 'at': VerbType.LocatedAt,
189
+ 'references': VerbType.References,
190
+ 'cites': VerbType.References,
191
+ 'before': VerbType.Precedes,
192
+ 'after': VerbType.Succeeds,
193
+ 'causes': VerbType.Causes,
194
+ 'needs': VerbType.Requires,
195
+ 'requires': VerbType.Requires,
196
+ 'makes': VerbType.Creates,
197
+ 'produces': VerbType.Creates,
198
+ 'changes': VerbType.Modifies,
199
+ 'updates': VerbType.Modifies,
200
+ 'owns': VerbType.Owns,
201
+ 'ownedBy': VerbType.BelongsTo, // Use BelongsTo for reverse ownership
202
+ 'uses': VerbType.Uses,
203
+ 'usedBy': VerbType.Uses // Same relationship, just interpret direction
204
+ };
205
+ const normalized = inputType.toLowerCase();
206
+ return verbMappings[normalized] || VerbType.RelatedTo;
207
+ }
208
+ /**
209
+ * Infer type from data structure
210
+ */
211
+ inferTypeFromData(data) {
212
+ if (!data || typeof data !== 'object')
213
+ return null;
214
+ const scores = new Map();
215
+ const fields = Object.keys(data);
216
+ const values = Object.values(data);
217
+ // Calculate scores for each type based on field matches
218
+ for (const [type, signature] of Object.entries(TYPE_SIGNATURES)) {
219
+ let score = 0;
220
+ // Check required fields
221
+ if (signature.required.length > 0) {
222
+ const hasRequired = signature.required.every(field => fields.includes(field));
223
+ if (!hasRequired)
224
+ continue;
225
+ score += signature.weight * 2;
226
+ }
227
+ // Check indicator fields
228
+ for (const field of fields) {
229
+ if (signature.indicators.some(indicator => field.toLowerCase().includes(indicator.toLowerCase()))) {
230
+ score += signature.weight;
231
+ }
232
+ }
233
+ // Check value patterns
234
+ for (const value of values) {
235
+ if (typeof value === 'string' && signature.patterns.length > 0) {
236
+ for (const pattern of signature.patterns) {
237
+ if (pattern.test(value)) {
238
+ score += signature.weight / 2;
239
+ break;
240
+ }
241
+ }
242
+ }
243
+ }
244
+ if (score > 0) {
245
+ scores.set(type, score);
246
+ }
247
+ }
248
+ // Return the type with highest score
249
+ if (scores.size > 0) {
250
+ const sorted = Array.from(scores.entries()).sort((a, b) => b[1] - a[1]);
251
+ return sorted[0][0];
252
+ }
253
+ // Fallback inference based on data structure
254
+ if (fields.includes('url') || fields.includes('href')) {
255
+ return NounType.Document;
256
+ }
257
+ if (Array.isArray(data) || fields.includes('items') || fields.includes('elements')) {
258
+ return NounType.Collection;
259
+ }
260
+ // Check if it looks like a process/workflow
261
+ if (fields.includes('steps') || fields.includes('stages')) {
262
+ return NounType.Process;
263
+ }
264
+ return null;
265
+ }
266
+ /**
267
+ * Get direct mapping for common aliases
268
+ */
269
+ getDirectMapping(inputType) {
270
+ const mappings = {
271
+ // Specific mappings that aren't generic
272
+ 'company': NounType.Organization,
273
+ 'corp': NounType.Organization,
274
+ 'business': NounType.Organization,
275
+ 'employee': NounType.Person,
276
+ 'staff': NounType.Person,
277
+ 'customer': NounType.Person,
278
+ 'client': NounType.Person,
279
+ 'article': NounType.Document,
280
+ 'post': NounType.Document,
281
+ 'page': NounType.Document,
282
+ 'image': NounType.Media,
283
+ 'video': NounType.Media,
284
+ 'audio': NounType.Media,
285
+ 'photo': NounType.Media,
286
+ 'place': NounType.Location,
287
+ 'address': NounType.Location,
288
+ 'country': NounType.Location,
289
+ 'city': NounType.Location,
290
+ 'todo': NounType.Task,
291
+ 'job': NounType.Task,
292
+ 'work': NounType.Task,
293
+ 'meeting': NounType.Event,
294
+ 'appointment': NounType.Event,
295
+ 'conference': NounType.Event,
296
+ 'folder': NounType.Collection,
297
+ 'group': NounType.Collection,
298
+ 'list': NounType.Collection,
299
+ 'category': NounType.Collection
300
+ };
301
+ const normalized = inputType.toLowerCase();
302
+ return mappings[normalized] || null;
303
+ }
304
+ /**
305
+ * Check if a type is valid
306
+ */
307
+ isValidNounType(type) {
308
+ return Object.values(NounType).includes(type);
309
+ }
310
+ /**
311
+ * Check if a verb type is valid
312
+ */
313
+ isValidVerbType(type) {
314
+ return Object.values(VerbType).includes(type);
315
+ }
316
+ /**
317
+ * Get inference statistics
318
+ */
319
+ getStats() {
320
+ return {
321
+ ...this.inferenceStats,
322
+ cacheSize: this.typeCache.size,
323
+ inferenceRate: this.inferenceStats.total > 0
324
+ ? (this.inferenceStats.inferred / this.inferenceStats.total)
325
+ : 0
326
+ };
327
+ }
328
+ /**
329
+ * Clear the type cache
330
+ */
331
+ clearCache() {
332
+ this.typeCache.clear();
333
+ }
334
+ }
335
+ // Singleton instance
336
+ export const typeMapper = new IntelligentTypeMapper();
337
+ /**
338
+ * Helper function for easy type mapping
339
+ */
340
+ export function mapNounType(inputType, data) {
341
+ return typeMapper.mapNounType(inputType, data);
342
+ }
343
+ /**
344
+ * Helper function for verb mapping
345
+ */
346
+ export function mapVerbType(inputType) {
347
+ return typeMapper.mapVerbType(inputType);
348
+ }
349
+ //# sourceMappingURL=intelligentTypeMapper.js.map
@@ -4,6 +4,7 @@
4
4
  * Automatically updates indexes when data changes
5
5
  */
6
6
  import { StorageAdapter } from '../coreTypes.js';
7
+ import { NounType } from '../types/graphTypes.js';
7
8
  export interface MetadataIndexEntry {
8
9
  field: string;
9
10
  value: string | number | boolean;
@@ -28,6 +29,22 @@ export interface MetadataIndexConfig {
28
29
  indexedFields?: string[];
29
30
  excludeFields?: string[];
30
31
  }
32
+ interface CardinalityInfo {
33
+ uniqueValues: number;
34
+ totalValues: number;
35
+ distribution: 'uniform' | 'skewed' | 'sparse';
36
+ updateFrequency: number;
37
+ lastAnalyzed: number;
38
+ }
39
+ interface FieldStats {
40
+ cardinality: CardinalityInfo;
41
+ queryCount: number;
42
+ rangeQueryCount: number;
43
+ exactQueryCount: number;
44
+ avgQueryTime: number;
45
+ indexType: 'hash' | 'sorted' | 'both';
46
+ normalizationStrategy?: 'none' | 'precision' | 'bucket';
47
+ }
31
48
  export declare class MetadataIndexManager {
32
49
  private storage;
33
50
  private config;
@@ -41,6 +58,14 @@ export declare class MetadataIndexManager {
41
58
  private autoFlushThreshold;
42
59
  private sortedIndices;
43
60
  private numericFields;
61
+ private fieldStats;
62
+ private cardinalityUpdateInterval;
63
+ private operationCount;
64
+ private readonly HIGH_CARDINALITY_THRESHOLD;
65
+ private readonly TIMESTAMP_PRECISION_MS;
66
+ private readonly FLOAT_PRECISION;
67
+ private typeFieldAffinity;
68
+ private totalEntitiesByType;
44
69
  private unifiedCache;
45
70
  constructor(storage: StorageAdapter, config?: MetadataIndexConfig);
46
71
  /**
@@ -55,6 +80,27 @@ export declare class MetadataIndexManager {
55
80
  * Build sorted index for a field from hash index
56
81
  */
57
82
  private buildSortedIndex;
83
+ /**
84
+ * Detect field type from value
85
+ */
86
+ private detectFieldType;
87
+ /**
88
+ * Compare two values based on field type for sorting
89
+ */
90
+ private compareValues;
91
+ /**
92
+ * Binary search to find insertion position for a value
93
+ * Returns the index where the value should be inserted to maintain sorted order
94
+ */
95
+ private findInsertPosition;
96
+ /**
97
+ * Incrementally update sorted index when adding an ID
98
+ */
99
+ private updateSortedIndexAdd;
100
+ /**
101
+ * Incrementally update sorted index when removing an ID
102
+ */
103
+ private updateSortedIndexRemove;
58
104
  /**
59
105
  * Binary search for range start (inclusive or exclusive)
60
106
  */
@@ -63,6 +109,18 @@ export declare class MetadataIndexManager {
63
109
  * Binary search for range end (inclusive or exclusive)
64
110
  */
65
111
  private binarySearchEnd;
112
+ /**
113
+ * Update cardinality statistics for a field
114
+ */
115
+ private updateCardinalityStats;
116
+ /**
117
+ * Analyze field distribution for optimization
118
+ */
119
+ private analyzeFieldDistribution;
120
+ /**
121
+ * Update index strategy based on field statistics
122
+ */
123
+ private updateIndexStrategy;
66
124
  /**
67
125
  * Get IDs matching a range query
68
126
  */
@@ -80,7 +138,7 @@ export declare class MetadataIndexManager {
80
138
  */
81
139
  private makeSafeFilename;
82
140
  /**
83
- * Normalize value for consistent indexing
141
+ * Normalize value for consistent indexing with smart optimization
84
142
  */
85
143
  private normalizeValue;
86
144
  /**
@@ -186,4 +244,63 @@ export declare class MetadataIndexManager {
186
244
  * Delete index entry from storage using safe filenames
187
245
  */
188
246
  private deleteIndexEntry;
247
+ /**
248
+ * Get field statistics for optimization and discovery
249
+ */
250
+ getFieldStatistics(): Promise<Map<string, FieldStats>>;
251
+ /**
252
+ * Get field cardinality information
253
+ */
254
+ getFieldCardinality(field: string): Promise<CardinalityInfo | null>;
255
+ /**
256
+ * Get all field names with their cardinality (for query optimization)
257
+ */
258
+ getFieldsWithCardinality(): Promise<Array<{
259
+ field: string;
260
+ cardinality: number;
261
+ distribution: string;
262
+ }>>;
263
+ /**
264
+ * Get optimal query plan based on field statistics
265
+ */
266
+ getOptimalQueryPlan(filters: Record<string, any>): Promise<{
267
+ strategy: 'exact' | 'range' | 'hybrid';
268
+ fieldOrder: string[];
269
+ estimatedCost: number;
270
+ }>;
271
+ /**
272
+ * Export field statistics for analysis
273
+ */
274
+ exportFieldStats(): Promise<any>;
275
+ /**
276
+ * Update type-field affinity tracking for intelligent NLP
277
+ * Tracks which fields commonly appear with which entity types
278
+ */
279
+ private updateTypeFieldAffinity;
280
+ /**
281
+ * Get fields that commonly appear with a specific entity type
282
+ * Returns fields with their affinity scores (0-1)
283
+ */
284
+ getFieldsForType(nounType: NounType): Promise<Array<{
285
+ field: string;
286
+ affinity: number;
287
+ occurrences: number;
288
+ totalEntities: number;
289
+ }>>;
290
+ /**
291
+ * Get type-field affinity statistics for analysis
292
+ */
293
+ getTypeFieldAffinityStats(): Promise<{
294
+ totalTypes: number;
295
+ averageFieldsPerType: number;
296
+ typeBreakdown: Record<string, {
297
+ totalEntities: number;
298
+ uniqueFields: number;
299
+ topFields: Array<{
300
+ field: string;
301
+ affinity: number;
302
+ }>;
303
+ }>;
304
+ }>;
189
305
  }
306
+ export {};