@soulcraft/brainy 3.0.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 (260) hide show
  1. package/CHANGELOG.md +53 -3
  2. package/README.md +353 -110
  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 +273 -0
  90. package/dist/brainy.js +1181 -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/browserFramework.d.ts +6 -6
  96. package/dist/browserFramework.js +11 -8
  97. package/dist/browserFramework.minimal.d.ts +5 -5
  98. package/dist/browserFramework.minimal.js +11 -8
  99. package/dist/config/distributedPresets-new.d.ts +118 -0
  100. package/dist/config/distributedPresets-new.js +318 -0
  101. package/dist/config/distributedPresets.d.ts +118 -0
  102. package/dist/config/distributedPresets.js +318 -0
  103. package/dist/config/extensibleConfig.d.ts +99 -0
  104. package/dist/config/extensibleConfig.js +268 -0
  105. package/dist/config/index.d.ts +17 -0
  106. package/dist/config/index.js +35 -0
  107. package/dist/config/modelAutoConfig.d.ts +32 -0
  108. package/dist/config/modelAutoConfig.js +139 -0
  109. package/dist/config/modelPrecisionManager.d.ts +42 -0
  110. package/dist/config/modelPrecisionManager.js +98 -0
  111. package/dist/config/sharedConfigManager.d.ts +67 -0
  112. package/dist/config/sharedConfigManager.js +215 -0
  113. package/dist/config/storageAutoConfig.d.ts +41 -0
  114. package/dist/config/storageAutoConfig.js +328 -0
  115. package/dist/config/zeroConfig.d.ts +68 -0
  116. package/dist/config/zeroConfig.js +301 -0
  117. package/dist/cortex/backupRestore.d.ts +2 -2
  118. package/dist/cortex/backupRestore.js +85 -27
  119. package/dist/cortex/healthCheck.d.ts +2 -2
  120. package/dist/cortex/neuralImport.d.ts +2 -2
  121. package/dist/cortex/neuralImport.js +18 -13
  122. package/dist/cortex/performanceMonitor.d.ts +2 -2
  123. package/dist/critical/model-guardian.d.ts +4 -0
  124. package/dist/critical/model-guardian.js +31 -11
  125. package/dist/demo.d.ts +4 -4
  126. package/dist/demo.js +7 -7
  127. package/dist/distributed/cacheSync.d.ts +112 -0
  128. package/dist/distributed/cacheSync.js +265 -0
  129. package/dist/distributed/coordinator.d.ts +193 -0
  130. package/dist/distributed/coordinator.js +548 -0
  131. package/dist/distributed/httpTransport.d.ts +120 -0
  132. package/dist/distributed/httpTransport.js +446 -0
  133. package/dist/distributed/index.d.ts +8 -0
  134. package/dist/distributed/index.js +5 -0
  135. package/dist/distributed/networkTransport.d.ts +132 -0
  136. package/dist/distributed/networkTransport.js +633 -0
  137. package/dist/distributed/queryPlanner.d.ts +104 -0
  138. package/dist/distributed/queryPlanner.js +327 -0
  139. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  140. package/dist/distributed/readWriteSeparation.js +350 -0
  141. package/dist/distributed/shardManager.d.ts +114 -0
  142. package/dist/distributed/shardManager.js +357 -0
  143. package/dist/distributed/shardMigration.d.ts +110 -0
  144. package/dist/distributed/shardMigration.js +289 -0
  145. package/dist/distributed/storageDiscovery.d.ts +160 -0
  146. package/dist/distributed/storageDiscovery.js +551 -0
  147. package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
  148. package/dist/embeddings/CachedEmbeddings.js +146 -0
  149. package/dist/embeddings/EmbeddingManager.d.ts +102 -0
  150. package/dist/embeddings/EmbeddingManager.js +291 -0
  151. package/dist/embeddings/SingletonModelManager.d.ts +95 -0
  152. package/dist/embeddings/SingletonModelManager.js +220 -0
  153. package/dist/embeddings/index.d.ts +12 -0
  154. package/dist/embeddings/index.js +16 -0
  155. package/dist/embeddings/lightweight-embedder.d.ts +0 -1
  156. package/dist/embeddings/lightweight-embedder.js +4 -12
  157. package/dist/embeddings/model-manager.d.ts +11 -0
  158. package/dist/embeddings/model-manager.js +43 -7
  159. package/dist/embeddings/universal-memory-manager.d.ts +1 -1
  160. package/dist/embeddings/universal-memory-manager.js +27 -67
  161. package/dist/embeddings/worker-embedding.js +4 -8
  162. package/dist/errors/brainyError.d.ts +5 -1
  163. package/dist/errors/brainyError.js +12 -0
  164. package/dist/examples/basicUsage.js +7 -4
  165. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  166. package/dist/graph/graphAdjacencyIndex.js +288 -0
  167. package/dist/graph/pathfinding.js +4 -2
  168. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  169. package/dist/importManager.js +8 -5
  170. package/dist/index.d.ts +17 -22
  171. package/dist/index.js +37 -23
  172. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  173. package/dist/mcp/brainyMCPAdapter.js +5 -5
  174. package/dist/mcp/brainyMCPService.d.ts +3 -3
  175. package/dist/mcp/brainyMCPService.js +3 -11
  176. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  177. package/dist/neural/embeddedPatterns.d.ts +1 -1
  178. package/dist/neural/embeddedPatterns.js +2 -2
  179. package/dist/neural/entityExtractor.d.ts +65 -0
  180. package/dist/neural/entityExtractor.js +316 -0
  181. package/dist/neural/improvedNeuralAPI.d.ts +357 -0
  182. package/dist/neural/improvedNeuralAPI.js +2628 -0
  183. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  184. package/dist/neural/naturalLanguageProcessor.js +941 -66
  185. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  186. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  187. package/dist/neural/neuralAPI.js +8 -2
  188. package/dist/neural/patternLibrary.d.ts +57 -3
  189. package/dist/neural/patternLibrary.js +348 -13
  190. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  191. package/dist/neural/staticPatternMatcher.js +2 -2
  192. package/dist/neural/types.d.ts +287 -0
  193. package/dist/neural/types.js +24 -0
  194. package/dist/shared/default-augmentations.d.ts +3 -3
  195. package/dist/shared/default-augmentations.js +5 -5
  196. package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
  197. package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
  198. package/dist/storage/adapters/fileSystemStorage.js +218 -15
  199. package/dist/storage/adapters/memoryStorage.d.ts +4 -4
  200. package/dist/storage/adapters/memoryStorage.js +17 -12
  201. package/dist/storage/adapters/opfsStorage.d.ts +2 -2
  202. package/dist/storage/adapters/opfsStorage.js +2 -2
  203. package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
  204. package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
  205. package/dist/storage/backwardCompatibility.d.ts +10 -78
  206. package/dist/storage/backwardCompatibility.js +17 -132
  207. package/dist/storage/baseStorage.d.ts +18 -2
  208. package/dist/storage/baseStorage.js +74 -3
  209. package/dist/storage/cacheManager.js +2 -2
  210. package/dist/storage/readOnlyOptimizations.js +8 -3
  211. package/dist/streaming/pipeline.d.ts +154 -0
  212. package/dist/streaming/pipeline.js +551 -0
  213. package/dist/triple/TripleIntelligence.d.ts +25 -110
  214. package/dist/triple/TripleIntelligence.js +4 -574
  215. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  216. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  217. package/dist/types/apiTypes.d.ts +278 -0
  218. package/dist/types/apiTypes.js +33 -0
  219. package/dist/types/brainy.types.d.ts +308 -0
  220. package/dist/types/brainy.types.js +8 -0
  221. package/dist/types/brainyDataInterface.d.ts +5 -8
  222. package/dist/types/brainyDataInterface.js +2 -2
  223. package/dist/types/graphTypes.js +2 -2
  224. package/dist/utils/brainyTypes.d.ts +217 -0
  225. package/dist/utils/brainyTypes.js +261 -0
  226. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  227. package/dist/utils/embedding.d.ts +9 -4
  228. package/dist/utils/embedding.js +89 -26
  229. package/dist/utils/enhancedLogger.d.ts +104 -0
  230. package/dist/utils/enhancedLogger.js +232 -0
  231. package/dist/utils/hybridModelManager.d.ts +19 -28
  232. package/dist/utils/hybridModelManager.js +36 -200
  233. package/dist/utils/index.d.ts +1 -1
  234. package/dist/utils/index.js +1 -1
  235. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  236. package/dist/utils/intelligentTypeMapper.js +349 -0
  237. package/dist/utils/metadataIndex.d.ts +118 -1
  238. package/dist/utils/metadataIndex.js +539 -16
  239. package/dist/utils/nodeVersionCheck.d.ts +24 -0
  240. package/dist/utils/nodeVersionCheck.js +65 -0
  241. package/dist/utils/paramValidation.d.ts +39 -0
  242. package/dist/utils/paramValidation.js +192 -0
  243. package/dist/utils/rateLimiter.d.ts +160 -0
  244. package/dist/utils/rateLimiter.js +271 -0
  245. package/dist/utils/statistics.d.ts +4 -4
  246. package/dist/utils/statistics.js +3 -3
  247. package/dist/utils/structuredLogger.d.ts +146 -0
  248. package/dist/utils/structuredLogger.js +394 -0
  249. package/dist/utils/textEncoding.js +2 -1
  250. package/dist/utils/typeValidation.d.ts +59 -0
  251. package/dist/utils/typeValidation.js +374 -0
  252. package/dist/utils/version.js +19 -3
  253. package/package.json +15 -4
  254. package/scripts/download-models.cjs +94 -20
  255. package/dist/augmentations/walAugmentation.d.ts +0 -109
  256. package/dist/augmentations/walAugmentation.js +0 -516
  257. package/dist/chat/BrainyChat.d.ts +0 -121
  258. package/dist/chat/BrainyChat.js +0 -396
  259. package/dist/chat/ChatCLI.d.ts +0 -61
  260. package/dist/chat/ChatCLI.js +0 -351
