@soulcraft/brainy 2.4.0 β†’ 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Universal Display Augmentation
3
+ *
4
+ * 🎨 Provides intelligent display fields for any noun or verb using AI-powered analysis
5
+ *
6
+ * Features:
7
+ * - βœ… Leverages existing IntelligentTypeMatcher for semantic type detection
8
+ * - βœ… Complete icon coverage for all 31 NounTypes + 40+ VerbTypes
9
+ * - βœ… Zero performance impact with lazy computation and intelligent caching
10
+ * - βœ… Perfect isolation - can be disabled, replaced, or configured
11
+ * - βœ… Clean developer experience with zero conflicts
12
+ * - βœ… TypeScript support with full autocomplete
13
+ *
14
+ * Usage:
15
+ * ```typescript
16
+ * // User data access (unchanged)
17
+ * result.firstName // "John"
18
+ * result.metadata.title // "CEO"
19
+ *
20
+ * // Enhanced display (new capabilities)
21
+ * result.getDisplay('title') // "John Doe" (AI-computed)
22
+ * result.getDisplay('description') // "CEO at Acme Corp" (enhanced)
23
+ * result.getDisplay('type') // "Person" (from AI detection)
24
+ * result.getDisplay() // All display fields
25
+ * ```
26
+ */
27
+ import { BaseAugmentation, AugmentationContext, MetadataAccess } from './brainyAugmentation.js';
28
+ import type { DisplayConfig, DisplayAugmentationStats } from './display/types.js';
29
+ /**
30
+ * Universal Display Augmentation
31
+ *
32
+ * Self-contained augmentation that provides intelligent display fields
33
+ * for any data type using existing Brainy AI infrastructure
34
+ */
35
+ export declare class UniversalDisplayAugmentation extends BaseAugmentation {
36
+ readonly name = "display";
37
+ readonly version = "1.0.0";
38
+ readonly timing: "after";
39
+ readonly priority = 50;
40
+ readonly metadata: MetadataAccess;
41
+ operations: any;
42
+ computedFields: {
43
+ display: {
44
+ title: {
45
+ type: "string";
46
+ description: string;
47
+ };
48
+ description: {
49
+ type: "string";
50
+ description: string;
51
+ };
52
+ type: {
53
+ type: "string";
54
+ description: string;
55
+ };
56
+ tags: {
57
+ type: "array";
58
+ description: string;
59
+ };
60
+ relationship: {
61
+ type: "string";
62
+ description: string;
63
+ };
64
+ confidence: {
65
+ type: "number";
66
+ description: string;
67
+ };
68
+ };
69
+ };
70
+ private computationEngine;
71
+ private displayCache;
72
+ private requestDeduplicator;
73
+ private config;
74
+ protected context: AugmentationContext | undefined;
75
+ constructor(config?: Partial<DisplayConfig>);
76
+ /**
77
+ * Initialize the augmentation with AI components
78
+ * @param context BrainyData context
79
+ */
80
+ initialize(context: AugmentationContext): Promise<void>;
81
+ /**
82
+ * Execute augmentation - attach display capabilities to results
83
+ * @param operation The operation being performed
84
+ * @param params Operation parameters
85
+ * @param next Function to execute main operation
86
+ * @returns Enhanced result with display capabilities
87
+ */
88
+ execute<T = any>(operation: string, params: any, next: () => Promise<T>): Promise<T>;
89
+ /**
90
+ * Check if operation should be enhanced
91
+ * @param operation Operation name
92
+ * @returns True if should enhance
93
+ */
94
+ private shouldEnhanceOperation;
95
+ /**
96
+ * Enhance result with display capabilities
97
+ * @param result The operation result
98
+ * @param operation The operation type
99
+ * @returns Enhanced result
100
+ */
101
+ private enhanceWithDisplayCapabilities;
102
+ /**
103
+ * Enhance a single entity with display capabilities
104
+ * @param entity The entity to enhance
105
+ * @returns Enhanced entity
106
+ */
107
+ private enhanceEntity;
108
+ /**
109
+ * Create getDisplay method for an entity
110
+ * @param entity The entity
111
+ * @param isVerb Whether it's a verb entity
112
+ * @returns getDisplay function
113
+ */
114
+ private createGetDisplayMethod;
115
+ /**
116
+ * Create getAvailableFields method
117
+ * @returns getAvailableFields function
118
+ */
119
+ private createGetAvailableFieldsMethod;
120
+ /**
121
+ * Create getAvailableAugmentations method
122
+ * @returns getAvailableAugmentations function
123
+ */
124
+ private createGetAvailableAugmentationsMethod;
125
+ /**
126
+ * Create explore method for debugging
127
+ * @param entity The entity
128
+ * @returns explore function
129
+ */
130
+ private createExploreMethod;
131
+ /**
132
+ * Check if an entity is a verb
133
+ * @param entity The entity to check
134
+ * @returns True if it's a verb
135
+ */
136
+ private isVerbEntity;
137
+ /**
138
+ * Get coverage information
139
+ * @returns Coverage info string
140
+ */
141
+ private getCoverageInfo;
142
+ /**
143
+ * Get augmentation statistics
144
+ * @returns Performance and usage statistics
145
+ */
146
+ getStats(): DisplayAugmentationStats;
147
+ /**
148
+ * Configure the augmentation at runtime
149
+ * @param newConfig Partial configuration to merge
150
+ */
151
+ configure(newConfig: Partial<DisplayConfig>): void;
152
+ /**
153
+ * Clear all cached display data
154
+ */
155
+ clearCache(): void;
156
+ /**
157
+ * Precompute display fields for a batch of entities
158
+ * @param entities Array of entities to precompute
159
+ */
160
+ precomputeBatch(entities: Array<{
161
+ id: string;
162
+ data: any;
163
+ }>): Promise<void>;
164
+ /**
165
+ * Optional check if this augmentation should run
166
+ * @param operation Operation name
167
+ * @param params Operation parameters
168
+ * @returns True if should execute
169
+ */
170
+ shouldExecute(operation: string, params: any): boolean;
171
+ /**
172
+ * Cleanup when augmentation is shut down
173
+ */
174
+ shutdown(): Promise<void>;
175
+ }
176
+ /**
177
+ * Factory function to create display augmentation with default config
178
+ * @param config Optional configuration overrides
179
+ * @returns Configured display augmentation instance
180
+ */
181
+ export declare function createDisplayAugmentation(config?: Partial<DisplayConfig>): UniversalDisplayAugmentation;
182
+ /**
183
+ * Default configuration for the display augmentation
184
+ */
185
+ export declare const DEFAULT_DISPLAY_CONFIG: DisplayConfig;
186
+ /**
187
+ * Export for easy import and registration
188
+ */
189
+ export default UniversalDisplayAugmentation;
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Universal Display Augmentation
3
+ *
4
+ * 🎨 Provides intelligent display fields for any noun or verb using AI-powered analysis
5
+ *
6
+ * Features:
7
+ * - βœ… Leverages existing IntelligentTypeMatcher for semantic type detection
8
+ * - βœ… Complete icon coverage for all 31 NounTypes + 40+ VerbTypes
9
+ * - βœ… Zero performance impact with lazy computation and intelligent caching
10
+ * - βœ… Perfect isolation - can be disabled, replaced, or configured
11
+ * - βœ… Clean developer experience with zero conflicts
12
+ * - βœ… TypeScript support with full autocomplete
13
+ *
14
+ * Usage:
15
+ * ```typescript
16
+ * // User data access (unchanged)
17
+ * result.firstName // "John"
18
+ * result.metadata.title // "CEO"
19
+ *
20
+ * // Enhanced display (new capabilities)
21
+ * result.getDisplay('title') // "John Doe" (AI-computed)
22
+ * result.getDisplay('description') // "CEO at Acme Corp" (enhanced)
23
+ * result.getDisplay('type') // "Person" (from AI detection)
24
+ * result.getDisplay() // All display fields
25
+ * ```
26
+ */
27
+ import { BaseAugmentation } from './brainyAugmentation.js';
28
+ import { IntelligentComputationEngine } from './display/intelligentComputation.js';
29
+ import { RequestDeduplicator, getGlobalDisplayCache } from './display/cache.js';
30
+ /**
31
+ * Universal Display Augmentation
32
+ *
33
+ * Self-contained augmentation that provides intelligent display fields
34
+ * for any data type using existing Brainy AI infrastructure
35
+ */
36
+ export class UniversalDisplayAugmentation extends BaseAugmentation {
37
+ constructor(config = {}) {
38
+ super();
39
+ this.name = 'display';
40
+ this.version = '1.0.0';
41
+ this.timing = 'after'; // Enhance results after main operations
42
+ this.priority = 50; // Medium priority - after core operations
43
+ this.metadata = {
44
+ reads: '*', // Read all user data for intelligent analysis
45
+ writes: ['_display'] // Cache computed fields in isolated namespace
46
+ };
47
+ this.operations = ['get', 'search', 'findSimilar', 'getVerb', 'addNoun', 'addVerb'];
48
+ // Computed fields declaration for TypeScript support and discovery
49
+ this.computedFields = {
50
+ display: {
51
+ title: { type: 'string', description: 'Primary display name (AI-computed)' },
52
+ description: { type: 'string', description: 'Enhanced description with context' },
53
+ type: { type: 'string', description: 'Human-readable type (from AI detection)' },
54
+ tags: { type: 'array', description: 'Generated display tags' },
55
+ relationship: { type: 'string', description: 'Human-readable relationship (verbs only)' },
56
+ confidence: { type: 'number', description: 'AI confidence score (0-1)' }
57
+ }
58
+ };
59
+ // Merge with defaults
60
+ this.config = {
61
+ enabled: true,
62
+ cacheSize: 1000,
63
+ lazyComputation: true,
64
+ batchSize: 50,
65
+ confidenceThreshold: 0.7,
66
+ customFieldMappings: {},
67
+ priorityFields: {},
68
+ debugMode: false,
69
+ ...config
70
+ };
71
+ // Initialize components
72
+ this.computationEngine = new IntelligentComputationEngine(this.config);
73
+ this.displayCache = getGlobalDisplayCache(this.config.cacheSize);
74
+ this.requestDeduplicator = new RequestDeduplicator(this.config.batchSize);
75
+ }
76
+ /**
77
+ * Initialize the augmentation with AI components
78
+ * @param context BrainyData context
79
+ */
80
+ async initialize(context) {
81
+ if (!this.config.enabled) {
82
+ this.log('🎨 Universal Display augmentation disabled');
83
+ return;
84
+ }
85
+ this.context = context;
86
+ try {
87
+ // Initialize AI-powered computation engine
88
+ await this.computationEngine.initialize();
89
+ this.log('🎨 Universal Display augmentation initialized successfully');
90
+ this.log(` Cache size: ${this.config.cacheSize}`);
91
+ this.log(` Lazy computation: ${this.config.lazyComputation}`);
92
+ this.log(` Coverage: ${this.getCoverageInfo()}`);
93
+ }
94
+ catch (error) {
95
+ this.log('⚠️ Display augmentation initialization warning:', 'warn');
96
+ this.log(` ${error}`, 'warn');
97
+ this.log(' Falling back to basic mode', 'warn');
98
+ }
99
+ }
100
+ /**
101
+ * Execute augmentation - attach display capabilities to results
102
+ * @param operation The operation being performed
103
+ * @param params Operation parameters
104
+ * @param next Function to execute main operation
105
+ * @returns Enhanced result with display capabilities
106
+ */
107
+ async execute(operation, params, next) {
108
+ // Always execute main operation first
109
+ const result = await next();
110
+ // Only enhance if enabled and operation is relevant
111
+ if (!this.config.enabled || !this.shouldEnhanceOperation(operation)) {
112
+ return result;
113
+ }
114
+ try {
115
+ // Enhance result with display capabilities
116
+ return this.enhanceWithDisplayCapabilities(result, operation);
117
+ }
118
+ catch (error) {
119
+ this.log(`Display enhancement failed for ${operation}: ${error}`, 'warn');
120
+ return result; // Return unenhanced result on error
121
+ }
122
+ }
123
+ /**
124
+ * Check if operation should be enhanced
125
+ * @param operation Operation name
126
+ * @returns True if should enhance
127
+ */
128
+ shouldEnhanceOperation(operation) {
129
+ const enhanceableOps = ['get', 'search', 'findSimilar', 'getVerb'];
130
+ return enhanceableOps.includes(operation);
131
+ }
132
+ /**
133
+ * Enhance result with display capabilities
134
+ * @param result The operation result
135
+ * @param operation The operation type
136
+ * @returns Enhanced result
137
+ */
138
+ enhanceWithDisplayCapabilities(result, operation) {
139
+ if (!result)
140
+ return result;
141
+ // Handle different result types
142
+ if (Array.isArray(result)) {
143
+ // Array of results (search, findSimilar)
144
+ return result.map(item => this.enhanceEntity(item));
145
+ }
146
+ else if (result.id || result.metadata) {
147
+ // Single entity (get, getVerb)
148
+ return this.enhanceEntity(result);
149
+ }
150
+ return result;
151
+ }
152
+ /**
153
+ * Enhance a single entity with display capabilities
154
+ * @param entity The entity to enhance
155
+ * @returns Enhanced entity
156
+ */
157
+ enhanceEntity(entity) {
158
+ if (!entity)
159
+ return entity;
160
+ // Determine if it's a noun or verb
161
+ const isVerb = this.isVerbEntity(entity);
162
+ // Add display methods
163
+ const enhanced = {
164
+ ...entity,
165
+ getDisplay: this.createGetDisplayMethod(entity, isVerb),
166
+ getAvailableFields: this.createGetAvailableFieldsMethod(),
167
+ getAvailableAugmentations: this.createGetAvailableAugmentationsMethod(),
168
+ explore: this.createExploreMethod(entity)
169
+ };
170
+ return enhanced;
171
+ }
172
+ /**
173
+ * Create getDisplay method for an entity
174
+ * @param entity The entity
175
+ * @param isVerb Whether it's a verb entity
176
+ * @returns getDisplay function
177
+ */
178
+ createGetDisplayMethod(entity, isVerb) {
179
+ return async (field) => {
180
+ // Generate cache key
181
+ const cacheKey = this.displayCache.generateKey(entity.id, entity.metadata || entity, isVerb ? 'verb' : 'noun');
182
+ // Use request deduplicator to prevent duplicate computations
183
+ const computedFields = await this.requestDeduplicator.deduplicate(cacheKey, async () => {
184
+ // Check cache first
185
+ let cached = this.displayCache.get(cacheKey);
186
+ if (cached)
187
+ return cached;
188
+ // Compute display fields
189
+ const startTime = Date.now();
190
+ let computed;
191
+ if (isVerb) {
192
+ computed = await this.computationEngine.computeVerbDisplay(entity);
193
+ }
194
+ else {
195
+ computed = await this.computationEngine.computeNounDisplay(entity.metadata || entity, entity.id);
196
+ }
197
+ // Cache the result
198
+ const computationTime = Date.now() - startTime;
199
+ this.displayCache.set(cacheKey, computed, computationTime);
200
+ return computed;
201
+ });
202
+ // Return specific field or all fields
203
+ return field ? computedFields[field] : computedFields;
204
+ };
205
+ }
206
+ /**
207
+ * Create getAvailableFields method
208
+ * @returns getAvailableFields function
209
+ */
210
+ createGetAvailableFieldsMethod() {
211
+ return (namespace) => {
212
+ if (namespace === 'display') {
213
+ return ['title', 'description', 'type', 'tags', 'relationship', 'confidence'];
214
+ }
215
+ return [];
216
+ };
217
+ }
218
+ /**
219
+ * Create getAvailableAugmentations method
220
+ * @returns getAvailableAugmentations function
221
+ */
222
+ createGetAvailableAugmentationsMethod() {
223
+ return () => {
224
+ return ['display']; // This augmentation provides 'display' namespace
225
+ };
226
+ }
227
+ /**
228
+ * Create explore method for debugging
229
+ * @param entity The entity
230
+ * @returns explore function
231
+ */
232
+ createExploreMethod(entity) {
233
+ return async () => {
234
+ console.log(`\nπŸ“‹ Entity Exploration: ${entity.id || 'unknown'}`);
235
+ console.log('━'.repeat(50));
236
+ // Show user data
237
+ console.log('\nπŸ‘€ User Data:');
238
+ const userData = entity.metadata || entity;
239
+ for (const [key, value] of Object.entries(userData)) {
240
+ if (!key.startsWith('_')) {
241
+ console.log(` β€’ ${key}: ${JSON.stringify(value)}`);
242
+ }
243
+ }
244
+ // Show computed display fields
245
+ try {
246
+ console.log('\n🎨 Display Fields:');
247
+ const displayMethod = this.createGetDisplayMethod(entity, this.isVerbEntity(entity));
248
+ const displayFields = await displayMethod();
249
+ for (const [key, value] of Object.entries(displayFields)) {
250
+ console.log(` β€’ ${key}: ${JSON.stringify(value)}`);
251
+ }
252
+ }
253
+ catch (error) {
254
+ console.log(` Error computing display fields: ${error}`);
255
+ }
256
+ console.log('');
257
+ };
258
+ }
259
+ /**
260
+ * Check if an entity is a verb
261
+ * @param entity The entity to check
262
+ * @returns True if it's a verb
263
+ */
264
+ isVerbEntity(entity) {
265
+ return !!(entity.sourceId && entity.targetId) ||
266
+ !!(entity.source && entity.target) ||
267
+ !!entity.verb;
268
+ }
269
+ /**
270
+ * Get coverage information
271
+ * @returns Coverage info string
272
+ */
273
+ getCoverageInfo() {
274
+ return 'Clean display - focuses on AI-powered content';
275
+ }
276
+ /**
277
+ * Get augmentation statistics
278
+ * @returns Performance and usage statistics
279
+ */
280
+ getStats() {
281
+ return this.displayCache.getStats();
282
+ }
283
+ /**
284
+ * Configure the augmentation at runtime
285
+ * @param newConfig Partial configuration to merge
286
+ */
287
+ configure(newConfig) {
288
+ this.config = { ...this.config, ...newConfig };
289
+ if (!this.config.enabled) {
290
+ this.displayCache.clear();
291
+ }
292
+ }
293
+ /**
294
+ * Clear all cached display data
295
+ */
296
+ clearCache() {
297
+ this.displayCache.clear();
298
+ }
299
+ /**
300
+ * Precompute display fields for a batch of entities
301
+ * @param entities Array of entities to precompute
302
+ */
303
+ async precomputeBatch(entities) {
304
+ const computeRequests = entities.map(({ id, data }) => ({
305
+ key: this.displayCache.generateKey(id, data, 'noun'),
306
+ computeFn: () => this.computationEngine.computeNounDisplay(data, id)
307
+ }));
308
+ await this.displayCache.batchPrecompute(computeRequests);
309
+ }
310
+ /**
311
+ * Optional check if this augmentation should run
312
+ * @param operation Operation name
313
+ * @param params Operation parameters
314
+ * @returns True if should execute
315
+ */
316
+ shouldExecute(operation, params) {
317
+ return this.config.enabled && this.shouldEnhanceOperation(operation);
318
+ }
319
+ /**
320
+ * Cleanup when augmentation is shut down
321
+ */
322
+ async shutdown() {
323
+ try {
324
+ // Cleanup computation engine
325
+ await this.computationEngine.shutdown();
326
+ // Cleanup request deduplicator
327
+ this.requestDeduplicator.shutdown();
328
+ // Clear cache if configured to do so
329
+ if (this.config.debugMode) {
330
+ const stats = this.getStats();
331
+ this.log(`🎨 Display augmentation shutdown statistics:`);
332
+ this.log(` Total computations: ${stats.totalComputations}`);
333
+ this.log(` Cache hit ratio: ${(stats.cacheHitRatio * 100).toFixed(1)}%`);
334
+ this.log(` Average computation time: ${stats.averageComputationTime.toFixed(1)}ms`);
335
+ }
336
+ this.log('🎨 Universal Display augmentation shut down');
337
+ }
338
+ catch (error) {
339
+ this.log(`Display augmentation shutdown error: ${error}`, 'error');
340
+ }
341
+ }
342
+ }
343
+ /**
344
+ * Factory function to create display augmentation with default config
345
+ * @param config Optional configuration overrides
346
+ * @returns Configured display augmentation instance
347
+ */
348
+ export function createDisplayAugmentation(config = {}) {
349
+ return new UniversalDisplayAugmentation(config);
350
+ }
351
+ /**
352
+ * Default configuration for the display augmentation
353
+ */
354
+ export const DEFAULT_DISPLAY_CONFIG = {
355
+ enabled: true,
356
+ cacheSize: 1000,
357
+ lazyComputation: true,
358
+ batchSize: 50,
359
+ confidenceThreshold: 0.7,
360
+ customFieldMappings: {},
361
+ priorityFields: {},
362
+ debugMode: false
363
+ };
364
+ /**
365
+ * Export for easy import and registration
366
+ */
367
+ export default UniversalDisplayAugmentation;
368
+ //# sourceMappingURL=universalDisplayAugmentation.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soulcraft/brainy",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "Universal Knowledge Protocolβ„’ - World's first Triple Intelligence database unifying vector, graph, and document search in one API. 31 nouns Γ— 40 verbs for infinite expressiveness.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",