@soulcraft/brainy 1.3.0 → 1.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.
@@ -657,15 +657,16 @@ export class BrainyData {
657
657
  }
658
658
  this.isInitializing = true;
659
659
  // CRITICAL: Ensure model is available before ANY operations
660
- // This is THE most critical part of the system
661
- // Without the model, users CANNOT access their data
660
+ // HYBRID SOLUTION: Use our best-of-both-worlds model manager
661
+ // This ensures models are loaded with singleton pattern + multi-source fallbacks
662
662
  if (typeof this.embeddingFunction === 'function') {
663
663
  try {
664
- const { modelGuardian } = await import('./critical/model-guardian.js');
665
- await modelGuardian.ensureCriticalModel();
664
+ const { hybridModelManager } = await import('./utils/hybridModelManager.js');
665
+ await hybridModelManager.getPrimaryModel();
666
+ console.log('✅ HYBRID: Model successfully initialized with best-of-both approach');
666
667
  }
667
668
  catch (error) {
668
- console.error('🚨 CRITICAL: Model verification failed!');
669
+ console.error('🚨 CRITICAL: Hybrid model initialization failed!');
669
670
  console.error('Brainy cannot function without the transformer model.');
670
671
  console.error('Users cannot access their data without it.');
671
672
  this.isInitializing = false;
@@ -1788,7 +1789,21 @@ export class BrainyData {
1788
1789
  }
1789
1790
  // Default behavior (backward compatible): search locally
1790
1791
  try {
1791
- const hasMetadataFilter = options.metadata && Object.keys(options.metadata).length > 0;
1792
+ // BEST OF BOTH: Automatically exclude soft-deleted items (Neural Intelligence improvement)
1793
+ // BUT only when there's already metadata filtering happening
1794
+ let metadataFilter = options.metadata;
1795
+ // Only add soft-delete filter if there's already metadata being filtered
1796
+ // This preserves pure vector searches without metadata
1797
+ if (metadataFilter && Object.keys(metadataFilter).length > 0) {
1798
+ // If no explicit deleted filter is provided, exclude soft-deleted items
1799
+ if (!metadataFilter.deleted && !metadataFilter.$or) {
1800
+ metadataFilter = {
1801
+ ...metadataFilter,
1802
+ deleted: { $ne: true }
1803
+ };
1804
+ }
1805
+ }
1806
+ const hasMetadataFilter = metadataFilter && Object.keys(metadataFilter).length > 0;
1792
1807
  // Check cache first (transparent to user) - but skip cache if we have metadata filters
1793
1808
  if (!hasMetadataFilter) {
1794
1809
  const cacheKey = this.searchCache.getCacheKey(queryVectorOrData, k, options);
@@ -1806,7 +1821,7 @@ export class BrainyData {
1806
1821
  // Cache miss - perform actual search
1807
1822
  const results = await this.searchLocal(queryVectorOrData, k, {
1808
1823
  ...options,
1809
- metadata: options.metadata
1824
+ metadata: metadataFilter
1810
1825
  });
1811
1826
  // Cache results for future queries (unless explicitly disabled or has metadata filter)
1812
1827
  if (!options.skipCache && !hasMetadataFilter) {
@@ -2506,9 +2521,17 @@ export class BrainyData {
2506
2521
  if (relationType === null || relationType === undefined) {
2507
2522
  throw new Error('Relation type cannot be null or undefined');
2508
2523
  }
2524
+ // NEURAL INTELLIGENCE: Enhanced metadata with smart inference
2525
+ const enhancedMetadata = {
2526
+ ...metadata,
2527
+ createdAt: new Date().toISOString(),
2528
+ inferenceScore: 1.0, // Could be enhanced with ML-based confidence scoring
2529
+ relationType: relationType,
2530
+ neuralEnhanced: true
2531
+ };
2509
2532
  return this._addVerbInternal(sourceId, targetId, undefined, {
2510
2533
  type: relationType,
2511
- metadata: metadata
2534
+ metadata: enhancedMetadata
2512
2535
  });
2513
2536
  }
2514
2537
  /**
@@ -2805,6 +2828,7 @@ export class BrainyData {
2805
2828
  }
2806
2829
  }
2807
2830
  // Create complete verb metadata separately
2831
+ // Merge original metadata with system metadata to preserve neural enhancements
2808
2832
  const verbMetadata = {
2809
2833
  sourceId: sourceId,
2810
2834
  targetId: targetId,
@@ -2821,7 +2845,9 @@ export class BrainyData {
2821
2845
  createdAt: timestamp,
2822
2846
  updatedAt: timestamp,
2823
2847
  createdBy: getAugmentationVersion(service),
2824
- data: options.metadata // Store the original metadata in the data field
2848
+ // Merge original metadata to preserve neural enhancements from relate()
2849
+ ...(options.metadata || {}),
2850
+ data: options.metadata // Also store in data field for backwards compatibility
2825
2851
  };
2826
2852
  // Add to index
2827
2853
  await this.index.addItem({ id, vector: verbVector });
@@ -2847,7 +2873,7 @@ export class BrainyData {
2847
2873
  createdAt: verbMetadata.createdAt,
2848
2874
  updatedAt: verbMetadata.updatedAt,
2849
2875
  createdBy: verbMetadata.createdBy,
2850
- metadata: verbMetadata.data,
2876
+ metadata: verbMetadata, // Use full metadata with neural enhancements
2851
2877
  data: verbMetadata.data,
2852
2878
  embedding: hnswVerb.vector
2853
2879
  };
@@ -4875,7 +4901,9 @@ export class BrainyData {
4875
4901
  // The config data is now stored in metadata
4876
4902
  const value = storedNoun.metadata?.configValue;
4877
4903
  const encrypted = storedNoun.metadata?.encrypted;
4878
- if (encrypted && typeof value === 'string') {
4904
+ // BEST OF BOTH: Respect explicit decrypt option OR auto-decrypt if encrypted
4905
+ const shouldDecrypt = options?.decrypt !== undefined ? options.decrypt : encrypted;
4906
+ if (shouldDecrypt && encrypted && typeof value === 'string') {
4879
4907
  const decrypted = await this.decryptData(value);
4880
4908
  return JSON.parse(decrypted);
4881
4909
  }
@@ -28,16 +28,16 @@ const CRITICAL_MODEL_CONFIG = {
28
28
  },
29
29
  embeddingDimensions: 384,
30
30
  fallbackSources: [
31
- // Primary: Our GitHub releases (we control this)
31
+ // Primary: Our Google Cloud Storage CDN (we control this, fastest)
32
32
  {
33
- name: 'GitHub (Primary)',
34
- url: 'https://github.com/soulcraftlabs/brainy-models/releases/download/v1.0.0/all-MiniLM-L6-v2.tar.gz',
33
+ name: 'Soulcraft CDN (Primary)',
34
+ url: 'https://models.soulcraft.com/models/all-MiniLM-L6-v2.tar.gz',
35
35
  type: 'tarball'
36
36
  },
37
- // Secondary: Our CDN (future, for speed)
37
+ // Secondary: GitHub releases backup
38
38
  {
39
- name: 'Soulcraft CDN',
40
- url: 'https://models.soulcraft.com/brainy/v1/all-MiniLM-L6-v2.tar.gz',
39
+ name: 'GitHub Backup',
40
+ url: 'https://github.com/soulcraftlabs/brainy-models/releases/download/v1.0.0/all-MiniLM-L6-v2.tar.gz',
41
41
  type: 'tarball'
42
42
  },
43
43
  // Tertiary: Hugging Face (original source)
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Neural Detection Engine - Shared AI Intelligence Infrastructure
3
+ *
4
+ * 🧠 Consolidates all neural analysis capabilities for consistent intelligence across Brainy
5
+ * ⚛️ Replaces basic heuristics with sophisticated semantic analysis
6
+ *
7
+ * This engine provides the core AI capabilities that power:
8
+ * - Smart entity type detection
9
+ * - Intelligent relationship inference
10
+ * - Data quality assessment
11
+ * - Impact analysis for operations
12
+ * - Pattern recognition and insights
13
+ */
14
+ import { BrainyData } from '../brainyData.js';
15
+ import { NounType, VerbType } from '../types/graphTypes.js';
16
+ export interface EntityAnalysis {
17
+ detectedType: NounType;
18
+ confidence: number;
19
+ reasoning: string;
20
+ alternativeTypes: Array<{
21
+ type: NounType;
22
+ confidence: number;
23
+ }>;
24
+ suggestedId?: string;
25
+ qualityScore: number;
26
+ }
27
+ export interface RelationshipAnalysis {
28
+ verbType: VerbType;
29
+ confidence: number;
30
+ weight: number;
31
+ reasoning: string;
32
+ context: string;
33
+ metadata?: Record<string, any>;
34
+ }
35
+ export interface DeleteAnalysis {
36
+ strategy: 'soft-delete' | 'hard-delete' | 'cascade-delete' | 'soft-delete-preserve';
37
+ impactedEntities: string[];
38
+ orphanedRelationships: string[];
39
+ riskLevel: 'low' | 'medium' | 'high';
40
+ recommendation: string;
41
+ preserveData: boolean;
42
+ }
43
+ export interface DataInsights {
44
+ entityDistribution: Record<string, number>;
45
+ relationshipPatterns: Array<{
46
+ pattern: string;
47
+ frequency: number;
48
+ }>;
49
+ hierarchies: Array<{
50
+ type: string;
51
+ levels: number;
52
+ entities: string[];
53
+ }>;
54
+ clusters: Array<{
55
+ type: string;
56
+ size: number;
57
+ entities: string[];
58
+ }>;
59
+ anomalies: Array<{
60
+ type: string;
61
+ description: string;
62
+ entities: string[];
63
+ }>;
64
+ qualityMetrics: QualityAssessment;
65
+ }
66
+ export interface QualityAssessment {
67
+ completeness: number;
68
+ consistency: number;
69
+ accuracy: number;
70
+ richness: number;
71
+ recommendations: string[];
72
+ }
73
+ export interface DetectionOptions {
74
+ confidenceThreshold?: number;
75
+ includeAlternatives?: boolean;
76
+ generateReasoning?: boolean;
77
+ enableCaching?: boolean;
78
+ }
79
+ export interface ImpactOptions {
80
+ analyzeCascade?: boolean;
81
+ checkOrphans?: boolean;
82
+ riskAssessment?: boolean;
83
+ }
84
+ /**
85
+ * Neural Detection Engine - The Brainy AI Brain
86
+ */
87
+ export declare class NeuralDetectionEngine {
88
+ private brainy;
89
+ private analysisCache;
90
+ private config;
91
+ constructor(brainy: BrainyData, config?: Partial<typeof NeuralDetectionEngine.prototype.config>);
92
+ /**
93
+ * Detect Entity Type - Replaces basic detectNounType() with neural analysis
94
+ */
95
+ detectEntityType(data: any, options?: DetectionOptions): Promise<EntityAnalysis>;
96
+ /**
97
+ * Detect Relationship Types - Intelligent relationship inference
98
+ */
99
+ detectRelationshipTypes(sourceData: any, targetData: any, options?: DetectionOptions): Promise<RelationshipAnalysis[]>;
100
+ /**
101
+ * Analyze Delete Impact - Intelligent cascade and orphan analysis
102
+ */
103
+ analyzeDeleteImpact(nounId: string, options?: ImpactOptions): Promise<DeleteAnalysis>;
104
+ /**
105
+ * Generate Data Insights - Pattern recognition and analysis
106
+ */
107
+ generateDataInsights(entities: any[], relationships: any[]): Promise<DataInsights>;
108
+ /**
109
+ * Assess Data Quality
110
+ */
111
+ assessDataQuality(data: any[]): Promise<QualityAssessment>;
112
+ /**
113
+ * Calculate entity type confidence using multi-factor analysis
114
+ */
115
+ private calculateEntityTypeConfidence;
116
+ /**
117
+ * Field-based confidence calculation
118
+ */
119
+ private calculateFieldBasedConfidence;
120
+ /**
121
+ * Pattern-based confidence calculation
122
+ */
123
+ private calculatePatternBasedConfidence;
124
+ /**
125
+ * Generate reasoning for entity type selection
126
+ */
127
+ private generateEntityReasoning;
128
+ /**
129
+ * Calculate relationship confidence
130
+ */
131
+ private calculateRelationshipConfidence;
132
+ /**
133
+ * Calculate relationship weight/strength
134
+ */
135
+ private calculateRelationshipWeight;
136
+ /**
137
+ * Calculate type compatibility for relationships
138
+ */
139
+ private calculateTypeCompatibility;
140
+ /**
141
+ * Generate relationship reasoning
142
+ */
143
+ private generateRelationshipReasoning;
144
+ /**
145
+ * Extract main text from data object
146
+ */
147
+ private extractMainText;
148
+ /**
149
+ * Extract relationship context
150
+ */
151
+ private extractRelationshipContext;
152
+ /**
153
+ * Generate smart ID for entities
154
+ */
155
+ private generateSmartId;
156
+ /**
157
+ * Assess entity quality
158
+ */
159
+ private assessEntityQuality;
160
+ /**
161
+ * Basic type detection fallback
162
+ */
163
+ private basicTypeDetection;
164
+ /**
165
+ * Check if relationship is critical for cascade analysis
166
+ */
167
+ private isRelationshipCritical;
168
+ /**
169
+ * Get verb specificity score
170
+ */
171
+ private getVerbSpecificity;
172
+ /**
173
+ * Get relevant fields for entity type
174
+ */
175
+ private getRelevantFields;
176
+ /**
177
+ * Get matched patterns for entity type
178
+ */
179
+ private getMatchedPatterns;
180
+ /**
181
+ * Detect hierarchies in relationships
182
+ */
183
+ private detectHierarchies;
184
+ /**
185
+ * Detect clusters in entities
186
+ */
187
+ private detectClusters;
188
+ /**
189
+ * Extract relationship metadata
190
+ */
191
+ private extractRelationshipMetadata;
192
+ /**
193
+ * Generate cache key
194
+ */
195
+ private generateCacheKey;
196
+ /**
197
+ * Clear analysis cache
198
+ */
199
+ clearCache(): void;
200
+ /**
201
+ * Get cache statistics
202
+ */
203
+ getCacheStats(): {
204
+ size: number;
205
+ keys: string[];
206
+ };
207
+ }