@soulcraft/brainy 0.51.1 → 0.52.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.
package/README.md CHANGED
@@ -129,6 +129,26 @@ const results = await brainy.search("wireless headphones", 10, {
129
129
  - ✅ **5x Fewer Dependencies**: Clean tree, no peer dependency issues
130
130
  - ✅ **Same API**: Drop-in replacement, existing code works unchanged
131
131
 
132
+ ### 🚀 Why Developers Love Brainy
133
+
134
+ - **🧠 Zero-to-Smart™** - No config files, no tuning parameters, no DevOps headaches. Brainy auto-detects your environment and optimizes itself
135
+ - **🌍 True Write-Once, Run-Anywhere** - Same code runs in Angular, React, Vue, Node.js, Deno, Bun, serverless, edge workers, and web workers with automatic environment detection
136
+ - **⚡ Scary Fast** - Handles millions of vectors with sub-millisecond search. GPU acceleration for embeddings, optimized CPU for distance calculations
137
+ - **🎯 Self-Learning** - Like having a database that goes to the gym. Gets faster and smarter the more you use it
138
+ - **🔮 AI-First Design** - Built for the age of embeddings, RAG, and semantic search. Your LLMs will thank you
139
+ - **🎮 Actually Fun to Use** - Clean API, great DX, and it does the heavy lifting so you can build cool stuff
140
+
141
+ ### 🚀 NEW: Ultra-Fast Search Performance + Auto-Configuration
142
+
143
+ **Your searches just got 100x faster AND Brainy now configures itself!** Advanced performance with zero setup:
144
+
145
+ - **🤖 Intelligent Auto-Configuration** - Detects environment and usage patterns, optimizes automatically
146
+ - **⚡ Smart Result Caching** - Repeated queries return in <1ms with automatic cache invalidation
147
+ - **📄 Cursor-Based Pagination** - Navigate millions of results with constant O(k) performance
148
+ - **🔄 Real-Time Data Sync** - Cache automatically updates when data changes, even in distributed scenarios
149
+ - **📊 Performance Monitoring** - Built-in hit rate and memory usage tracking with adaptive optimization
150
+ - **🎯 Zero Breaking Changes** - All existing code works unchanged, just faster and smarter
151
+
132
152
  ## 🏆 Why Brainy Wins
133
153
 
134
154
  - 🧠 **Triple Search Power** - Vector + Graph + Faceted filtering in one query
@@ -349,6 +369,62 @@ const health = reader.getHealthStatus()
349
369
  console.log(`Instance ${health.instanceId}: ${health.status}`)
350
370
  ```
351
371
 
372
+ ### 🐳 NEW: Zero-Config Docker Deployment
373
+
374
+ **Deploy to any cloud with embedded models - no runtime downloads needed!**
375
+
376
+ ```dockerfile
377
+ # One line extracts models automatically during build
378
+ RUN npm run download-models
379
+
380
+ # Deploy anywhere: Google Cloud, AWS, Azure, Cloudflare, etc.
381
+ ```
382
+
383
+ - **⚡ 7x Faster Cold Starts** - Models embedded in container, no downloads
384
+ - **🌐 Universal Cloud Support** - Same Dockerfile works everywhere
385
+ - **🔒 Offline Ready** - No external dependencies at runtime
386
+ - **📦 Zero Configuration** - Automatic model detection and loading
387
+
388
+ ```javascript
389
+ // Zero configuration - everything optimized automatically!
390
+ const brainy = new BrainyData() // Auto-detects environment & optimizes
391
+ await brainy.init()
392
+
393
+ // Caching happens automatically - no setup needed!
394
+ const results1 = await brainy.search('query', 10) // ~50ms first time
395
+ const results2 = await brainy.search('query', 10) // <1ms cached hit!
396
+
397
+ // Advanced pagination works instantly
398
+ const page1 = await brainy.searchWithCursor('query', 100)
399
+ const page2 = await brainy.searchWithCursor('query', 100, {
400
+ cursor: page1.cursor // Constant time, no matter how deep!
401
+ })
402
+
403
+ // Monitor auto-optimized performance
404
+ const stats = brainy.getCacheStats()
405
+ console.log(`Auto-tuned cache hit rate: ${(stats.search.hitRate * 100).toFixed(1)}%`)
406
+ ```
407
+
408
+ ## 🎭 Key Features
409
+
410
+ ### Core Capabilities
411
+
412
+ - **Vector Search** - Find semantically similar content using embeddings
413
+ - **MongoDB-Style Metadata Filtering** 🆕 - Advanced filtering with `$gt`, `$in`, `$regex`, `$and`, `$or` operators
414
+ - **Graph Relationships** - Connect data with meaningful relationships
415
+ - **JSON Document Search** - Search within specific fields with prioritization
416
+ - **Distributed Mode** - Scale horizontally with automatic coordination between instances
417
+ - **Real-Time Syncing** - WebSocket and WebRTC for distributed instances
418
+ - **Streaming Pipeline** - Process data in real-time as it flows through
419
+ - **Model Control Protocol** - Let AI models access your data
420
+
421
+ ### Developer Experience
422
+
423
+ - **TypeScript Support** - Fully typed API with generics
424
+ - **Extensible Augmentations** - Customize and extend functionality
425
+ - **REST API** - Web service wrapper for HTTP endpoints
426
+ - **Auto-Complete** - IntelliSense for all APIs and types
427
+
352
428
  ## 🆚 Why Not Just Use...?
353
429
 
354
430
  ### vs. Multiple Databases
@@ -488,6 +564,92 @@ Deploy to: Google Cloud Run, AWS Lambda/ECS, Azure Container Instances, Cloudfla
488
564
 
489
565
  </details>
490
566
 
567
+ ## 🚀 Getting Started in 30 Seconds
568
+
569
+ **The same Brainy code works everywhere - React, Vue, Angular, Node.js, Serverless, Edge Workers.**
570
+
571
+ ```javascript
572
+ // This EXACT code works in ALL environments
573
+ import { BrainyData } from '@soulcraft/brainy'
574
+
575
+ const brainy = new BrainyData()
576
+ await brainy.init()
577
+
578
+ // Add nouns (entities)
579
+ const openai = await brainy.add("OpenAI", { type: "company" })
580
+ const gpt4 = await brainy.add("GPT-4", { type: "product" })
581
+
582
+ // Add verbs (relationships)
583
+ await brainy.relate(openai, gpt4, "develops")
584
+
585
+ // Vector search + Graph traversal
586
+ const similar = await brainy.search("AI companies", 5)
587
+ const products = await brainy.getVerbsBySource(openai)
588
+ ```
589
+
590
+ <details>
591
+ <summary>🔍 <strong>See Framework Examples</strong></summary>
592
+
593
+ ### React
594
+
595
+ ```jsx
596
+ function App() {
597
+ const [brainy] = useState(() => new BrainyData())
598
+ useEffect(() => brainy.init(), [])
599
+
600
+ const search = async (query) => {
601
+ return await brainy.search(query, 10)
602
+ }
603
+ // Same API as above
604
+ }
605
+ ```
606
+
607
+ ### Vue 3
608
+
609
+ ```vue
610
+ <script setup>
611
+ const brainy = new BrainyData()
612
+ await brainy.init()
613
+ // Same API as above
614
+ </script>
615
+ ```
616
+
617
+ ### Angular
618
+
619
+ ```typescript
620
+ @Component({})
621
+ export class AppComponent {
622
+ brainy = new BrainyData()
623
+
624
+ async ngOnInit() {
625
+ await this.brainy.init()
626
+ // Same API as above
627
+ }
628
+ }
629
+ ```
630
+
631
+ ### Node.js / Deno / Bun
632
+
633
+ ```javascript
634
+ const brainy = new BrainyData()
635
+ await brainy.init()
636
+ // Same API as above
637
+ ```
638
+
639
+ </details>
640
+
641
+ ### 🌍 Framework-First, Runs Everywhere
642
+
643
+ **Brainy automatically detects your environment and optimizes everything:**
644
+
645
+ | Environment | Storage | Optimization |
646
+ |-----------------|-----------------|----------------------------|
647
+ | 🌐 Browser | OPFS | Web Workers, Memory Cache |
648
+ | 🟢 Node.js | FileSystem / S3 | Worker Threads, Clustering |
649
+ | ⚡ Serverless | S3 / Memory | Cold Start Optimization |
650
+ | 🔥 Edge Workers | Memory / KV | Minimal Footprint |
651
+ | 🦕 Deno/Bun | FileSystem / S3 | Native Performance |
652
+
491
653
  ## 📚 Documentation & Resources
492
654
 
493
655
  - **[🚀 Quick Start Guide](docs/getting-started/)** - Get up and running in minutes
@@ -0,0 +1,158 @@
1
+ import { ICognitionAugmentation, AugmentationResponse } from '../types/augmentations.js';
2
+ /**
3
+ * Configuration options for the Intelligent Verb Scoring augmentation
4
+ */
5
+ export interface IVerbScoringConfig {
6
+ /** Enable semantic proximity scoring based on entity embeddings */
7
+ enableSemanticScoring: boolean;
8
+ /** Enable frequency-based weight amplification */
9
+ enableFrequencyAmplification: boolean;
10
+ /** Enable temporal decay for weights */
11
+ enableTemporalDecay: boolean;
12
+ /** Decay rate per day for temporal scoring (0-1) */
13
+ temporalDecayRate: number;
14
+ /** Minimum weight threshold */
15
+ minWeight: number;
16
+ /** Maximum weight threshold */
17
+ maxWeight: number;
18
+ /** Base confidence score for new relationships */
19
+ baseConfidence: number;
20
+ /** Learning rate for adaptive scoring (0-1) */
21
+ learningRate: number;
22
+ }
23
+ /**
24
+ * Default configuration for the Intelligent Verb Scoring augmentation
25
+ */
26
+ export declare const DEFAULT_VERB_SCORING_CONFIG: IVerbScoringConfig;
27
+ /**
28
+ * Relationship statistics for learning and adaptation
29
+ */
30
+ interface RelationshipStats {
31
+ count: number;
32
+ totalWeight: number;
33
+ averageWeight: number;
34
+ lastSeen: Date;
35
+ firstSeen: Date;
36
+ semanticSimilarity?: number;
37
+ }
38
+ /**
39
+ * Intelligent Verb Scoring Cognition Augmentation
40
+ *
41
+ * Automatically generates intelligent weight and confidence scores for verb relationships
42
+ * using semantic analysis, frequency patterns, and temporal factors.
43
+ */
44
+ export declare class IntelligentVerbScoring implements ICognitionAugmentation {
45
+ readonly name = "intelligent-verb-scoring";
46
+ readonly description = "Automatically generates intelligent weight and confidence scores for verb relationships";
47
+ enabled: boolean;
48
+ private config;
49
+ private relationshipStats;
50
+ private brainyInstance;
51
+ private isInitialized;
52
+ constructor(config?: Partial<IVerbScoringConfig>);
53
+ initialize(): Promise<void>;
54
+ shutDown(): Promise<void>;
55
+ getStatus(): Promise<'active' | 'inactive' | 'error'>;
56
+ /**
57
+ * Set reference to the BrainyData instance for accessing graph data
58
+ */
59
+ setBrainyInstance(instance: any): void;
60
+ /**
61
+ * Main reasoning method for generating intelligent verb scores
62
+ */
63
+ reason(query: string, context?: Record<string, unknown>): AugmentationResponse<{
64
+ inference: string;
65
+ confidence: number;
66
+ }>;
67
+ infer(dataSubset: Record<string, unknown>): AugmentationResponse<Record<string, unknown>>;
68
+ executeLogic(ruleId: string, input: Record<string, unknown>): AugmentationResponse<boolean>;
69
+ /**
70
+ * Generate intelligent weight and confidence scores for a verb relationship
71
+ *
72
+ * @param sourceId - ID of the source entity
73
+ * @param targetId - ID of the target entity
74
+ * @param verbType - Type of the relationship
75
+ * @param existingWeight - Existing weight if any
76
+ * @param metadata - Additional metadata about the relationship
77
+ * @returns Computed weight and confidence scores
78
+ */
79
+ computeVerbScores(sourceId: string, targetId: string, verbType: string, existingWeight?: number, metadata?: any): Promise<{
80
+ weight: number;
81
+ confidence: number;
82
+ reasoning: string[];
83
+ }>;
84
+ /**
85
+ * Calculate semantic similarity between two entities using their embeddings
86
+ */
87
+ private calculateSemanticScore;
88
+ /**
89
+ * Calculate frequency-based boost for repeated relationships
90
+ */
91
+ private calculateFrequencyBoost;
92
+ /**
93
+ * Calculate temporal decay factor based on recency
94
+ */
95
+ private calculateTemporalFactor;
96
+ /**
97
+ * Calculate learning-based adjustment using historical patterns
98
+ */
99
+ private calculateLearningAdjustment;
100
+ /**
101
+ * Update relationship statistics for learning
102
+ */
103
+ private updateRelationshipStats;
104
+ /**
105
+ * Blend two scores using a weighted average
106
+ */
107
+ private blendScores;
108
+ /**
109
+ * Get current configuration
110
+ */
111
+ getConfig(): IVerbScoringConfig;
112
+ /**
113
+ * Update configuration
114
+ */
115
+ updateConfig(newConfig: Partial<IVerbScoringConfig>): void;
116
+ /**
117
+ * Get relationship statistics (for debugging/monitoring)
118
+ */
119
+ getRelationshipStats(): Map<string, RelationshipStats>;
120
+ /**
121
+ * Clear relationship statistics
122
+ */
123
+ clearStats(): void;
124
+ /**
125
+ * Provide feedback to improve future scoring
126
+ * This allows the system to learn from user corrections or validation
127
+ *
128
+ * @param sourceId - Source entity ID
129
+ * @param targetId - Target entity ID
130
+ * @param verbType - Relationship type
131
+ * @param feedbackWeight - The corrected/validated weight (0-1)
132
+ * @param feedbackConfidence - The corrected/validated confidence (0-1)
133
+ * @param feedbackType - Type of feedback ('correction', 'validation', 'enhancement')
134
+ */
135
+ provideFeedback(sourceId: string, targetId: string, verbType: string, feedbackWeight: number, feedbackConfidence?: number, feedbackType?: 'correction' | 'validation' | 'enhancement'): Promise<void>;
136
+ /**
137
+ * Get learning statistics for monitoring and debugging
138
+ */
139
+ getLearningStats(): {
140
+ totalRelationships: number;
141
+ averageConfidence: number;
142
+ feedbackCount: number;
143
+ topRelationships: Array<{
144
+ relationship: string;
145
+ count: number;
146
+ averageWeight: number;
147
+ }>;
148
+ };
149
+ /**
150
+ * Export learning data for backup or analysis
151
+ */
152
+ exportLearningData(): string;
153
+ /**
154
+ * Import learning data from backup
155
+ */
156
+ importLearningData(jsonData: string): void;
157
+ }
158
+ export {};