@@ -26,7 +26,7 @@ export declare class NaturalLanguageProcessor {
26
26
  /**
27
27
  * Process natural language query into structured Triple Intelligence query
28
28
  * @param naturalQuery The natural language query string
29
- * @param queryEmbedding Pre-computed embedding from BrainyData (passed in to avoid circular dependency)
29
+ * @param queryEmbedding Pre-computed embedding from Brainy (passed in to avoid circular dependency)
30
30
  */
31
31
  processNaturalQuery(naturalQuery: string, queryEmbedding?: Vector): Promise<TripleQuery>;
32
32
  /**
@@ -46,7 +46,7 @@ export declare class NaturalLanguageProcessor {
46
46
  */
47
47
  private buildFieldConstraints;
48
48
  /**
49
- * Find similar queries from history (without using BrainyData)
49
+ * Find similar queries from history (without using Brainy)
50
50
  */
51
51
  private findSimilarQueries;
52
52
  /**
@@ -20,7 +20,7 @@ export class NaturalLanguageProcessor {
20
20
  /**
21
21
  * Process natural language query into structured Triple Intelligence query
22
22
  * @param naturalQuery The natural language query string
23
- * @param queryEmbedding Pre-computed embedding from BrainyData (passed in to avoid circular dependency)
23
+ * @param queryEmbedding Pre-computed embedding from Brainy (passed in to avoid circular dependency)
24
24
  */
25
25
  async processNaturalQuery(naturalQuery, queryEmbedding) {
26
26
  // Use static pattern matcher (no async, no memory allocation!)
@@ -33,7 +33,7 @@ export class NaturalLanguageProcessor {
33
33
  structuredQuery.where = this.buildFieldConstraints(intent.extractedTerms.fields);
34
34
  }
35
35
  }
36
- // Track for learning (but don't create new BrainyData!)
36
+ // Track for learning (but don't create new Brainy!)
37
37
  this.queryHistory.push({
38
38
  query: naturalQuery,
39
39
  result: structuredQuery,
@@ -118,7 +118,7 @@ export class NaturalLanguageProcessor {
118
118
  return constraints;
119
119
  }
120
120
  /**
121
- * Find similar queries from history (without using BrainyData)
121
+ * Find similar queries from history (without using Brainy)
122
122
  */
123
123
  findSimilarQueries(embedding) {
124
124
  // Simple similarity check against recent history
@@ -603,10 +603,16 @@ export class NeuralAPI {
603
603
  return { width: 100, height: 100 };
604
604
  }
605
605
  async getViewportLOD(viewport, lod) {
606
- return {};
606
+ // LOD visualization is an optional advanced feature
607
+ // Return default view without LOD optimization
608
+ console.warn('Viewport LOD optimization not available. Using standard view.');
609
+ return { nodes: [], edges: [], optimized: false };
607
610
  }
608
611
  async getGlobalLOD(lod) {
609
- return {};
612
+ // LOD visualization is an optional advanced feature
613
+ // Return default view without LOD optimization
614
+ console.warn('Global LOD optimization not available. Using standard view.');
615
+ return { nodes: [], edges: [], optimized: false };
610
616
  }
611
617
  }
612
618
  //# sourceMappingURL=neuralAPI.js.map
@@ -8,7 +8,7 @@
8
8
  * - Progressive learning from usage
9
9
  */
10
10
  import { Vector } from '../coreTypes.js';
11
- import { BrainyData } from '../brainyData.js';
11
+ import { Brainy } from '../brainy.js';
12
12
  export interface Pattern {
13
13
  id: string;
14
14
  category: string;
@@ -19,10 +19,20 @@ export interface Pattern {
19
19
  embedding?: Vector;
20
20
  domain?: string;
21
21
  frequency?: number | string;
22
+ slots?: SlotDefinition[];
23
+ }
24
+ export interface SlotDefinition {
25
+ name: string;
26
+ type: 'text' | 'number' | 'date' | 'entity' | 'location' | 'person' | 'any';
27
+ required?: boolean;
28
+ default?: any;
29
+ pattern?: string;
30
+ transform?: (value: string) => any;
22
31
  }
23
32
  export interface SlotExtraction {
24
33
  slots: Record<string, any>;
25
34
  confidence: number;
35
+ errors?: string[];
26
36
  }
27
37
  export declare class PatternLibrary {
28
38
  private patterns;
@@ -30,7 +40,7 @@ export declare class PatternLibrary {
30
40
  private brain;
31
41
  private embeddingCache;
32
42
  private successMetrics;
33
- constructor(brain: BrainyData);
43
+ constructor(brain: Brainy);
34
44
  /**
35
45
  * Initialize pattern library with pre-computed embeddings
36
46
  */
@@ -51,9 +61,53 @@ export declare class PatternLibrary {
51
61
  similarity: number;
52
62
  }>>;
53
63
  /**
54
- * Extract slots from query based on pattern
64
+ * Extract slots from query based on pattern with enhanced fuzzy matching
55
65
  */
56
66
  extractSlots(query: string, pattern: Pattern): SlotExtraction;
67
+ /**
68
+ * Extract named slots with type validation
69
+ */
70
+ private extractNamedSlots;
71
+ /**
72
+ * Fuzzy extraction using Levenshtein distance
73
+ */
74
+ private fuzzyExtractSlots;
75
+ /**
76
+ * Fuzzy extraction for named slots
77
+ */
78
+ private fuzzyExtractNamedSlots;
79
+ /**
80
+ * Find slot value in tokens based on type
81
+ */
82
+ private findSlotValueInTokens;
83
+ /**
84
+ * Get default regex pattern for slot type
85
+ */
86
+ private getDefaultPatternForType;
87
+ /**
88
+ * Transform value based on type
89
+ */
90
+ private transformByType;
91
+ /**
92
+ * Validate slot value against definition
93
+ */
94
+ private validateSlotValue;
95
+ /**
96
+ * Calculate Levenshtein distance between two strings
97
+ */
98
+ private levenshteinDistance;
99
+ /**
100
+ * Align two strings for slot extraction
101
+ */
102
+ private alignStrings;
103
+ /**
104
+ * Find best token match using fuzzy comparison
105
+ */
106
+ private findBestTokenMatch;
107
+ /**
108
+ * Extract slots from string alignment
109
+ */
110
+ private extractSlotsFromAlignment;
57
111
  /**
58
112
  * Fill template with extracted slots
59
113
  */
@@ -69,6 +69,7 @@ export class PatternLibrary {
69
69
  if (this.embeddingCache.has(text)) {
70
70
  return this.embeddingCache.get(text);
71
71
  }
72
+ // Use brain's embed method directly to avoid recursion
72
73
  const embedding = await this.brain.embed(text);
73
74
  this.embeddingCache.set(text, embedding);
74
75
  return embedding;
@@ -95,11 +96,16 @@ export class PatternLibrary {
95
96
  return matches.slice(0, k);
96
97
  }
97
98
  /**
98
- * Extract slots from query based on pattern
99
+ * Extract slots from query based on pattern with enhanced fuzzy matching
99
100
  */
100
101
  extractSlots(query, pattern) {
101
102
  const slots = {};
103
+ const errors = [];
102
104
  let confidence = pattern.confidence;
105
+ // If pattern has named slot definitions, use them
106
+ if (pattern.slots && pattern.slots.length > 0) {
107
+ return this.extractNamedSlots(query, pattern);
108
+ }
103
109
  // Try regex extraction first
104
110
  const regex = new RegExp(pattern.pattern, 'i');
105
111
  const match = query.match(regex);
@@ -112,21 +118,350 @@ export class PatternLibrary {
112
118
  confidence = Math.min(confidence * 1.2, 1.0);
113
119
  }
114
120
  else {
115
- // Fall back to token-based extraction
116
- const tokens = this.tokenize(query);
117
- const exampleTokens = this.tokenize(pattern.examples[0]);
118
- // Simple alignment-based extraction
119
- for (let i = 0; i < tokens.length; i++) {
120
- if (i < exampleTokens.length && exampleTokens[i].startsWith('$')) {
121
- slots[exampleTokens[i]] = tokens[i];
122
- }
121
+ // Enhanced fuzzy matching with Levenshtein distance
122
+ const fuzzyResult = this.fuzzyExtractSlots(query, pattern);
123
+ Object.assign(slots, fuzzyResult.slots);
124
+ confidence = fuzzyResult.confidence;
125
+ if (fuzzyResult.errors) {
126
+ errors.push(...fuzzyResult.errors);
123
127
  }
124
- // Lower confidence for fuzzy matching
125
- confidence *= 0.7;
126
128
  }
127
129
  // Post-process slots
128
130
  this.postProcessSlots(slots, pattern);
129
- return { slots, confidence };
131
+ return { slots, confidence, errors: errors.length > 0 ? errors : undefined };
132
+ }
133
+ /**
134
+ * Extract named slots with type validation
135
+ */
136
+ extractNamedSlots(query, pattern) {
137
+ const slots = {};
138
+ const errors = [];
139
+ let confidence = pattern.confidence;
140
+ if (!pattern.slots) {
141
+ return { slots, confidence };
142
+ }
143
+ // Create a flexible regex from pattern
144
+ let flexiblePattern = pattern.pattern;
145
+ const slotPositions = new Map();
146
+ // Replace named slots in pattern with capture groups
147
+ pattern.slots.forEach((slot, index) => {
148
+ const slotPattern = slot.pattern || this.getDefaultPatternForType(slot.type);
149
+ flexiblePattern = flexiblePattern.replace(new RegExp(`\\{${slot.name}\\}`, 'g'), `(${slotPattern})`);
150
+ slotPositions.set(index + 1, slot);
151
+ });
152
+ const regex = new RegExp(flexiblePattern, 'i');
153
+ const match = query.match(regex);
154
+ if (match) {
155
+ // Extract and validate each slot
156
+ slotPositions.forEach((slotDef, position) => {
157
+ const value = match[position];
158
+ if (value) {
159
+ // Apply transformation if defined
160
+ const transformedValue = slotDef.transform
161
+ ? slotDef.transform(value)
162
+ : this.transformByType(value, slotDef.type);
163
+ // Validate the value
164
+ if (this.validateSlotValue(transformedValue, slotDef)) {
165
+ slots[slotDef.name] = transformedValue;
166
+ }
167
+ else {
168
+ errors.push(`Invalid value for slot '${slotDef.name}': expected ${slotDef.type}, got '${value}'`);
169
+ confidence *= 0.8;
170
+ }
171
+ }
172
+ else if (slotDef.required) {
173
+ if (slotDef.default !== undefined) {
174
+ slots[slotDef.name] = slotDef.default;
175
+ }
176
+ else {
177
+ errors.push(`Required slot '${slotDef.name}' not found`);
178
+ confidence *= 0.5;
179
+ }
180
+ }
181
+ });
182
+ }
183
+ else {
184
+ // Try fuzzy matching for named slots
185
+ const fuzzyResult = this.fuzzyExtractNamedSlots(query, pattern);
186
+ Object.assign(slots, fuzzyResult.slots);
187
+ confidence = fuzzyResult.confidence;
188
+ if (fuzzyResult.errors) {
189
+ errors.push(...fuzzyResult.errors);
190
+ }
191
+ }
192
+ return { slots, confidence, errors: errors.length > 0 ? errors : undefined };
193
+ }
194
+ /**
195
+ * Fuzzy extraction using Levenshtein distance
196
+ */
197
+ fuzzyExtractSlots(query, pattern) {
198
+ const slots = {};
199
+ let bestConfidence = 0;
200
+ // Try each example with fuzzy matching
201
+ for (const example of pattern.examples) {
202
+ const distance = this.levenshteinDistance(query.toLowerCase(), example.toLowerCase());
203
+ const similarity = 1 - (distance / Math.max(query.length, example.length));
204
+ if (similarity > 0.6) { // 60% similarity threshold
205
+ // Extract slots using alignment
206
+ const aligned = this.alignStrings(query, example);
207
+ const extractedSlots = this.extractSlotsFromAlignment(aligned, pattern);
208
+ if (Object.keys(extractedSlots).length > 0) {
209
+ const currentConfidence = pattern.confidence * similarity;
210
+ if (currentConfidence > bestConfidence) {
211
+ Object.assign(slots, extractedSlots);
212
+ bestConfidence = currentConfidence;
213
+ }
214
+ }
215
+ }
216
+ }
217
+ return {
218
+ slots,
219
+ confidence: bestConfidence,
220
+ errors: bestConfidence < 0.5 ? ['Low confidence fuzzy match'] : undefined
221
+ };
222
+ }
223
+ /**
224
+ * Fuzzy extraction for named slots
225
+ */
226
+ fuzzyExtractNamedSlots(query, pattern) {
227
+ const slots = {};
228
+ const errors = [];
229
+ let confidence = pattern.confidence * 0.7; // Lower confidence for fuzzy
230
+ if (!pattern.slots) {
231
+ return { slots, confidence };
232
+ }
233
+ // Tokenize query for flexible matching
234
+ const tokens = this.tokenize(query);
235
+ pattern.slots.forEach(slotDef => {
236
+ const value = this.findSlotValueInTokens(tokens, slotDef);
237
+ if (value) {
238
+ const transformedValue = slotDef.transform
239
+ ? slotDef.transform(value)
240
+ : this.transformByType(value, slotDef.type);
241
+ if (this.validateSlotValue(transformedValue, slotDef)) {
242
+ slots[slotDef.name] = transformedValue;
243
+ }
244
+ else {
245
+ errors.push(`Fuzzy match: uncertain value for '${slotDef.name}'`);
246
+ confidence *= 0.9;
247
+ }
248
+ }
249
+ else if (slotDef.required && slotDef.default !== undefined) {
250
+ slots[slotDef.name] = slotDef.default;
251
+ }
252
+ });
253
+ return { slots, confidence, errors: errors.length > 0 ? errors : undefined };
254
+ }
255
+ /**
256
+ * Find slot value in tokens based on type
257
+ */
258
+ findSlotValueInTokens(tokens, slotDef) {
259
+ const joinedTokens = tokens.join(' ');
260
+ switch (slotDef.type) {
261
+ case 'number':
262
+ const numberMatch = joinedTokens.match(/\d+(\.\d+)?/);
263
+ return numberMatch ? numberMatch[0] : null;
264
+ case 'date':
265
+ const datePatterns = [
266
+ /\d{4}-\d{2}-\d{2}/,
267
+ /\d{1,2}\/\d{1,2}\/\d{2,4}/,
268
+ /(january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}/i,
269
+ /(today|tomorrow|yesterday)/i
270
+ ];
271
+ for (const pattern of datePatterns) {
272
+ const match = joinedTokens.match(pattern);
273
+ if (match)
274
+ return match[0];
275
+ }
276
+ return null;
277
+ case 'person':
278
+ // Look for capitalized words (proper nouns)
279
+ const personMatch = joinedTokens.match(/\b[A-Z][a-z]+(\s+[A-Z][a-z]+)*\b/);
280
+ return personMatch ? personMatch[0] : null;
281
+ case 'location':
282
+ // Look for location indicators
283
+ const locationPatterns = [
284
+ /\b(in|at|from|to)\s+([A-Z][a-z]+(\s+[A-Z][a-z]+)*)\b/,
285
+ /\b[A-Z][a-z]+,\s+[A-Z]{2}\b/ // City, STATE format
286
+ ];
287
+ for (const pattern of locationPatterns) {
288
+ const match = joinedTokens.match(pattern);
289
+ if (match)
290
+ return match[2] || match[0];
291
+ }
292
+ return null;
293
+ case 'entity':
294
+ case 'text':
295
+ case 'any':
296
+ default:
297
+ // Return first non-common word as potential value
298
+ const commonWords = new Set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for']);
299
+ const significantToken = tokens.find(t => !commonWords.has(t.toLowerCase()));
300
+ return significantToken || null;
301
+ }
302
+ }
303
+ /**
304
+ * Get default regex pattern for slot type
305
+ */
306
+ getDefaultPatternForType(type) {
307
+ switch (type) {
308
+ case 'number':
309
+ return '\\d+(?:\\.\\d+)?';
310
+ case 'date':
311
+ return '[\\w\\s,/-]+';
312
+ case 'person':
313
+ return '[A-Z][a-z]+(?:\\s+[A-Z][a-z]+)*';
314
+ case 'location':
315
+ return '[A-Z][a-z]+(?:[\\s,]+[A-Z][a-z]+)*';
316
+ case 'entity':
317
+ return '[\\w\\s-]+';
318
+ case 'text':
319
+ case 'any':
320
+ default:
321
+ return '.+';
322
+ }
323
+ }
324
+ /**
325
+ * Transform value based on type
326
+ */
327
+ transformByType(value, type) {
328
+ switch (type) {
329
+ case 'number':
330
+ const num = parseFloat(value);
331
+ return isNaN(num) ? value : num;
332
+ case 'date':
333
+ // Simple date parsing
334
+ if (value.toLowerCase() === 'today') {
335
+ return new Date().toISOString().split('T')[0];
336
+ }
337
+ else if (value.toLowerCase() === 'tomorrow') {
338
+ const tomorrow = new Date();
339
+ tomorrow.setDate(tomorrow.getDate() + 1);
340
+ return tomorrow.toISOString().split('T')[0];
341
+ }
342
+ else if (value.toLowerCase() === 'yesterday') {
343
+ const yesterday = new Date();
344
+ yesterday.setDate(yesterday.getDate() - 1);
345
+ return yesterday.toISOString().split('T')[0];
346
+ }
347
+ return value;
348
+ case 'person':
349
+ case 'location':
350
+ case 'entity':
351
+ // Capitalize properly
352
+ return value.split(' ')
353
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
354
+ .join(' ');
355
+ default:
356
+ return value.trim();
357
+ }
358
+ }
359
+ /**
360
+ * Validate slot value against definition
361
+ */
362
+ validateSlotValue(value, slotDef) {
363
+ if (value === null || value === undefined) {
364
+ return !slotDef.required;
365
+ }
366
+ switch (slotDef.type) {
367
+ case 'number':
368
+ return typeof value === 'number' && !isNaN(value);
369
+ case 'date':
370
+ return typeof value === 'string' && value.length > 0;
371
+ case 'text':
372
+ case 'person':
373
+ case 'location':
374
+ case 'entity':
375
+ return typeof value === 'string' && value.length > 0;
376
+ case 'any':
377
+ return true;
378
+ default:
379
+ return true;
380
+ }
381
+ }
382
+ /**
383
+ * Calculate Levenshtein distance between two strings
384
+ */
385
+ levenshteinDistance(s1, s2) {
386
+ const len1 = s1.length;
387
+ const len2 = s2.length;
388
+ const matrix = [];
389
+ for (let i = 0; i <= len1; i++) {
390
+ matrix[i] = [i];
391
+ }
392
+ for (let j = 0; j <= len2; j++) {
393
+ matrix[0][j] = j;
394
+ }
395
+ for (let i = 1; i <= len1; i++) {
396
+ for (let j = 1; j <= len2; j++) {
397
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
398
+ matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
399
+ matrix[i][j - 1] + 1, // insertion
400
+ matrix[i - 1][j - 1] + cost // substitution
401
+ );
402
+ }
403
+ }
404
+ return matrix[len1][len2];
405
+ }
406
+ /**
407
+ * Align two strings for slot extraction
408
+ */
409
+ alignStrings(query, example) {
410
+ const queryTokens = this.tokenize(query);
411
+ const exampleTokens = this.tokenize(example);
412
+ const aligned = [];
413
+ let i = 0, j = 0;
414
+ while (i < queryTokens.length && j < exampleTokens.length) {
415
+ if (queryTokens[i] === exampleTokens[j]) {
416
+ aligned.push([queryTokens[i], exampleTokens[j]]);
417
+ i++;
418
+ j++;
419
+ }
420
+ else {
421
+ // Try to find best match
422
+ const bestMatch = this.findBestTokenMatch(queryTokens[i], exampleTokens.slice(j, j + 3));
423
+ if (bestMatch.index >= 0) {
424
+ j += bestMatch.index;
425
+ aligned.push([queryTokens[i], exampleTokens[j]]);
426
+ }
427
+ else {
428
+ aligned.push([queryTokens[i], exampleTokens[j]]);
429
+ }
430
+ i++;
431
+ j++;
432
+ }
433
+ }
434
+ return aligned;
435
+ }
436
+ /**
437
+ * Find best token match using fuzzy comparison
438
+ */
439
+ findBestTokenMatch(token, candidates) {
440
+ let bestIndex = -1;
441
+ let bestSimilarity = 0;
442
+ candidates.forEach((candidate, index) => {
443
+ const distance = this.levenshteinDistance(token.toLowerCase(), candidate.toLowerCase());
444
+ const similarity = 1 - (distance / Math.max(token.length, candidate.length));
445
+ if (similarity > bestSimilarity && similarity > 0.6) {
446
+ bestIndex = index;
447
+ bestSimilarity = similarity;
448
+ }
449
+ });
450
+ return { index: bestIndex, similarity: bestSimilarity };
451
+ }
452
+ /**
453
+ * Extract slots from string alignment
454
+ */
455
+ extractSlotsFromAlignment(aligned, _pattern) {
456
+ const slots = {};
457
+ let slotIndex = 1;
458
+ aligned.forEach(([queryToken, exampleToken]) => {
459
+ if (exampleToken.startsWith('$')) {
460
+ slots[`$${slotIndex}`] = queryToken;
461
+ slotIndex++;
462
+ }
463
+ });
464
+ return slots;
130
465
  }
131
466
  /**
132
467
  * Fill template with extracted slots
@@ -246,7 +581,7 @@ export class PatternLibrary {
246
581
  /**
247
582
  * Helper: Post-process extracted slots
248
583
  */
249
- postProcessSlots(slots, pattern) {
584
+ postProcessSlots(slots, _pattern) {
250
585
  // Convert string numbers to actual numbers
251
586
  for (const [key, value] of Object.entries(slots)) {
252
587
  if (typeof value === 'string') {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Static Pattern Matcher - NO runtime initialization, NO BrainyData needed
2
+ * Static Pattern Matcher - NO runtime initialization, NO Brainy needed
3
3
  *
4
4
  * All patterns and embeddings are pre-computed at build time
5
5
  * This is pure pattern matching with zero dependencies
@@ -24,7 +24,7 @@ export declare function matchPatternByRegex(query: string): {
24
24
  } | null;
25
25
  /**
26
26
  * Convert natural language to structured query using STATIC patterns
27
- * NO initialization needed, NO BrainyData required
27
+ * NO initialization needed, NO Brainy required
28
28
  */
29
29
  export declare function patternMatchQuery(query: string, queryEmbedding?: Vector): TripleQuery;
30
30
  export declare const PATTERN_STATS: {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Static Pattern Matcher - NO runtime initialization, NO BrainyData needed
2
+ * Static Pattern Matcher - NO runtime initialization, NO Brainy needed
3
3
  *
4
4
  * All patterns and embeddings are pre-computed at build time
5
5
  * This is pure pattern matching with zero dependencies
@@ -111,7 +111,7 @@ export function matchPatternByRegex(query) {
111
111
  }
112
112
  /**
113
113
  * Convert natural language to structured query using STATIC patterns
114
- * NO initialization needed, NO BrainyData required
114
+ * NO initialization needed, NO Brainy required
115
115
  */
116
116
  export function patternMatchQuery(query, queryEmbedding) {
117
117
  // ALWAYS use vector similarity when we have embeddings (which we always do!)