@soulcraft/brainy 0.48.0 → 0.49.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.
Files changed (47) hide show
  1. package/README.md +268 -554
  2. package/dist/brainyData.d.ts +83 -2
  3. package/dist/brainyData.js +536 -66
  4. package/dist/brainyData.js.map +1 -1
  5. package/dist/coreTypes.d.ts +74 -12
  6. package/dist/distributed/configManager.d.ts +9 -0
  7. package/dist/distributed/configManager.js +129 -10
  8. package/dist/distributed/configManager.js.map +1 -1
  9. package/dist/hnsw/hnswIndex.d.ts +1 -1
  10. package/dist/hnsw/hnswIndex.js +44 -25
  11. package/dist/hnsw/hnswIndex.js.map +1 -1
  12. package/dist/hnsw/optimizedHNSWIndex.d.ts +1 -1
  13. package/dist/hnsw/optimizedHNSWIndex.js +3 -3
  14. package/dist/hnsw/optimizedHNSWIndex.js.map +1 -1
  15. package/dist/storage/adapters/baseStorageAdapter.d.ts +18 -2
  16. package/dist/storage/adapters/baseStorageAdapter.js +69 -4
  17. package/dist/storage/adapters/baseStorageAdapter.js.map +1 -1
  18. package/dist/storage/adapters/fileSystemStorage.d.ts +14 -8
  19. package/dist/storage/adapters/fileSystemStorage.js +90 -22
  20. package/dist/storage/adapters/fileSystemStorage.js.map +1 -1
  21. package/dist/storage/adapters/memoryStorage.d.ts +0 -8
  22. package/dist/storage/adapters/memoryStorage.js +26 -45
  23. package/dist/storage/adapters/memoryStorage.js.map +1 -1
  24. package/dist/storage/adapters/opfsStorage.d.ts +40 -8
  25. package/dist/storage/adapters/opfsStorage.js +195 -44
  26. package/dist/storage/adapters/opfsStorage.js.map +1 -1
  27. package/dist/storage/adapters/optimizedS3Search.js +4 -3
  28. package/dist/storage/adapters/optimizedS3Search.js.map +1 -1
  29. package/dist/storage/adapters/s3CompatibleStorage.d.ts +3 -10
  30. package/dist/storage/adapters/s3CompatibleStorage.js +41 -44
  31. package/dist/storage/adapters/s3CompatibleStorage.js.map +1 -1
  32. package/dist/storage/backwardCompatibility.d.ts +84 -0
  33. package/dist/storage/backwardCompatibility.js +141 -0
  34. package/dist/storage/backwardCompatibility.js.map +1 -0
  35. package/dist/storage/baseStorage.d.ts +33 -19
  36. package/dist/storage/baseStorage.js +116 -195
  37. package/dist/storage/baseStorage.js.map +1 -1
  38. package/dist/utils/metadataFilter.d.ts +79 -0
  39. package/dist/utils/metadataFilter.js +229 -0
  40. package/dist/utils/metadataFilter.js.map +1 -0
  41. package/dist/utils/metadataIndex.d.ts +148 -0
  42. package/dist/utils/metadataIndex.js +639 -0
  43. package/dist/utils/metadataIndex.js.map +1 -0
  44. package/dist/utils/metadataIndexCache.d.ts +60 -0
  45. package/dist/utils/metadataIndexCache.js +119 -0
  46. package/dist/utils/metadataIndexCache.js.map +1 -0
  47. package/package.json +1 -1
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Backward Compatibility Layer for Storage Migration
3
+ *
4
+ * Handles the transition from 'index' to '_system' directory
5
+ * Ensures services running different versions can coexist
6
+ */
7
+ import { StatisticsData } from '../coreTypes.js';
8
+ export interface MigrationMetadata {
9
+ schemaVersion: number;
10
+ migrationStarted?: string;
11
+ migrationCompleted?: string;
12
+ lastUpdatedBy?: string;
13
+ }
14
+ /**
15
+ * Backward compatibility strategy for directory migration
16
+ */
17
+ export declare class StorageCompatibilityLayer {
18
+ private migrationMetadata;
19
+ /**
20
+ * Determines the read strategy based on what's available
21
+ * @returns Priority-ordered list of directories to try
22
+ */
23
+ static getReadPriority(): string[];
24
+ /**
25
+ * Determines write strategy based on migration state
26
+ * @param migrationComplete Whether migration is complete
27
+ * @returns List of directories to write to
28
+ */
29
+ static getWriteTargets(migrationComplete?: boolean): string[];
30
+ /**
31
+ * Check if we should perform migration based on service coordination
32
+ * @param existingStats Statistics from storage
33
+ * @returns Whether to initiate migration
34
+ */
35
+ static shouldMigrate(existingStats: StatisticsData | null): boolean;
36
+ /**
37
+ * Creates migration metadata
38
+ */
39
+ static createMigrationMetadata(): MigrationMetadata;
40
+ /**
41
+ * Merge statistics from multiple locations (deduplication)
42
+ */
43
+ static mergeStatistics(primary: StatisticsData | null, fallback: StatisticsData | null): StatisticsData | null;
44
+ /**
45
+ * Determines if dual-write is needed based on environment
46
+ * @param storageType The type of storage being used
47
+ * @returns Whether to write to both old and new locations
48
+ */
49
+ static needsDualWrite(storageType: string): boolean;
50
+ /**
51
+ * Grace period for migration (30 days default)
52
+ * After this period, services can stop reading from old location
53
+ */
54
+ static getMigrationGracePeriodMs(): number;
55
+ /**
56
+ * Check if migration grace period has expired
57
+ */
58
+ static isGracePeriodExpired(migrationStarted: string): boolean;
59
+ /**
60
+ * Log migration events for monitoring
61
+ */
62
+ static logMigrationEvent(event: string, details?: any): void;
63
+ }
64
+ /**
65
+ * Storage paths helper for migration
66
+ */
67
+ export declare class StoragePaths {
68
+ /**
69
+ * Get the statistics file path for a given directory
70
+ */
71
+ static getStatisticsPath(baseDir: string, filename?: string): string;
72
+ /**
73
+ * Get distributed config path
74
+ */
75
+ static getDistributedConfigPath(baseDir: string): string;
76
+ /**
77
+ * Check if a path is using the old structure
78
+ */
79
+ static isLegacyPath(path: string): boolean;
80
+ /**
81
+ * Convert legacy path to new structure
82
+ */
83
+ static modernizePath(path: string): string;
84
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Backward Compatibility Layer for Storage Migration
3
+ *
4
+ * Handles the transition from 'index' to '_system' directory
5
+ * Ensures services running different versions can coexist
6
+ */
7
+ /**
8
+ * Backward compatibility strategy for directory migration
9
+ */
10
+ export class StorageCompatibilityLayer {
11
+ constructor() {
12
+ this.migrationMetadata = null;
13
+ }
14
+ /**
15
+ * Determines the read strategy based on what's available
16
+ * @returns Priority-ordered list of directories to try
17
+ */
18
+ static getReadPriority() {
19
+ return ['_system', 'index']; // Try new location first, fallback to old
20
+ }
21
+ /**
22
+ * Determines write strategy based on migration state
23
+ * @param migrationComplete Whether migration is complete
24
+ * @returns List of directories to write to
25
+ */
26
+ static getWriteTargets(migrationComplete = false) {
27
+ if (migrationComplete) {
28
+ return ['_system']; // Only write to new location
29
+ }
30
+ // During migration, write to both for compatibility
31
+ return ['_system', 'index'];
32
+ }
33
+ /**
34
+ * Check if we should perform migration based on service coordination
35
+ * @param existingStats Statistics from storage
36
+ * @returns Whether to initiate migration
37
+ */
38
+ static shouldMigrate(existingStats) {
39
+ if (!existingStats)
40
+ return true; // No data yet, use new structure
41
+ // Check if we have migration metadata in stats
42
+ const migrationData = existingStats.migrationMetadata;
43
+ if (!migrationData)
44
+ return true; // No migration data, start migration
45
+ // Check schema version
46
+ if (migrationData.schemaVersion < 2)
47
+ return true;
48
+ // Already migrated
49
+ return false;
50
+ }
51
+ /**
52
+ * Creates migration metadata
53
+ */
54
+ static createMigrationMetadata() {
55
+ return {
56
+ schemaVersion: 2,
57
+ migrationStarted: new Date().toISOString(),
58
+ lastUpdatedBy: process.env.HOSTNAME || process.env.INSTANCE_ID || 'unknown'
59
+ };
60
+ }
61
+ /**
62
+ * Merge statistics from multiple locations (deduplication)
63
+ */
64
+ static mergeStatistics(primary, fallback) {
65
+ if (!primary && !fallback)
66
+ return null;
67
+ if (!fallback)
68
+ return primary;
69
+ if (!primary)
70
+ return fallback;
71
+ // Return the most recently updated
72
+ const primaryTime = new Date(primary.lastUpdated).getTime();
73
+ const fallbackTime = new Date(fallback.lastUpdated).getTime();
74
+ return primaryTime >= fallbackTime ? primary : fallback;
75
+ }
76
+ /**
77
+ * Determines if dual-write is needed based on environment
78
+ * @param storageType The type of storage being used
79
+ * @returns Whether to write to both old and new locations
80
+ */
81
+ static needsDualWrite(storageType) {
82
+ // Only need dual-write for shared storage systems
83
+ const sharedStorageTypes = ['s3', 'r2', 'gcs', 'filesystem'];
84
+ return sharedStorageTypes.includes(storageType.toLowerCase());
85
+ }
86
+ /**
87
+ * Grace period for migration (30 days default)
88
+ * After this period, services can stop reading from old location
89
+ */
90
+ static getMigrationGracePeriodMs() {
91
+ const days = parseInt(process.env.BRAINY_MIGRATION_GRACE_DAYS || '30', 10);
92
+ return days * 24 * 60 * 60 * 1000;
93
+ }
94
+ /**
95
+ * Check if migration grace period has expired
96
+ */
97
+ static isGracePeriodExpired(migrationStarted) {
98
+ const startTime = new Date(migrationStarted).getTime();
99
+ const now = Date.now();
100
+ const gracePeriod = this.getMigrationGracePeriodMs();
101
+ return (now - startTime) > gracePeriod;
102
+ }
103
+ /**
104
+ * Log migration events for monitoring
105
+ */
106
+ static logMigrationEvent(event, details) {
107
+ if (process.env.NODE_ENV !== 'test') {
108
+ console.log(`[Brainy Storage Migration] ${event}`, details || '');
109
+ }
110
+ }
111
+ }
112
+ /**
113
+ * Storage paths helper for migration
114
+ */
115
+ export class StoragePaths {
116
+ /**
117
+ * Get the statistics file path for a given directory
118
+ */
119
+ static getStatisticsPath(baseDir, filename = 'statistics') {
120
+ return `${baseDir}/${filename}.json`;
121
+ }
122
+ /**
123
+ * Get distributed config path
124
+ */
125
+ static getDistributedConfigPath(baseDir) {
126
+ return `${baseDir}/distributed_config.json`;
127
+ }
128
+ /**
129
+ * Check if a path is using the old structure
130
+ */
131
+ static isLegacyPath(path) {
132
+ return path.includes('/index/') || path.endsWith('/index');
133
+ }
134
+ /**
135
+ * Convert legacy path to new structure
136
+ */
137
+ static modernizePath(path) {
138
+ return path.replace('/index/', '/_system/').replace('/index', '/_system');
139
+ }
140
+ }
141
+ //# sourceMappingURL=backwardCompatibility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backwardCompatibility.js","sourceRoot":"","sources":["../../src/storage/backwardCompatibility.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH;;GAEG;AACH,MAAM,OAAO,yBAAyB;IAAtC;QACU,sBAAiB,GAA6B,IAAI,CAAA;IA8G5D,CAAC;IA5GC;;;OAGG;IACH,MAAM,CAAC,eAAe;QACpB,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA,CAAE,0CAA0C;IACzE,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,eAAe,CAAC,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,WAAmB,YAAY;QACvE,OAAO,GAAG,OAAO,IAAI,QAAQ,OAAO,CAAA;IACtC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,wBAAwB,CAAC,OAAe;QAC7C,OAAO,GAAG,OAAO,0BAA0B,CAAA;IAC7C,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,IAAY;QAC9B,OAAO,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;IAC5D,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,aAAa,CAAC,IAAY;QAC/B,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAC3E,CAAC;CACF"}
@@ -4,13 +4,27 @@
4
4
  */
5
5
  import { GraphVerb, HNSWNoun, HNSWVerb, StatisticsData } from '../coreTypes.js';
6
6
  import { BaseStorageAdapter } from './adapters/baseStorageAdapter.js';
7
+ export declare const ENTITIES_DIR = "entities";
8
+ export declare const NOUNS_VECTOR_DIR = "entities/nouns/vectors";
9
+ export declare const NOUNS_METADATA_DIR = "entities/nouns/metadata";
10
+ export declare const VERBS_VECTOR_DIR = "entities/verbs/vectors";
11
+ export declare const VERBS_METADATA_DIR = "entities/verbs/metadata";
12
+ export declare const INDEXES_DIR = "indexes";
13
+ export declare const METADATA_INDEX_DIR = "indexes/metadata";
7
14
  export declare const NOUNS_DIR = "nouns";
8
15
  export declare const VERBS_DIR = "verbs";
9
16
  export declare const METADATA_DIR = "metadata";
10
17
  export declare const NOUN_METADATA_DIR = "noun-metadata";
11
18
  export declare const VERB_METADATA_DIR = "verb-metadata";
12
19
  export declare const INDEX_DIR = "index";
20
+ export declare const SYSTEM_DIR = "_system";
13
21
  export declare const STATISTICS_KEY = "statistics";
22
+ export declare const STORAGE_SCHEMA_VERSION = 3;
23
+ export declare const USE_ENTITY_BASED_STRUCTURE = true;
24
+ /**
25
+ * Get the appropriate directory path based on configuration
26
+ */
27
+ export declare function getDirectoryPath(entityType: 'noun' | 'verb', dataType: 'vector' | 'metadata'): string;
14
28
  /**
15
29
  * Base storage adapter that implements common functionality
16
30
  * This is an abstract class that should be extended by specific storage adapters
@@ -35,12 +49,6 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
35
49
  * Get a noun from storage
36
50
  */
37
51
  getNoun(id: string): Promise<HNSWNoun | null>;
38
- /**
39
- * Get all nouns from storage
40
- * @deprecated This method is deprecated and will be removed in a future version.
41
- * It can cause memory issues with large datasets. Use getNouns() with pagination instead.
42
- */
43
- getAllNouns(): Promise<HNSWNoun[]>;
44
52
  /**
45
53
  * Get nouns by noun type
46
54
  * @param nounType The noun type to filter by
@@ -65,10 +73,10 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
65
73
  protected convertHNSWVerbToGraphVerb(hnswVerb: HNSWVerb): Promise<GraphVerb | null>;
66
74
  /**
67
75
  * Get all verbs from storage
68
- * @deprecated This method is deprecated and will be removed in a future version.
69
- * It can cause memory issues with large datasets. Use getVerbs() with pagination instead.
76
+ * @returns Promise that resolves to an array of all HNSWVerbs
77
+ * @deprecated This method loads all data into memory and may cause performance issues. Use getVerbs() with pagination instead.
70
78
  */
71
- getAllVerbs(): Promise<GraphVerb[]>;
79
+ getAllVerbs(): Promise<HNSWVerb[]>;
72
80
  /**
73
81
  * Get verbs by source
74
82
  */
@@ -81,6 +89,12 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
81
89
  * Get verbs by type
82
90
  */
83
91
  getVerbsByType(type: string): Promise<GraphVerb[]>;
92
+ /**
93
+ * Get all nouns from storage
94
+ * @returns Promise that resolves to an array of all nouns
95
+ * @deprecated This method loads all data into memory and may cause performance issues. Use getNouns() with pagination instead.
96
+ */
97
+ getAllNouns(): Promise<HNSWNoun[]>;
84
98
  /**
85
99
  * Get nouns with pagination and filtering
86
100
  * @param options Pagination and filtering options
@@ -186,11 +200,6 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
186
200
  * This method should be implemented by each specific adapter
187
201
  */
188
202
  protected abstract getNoun_internal(id: string): Promise<HNSWNoun | null>;
189
- /**
190
- * Get all nouns from storage
191
- * This method should be implemented by each specific adapter
192
- */
193
- protected abstract getAllNouns_internal(): Promise<HNSWNoun[]>;
194
203
  /**
195
204
  * Get nouns by noun type
196
205
  * This method should be implemented by each specific adapter
@@ -211,11 +220,6 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
211
220
  * This method should be implemented by each specific adapter
212
221
  */
213
222
  protected abstract getVerb_internal(id: string): Promise<HNSWVerb | null>;
214
- /**
215
- * Get all verbs from storage
216
- * This method should be implemented by each specific adapter
217
- */
218
- protected abstract getAllVerbs_internal(): Promise<HNSWVerb[]>;
219
223
  /**
220
224
  * Get verbs by source
221
225
  * This method should be implemented by each specific adapter
@@ -240,6 +244,16 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
240
244
  * Helper method to convert a Map to a plain object for serialization
241
245
  */
242
246
  protected mapToObject<K extends string | number, V>(map: Map<K, V>, valueTransformer?: (value: V) => any): Record<string, any>;
247
+ /**
248
+ * Save statistics data to storage (public interface)
249
+ * @param statistics The statistics data to save
250
+ */
251
+ saveStatistics(statistics: StatisticsData): Promise<void>;
252
+ /**
253
+ * Get statistics data from storage (public interface)
254
+ * @returns Promise that resolves to the statistics data or null if not found
255
+ */
256
+ getStatistics(): Promise<StatisticsData | null>;
243
257
  /**
244
258
  * Save statistics data to storage
245
259
  * This method should be implemented by each specific adapter