@soulcraft/brainy 6.2.2 → 6.2.4

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 (31) hide show
  1. package/dist/augmentations/KnowledgeAugmentation.d.ts +40 -0
  2. package/dist/augmentations/KnowledgeAugmentation.js +251 -0
  3. package/dist/importManager.d.ts +78 -0
  4. package/dist/importManager.js +267 -0
  5. package/dist/query/typeInference.d.ts +158 -0
  6. package/dist/query/typeInference.js +760 -0
  7. package/dist/storage/adapters/historicalStorageAdapter.d.ts +0 -2
  8. package/dist/storage/adapters/historicalStorageAdapter.js +4 -4
  9. package/dist/storage/adapters/typeAwareStorageAdapter.d.ts +252 -0
  10. package/dist/storage/adapters/typeAwareStorageAdapter.js +814 -0
  11. package/dist/storage/baseStorage.d.ts +12 -0
  12. package/dist/storage/baseStorage.js +16 -0
  13. package/dist/types/brainyDataInterface.d.ts +52 -0
  14. package/dist/types/brainyDataInterface.js +10 -0
  15. package/dist/utils/metadataIndex.d.ts +6 -2
  16. package/dist/utils/metadataIndex.js +31 -14
  17. package/dist/vfs/ConceptSystem.d.ts +203 -0
  18. package/dist/vfs/ConceptSystem.js +545 -0
  19. package/dist/vfs/EntityManager.d.ts +75 -0
  20. package/dist/vfs/EntityManager.js +216 -0
  21. package/dist/vfs/EventRecorder.d.ts +84 -0
  22. package/dist/vfs/EventRecorder.js +269 -0
  23. package/dist/vfs/GitBridge.d.ts +167 -0
  24. package/dist/vfs/GitBridge.js +537 -0
  25. package/dist/vfs/KnowledgeLayer.d.ts +35 -0
  26. package/dist/vfs/KnowledgeLayer.js +443 -0
  27. package/dist/vfs/PersistentEntitySystem.d.ts +165 -0
  28. package/dist/vfs/PersistentEntitySystem.js +503 -0
  29. package/dist/vfs/SemanticVersioning.d.ts +105 -0
  30. package/dist/vfs/SemanticVersioning.js +309 -0
  31. package/package.json +1 -1
@@ -618,6 +618,18 @@ export declare abstract class BaseStorage extends BaseStorageAdapter {
618
618
  * Periodically called when counts are updated
619
619
  */
620
620
  protected saveTypeStatistics(): Promise<void>;
621
+ /**
622
+ * Get noun counts by type (O(1) access to type statistics)
623
+ * v6.2.2: Exposed for MetadataIndexManager to use as single source of truth
624
+ * @returns Uint32Array indexed by NounType enum value (42 types)
625
+ */
626
+ getNounCountsByType(): Uint32Array;
627
+ /**
628
+ * Get verb counts by type (O(1) access to type statistics)
629
+ * v6.2.2: Exposed for MetadataIndexManager to use as single source of truth
630
+ * @returns Uint32Array indexed by VerbType enum value (127 types)
631
+ */
632
+ getVerbCountsByType(): Uint32Array;
621
633
  /**
622
634
  * Rebuild type counts from actual storage (v5.5.0)
623
635
  * Called when statistics are missing or inconsistent
@@ -1983,6 +1983,22 @@ export class BaseStorage extends BaseStorageAdapter {
1983
1983
  };
1984
1984
  await this.writeObjectToPath(`${SYSTEM_DIR}/type-statistics.json`, stats);
1985
1985
  }
1986
+ /**
1987
+ * Get noun counts by type (O(1) access to type statistics)
1988
+ * v6.2.2: Exposed for MetadataIndexManager to use as single source of truth
1989
+ * @returns Uint32Array indexed by NounType enum value (42 types)
1990
+ */
1991
+ getNounCountsByType() {
1992
+ return this.nounCountsByType;
1993
+ }
1994
+ /**
1995
+ * Get verb counts by type (O(1) access to type statistics)
1996
+ * v6.2.2: Exposed for MetadataIndexManager to use as single source of truth
1997
+ * @returns Uint32Array indexed by VerbType enum value (127 types)
1998
+ */
1999
+ getVerbCountsByType() {
2000
+ return this.verbCountsByType;
2001
+ }
1986
2002
  /**
1987
2003
  * Rebuild type counts from actual storage (v5.5.0)
1988
2004
  * Called when statistics are missing or inconsistent
@@ -0,0 +1,52 @@
1
+ /**
2
+ * BrainyInterface - Modern API Only
3
+ *
4
+ * This interface defines the MODERN methods from Brainy 3.0.
5
+ * Used to break circular dependencies while enforcing modern API usage.
6
+ *
7
+ * NO DEPRECATED METHODS - Only clean, modern API patterns.
8
+ */
9
+ import { Vector } from '../coreTypes.js';
10
+ import { AddParams, RelateParams, Result, Entity, FindParams, SimilarParams } from './brainy.types.js';
11
+ export interface BrainyInterface<T = unknown> {
12
+ /**
13
+ * Initialize the database
14
+ */
15
+ init(): Promise<void>;
16
+ /**
17
+ * Modern add method - unified entity creation
18
+ * @param params Parameters for adding entities
19
+ * @returns The ID of the created entity
20
+ */
21
+ add(params: AddParams<T>): Promise<string>;
22
+ /**
23
+ * Modern relate method - unified relationship creation
24
+ * @param params Parameters for creating relationships
25
+ * @returns The ID of the created relationship
26
+ */
27
+ relate(params: RelateParams<T>): Promise<string>;
28
+ /**
29
+ * Modern find method - unified search and discovery
30
+ * @param query Search query or parameters object
31
+ * @returns Array of search results
32
+ */
33
+ find(query: string | FindParams<T>): Promise<Result<T>[]>;
34
+ /**
35
+ * Modern get method - retrieve entities by ID
36
+ * @param id The entity ID to retrieve
37
+ * @returns Entity or null if not found
38
+ */
39
+ get(id: string): Promise<Entity<T> | null>;
40
+ /**
41
+ * Modern similar method - find similar entities
42
+ * @param params Parameters for similarity search
43
+ * @returns Array of similar entities with scores
44
+ */
45
+ similar(params: SimilarParams<T>): Promise<Result<T>[]>;
46
+ /**
47
+ * Generate embedding vector from text
48
+ * @param text The text to embed
49
+ * @returns Vector representation of the text
50
+ */
51
+ embed(text: string): Promise<Vector>;
52
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * BrainyInterface - Modern API Only
3
+ *
4
+ * This interface defines the MODERN methods from Brainy 3.0.
5
+ * Used to break circular dependencies while enforcing modern API usage.
6
+ *
7
+ * NO DEPRECATED METHODS - Only clean, modern API patterns.
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=brainyDataInterface.js.map
@@ -112,8 +112,9 @@ export declare class MetadataIndexManager {
112
112
  */
113
113
  private releaseLock;
114
114
  /**
115
- * Lazy load entity counts from storage statistics (O(1) operation)
116
- * This avoids rebuilding the entire index on startup
115
+ * Lazy load entity counts from the 'noun' field sparse index (O(n) where n = number of types)
116
+ * v6.2.2 FIX: Previously read from stats.nounCount which was SERVICE-keyed, not TYPE-keyed
117
+ * Now computes counts from the sparse index which has the correct type information
117
118
  */
118
119
  private lazyLoadCounts;
119
120
  /**
@@ -434,6 +435,9 @@ export declare class MetadataIndexManager {
434
435
  getTotalEntityCount(): number;
435
436
  /**
436
437
  * Get all entity types and their counts - O(1) operation
438
+ * v6.2.2: Fixed - totalEntitiesByType is correctly populated by updateTypeFieldAffinity
439
+ * during add operations. lazyLoadCounts was reading wrong data but that doesn't
440
+ * affect freshly-added entities within the same session.
437
441
  */
438
442
  getAllEntityCounts(): Map<string, number>;
439
443
  /**
@@ -84,8 +84,9 @@ export class MetadataIndexManager {
84
84
  this.chunkingStrategy = new AdaptiveChunkingStrategy();
85
85
  // Initialize Field Type Inference (v3.48.0)
86
86
  this.fieldTypeInference = new FieldTypeInference(storage);
87
- // Lazy load counts from storage statistics on first access
88
- this.lazyLoadCounts();
87
+ // v6.2.2: Removed lazyLoadCounts() call from constructor
88
+ // It was a race condition (not awaited) and read from wrong source.
89
+ // Now properly called in init() after warmCache() loads the sparse index.
89
90
  }
90
91
  /**
91
92
  * Initialize the metadata index manager
@@ -97,11 +98,15 @@ export class MetadataIndexManager {
97
98
  await this.loadFieldRegistry();
98
99
  // Initialize EntityIdMapper (loads UUID ↔ integer mappings from storage)
99
100
  await this.idMapper.init();
100
- // Phase 1b: Sync loaded counts to fixed-size arrays
101
- // This populates the Uint32Arrays from the Maps loaded by lazyLoadCounts()
102
- this.syncTypeCountsToFixed();
103
101
  // Warm the cache with common fields (v3.44.1 - lazy loading optimization)
102
+ // This loads the 'noun' sparse index which is needed for type counts
104
103
  await this.warmCache();
104
+ // v6.2.2: Load type counts AFTER warmCache (sparse index is now cached)
105
+ // Previously called in constructor without await and read from wrong source
106
+ await this.lazyLoadCounts();
107
+ // Phase 1b: Sync loaded counts to fixed-size arrays
108
+ // Now correctly happens AFTER lazyLoadCounts() finishes
109
+ this.syncTypeCountsToFixed();
105
110
  }
106
111
  /**
107
112
  * Warm the cache by preloading common field sparse indices (v3.44.1)
@@ -226,25 +231,34 @@ export class MetadataIndexManager {
226
231
  this.activeLocks.delete(lockKey);
227
232
  }
228
233
  /**
229
- * Lazy load entity counts from storage statistics (O(1) operation)
230
- * This avoids rebuilding the entire index on startup
234
+ * Lazy load entity counts from the 'noun' field sparse index (O(n) where n = number of types)
235
+ * v6.2.2 FIX: Previously read from stats.nounCount which was SERVICE-keyed, not TYPE-keyed
236
+ * Now computes counts from the sparse index which has the correct type information
231
237
  */
232
238
  async lazyLoadCounts() {
233
239
  try {
234
- // Get statistics from storage (should be O(1) with our FileSystemStorage improvements)
235
- const stats = await this.storage.getStatistics();
236
- if (stats && stats.nounCount) {
237
- // Populate entity counts from storage statistics
238
- for (const [type, count] of Object.entries(stats.nounCount)) {
239
- if (typeof count === 'number' && count > 0) {
240
- this.totalEntitiesByType.set(type, count);
240
+ // v6.2.2: Load counts from sparse index (correct source)
241
+ const nounSparseIndex = await this.loadSparseIndex('noun');
242
+ if (!nounSparseIndex) {
243
+ // No sparse index yet - counts will be populated as entities are added
244
+ return;
245
+ }
246
+ // Iterate through all chunks and sum up bitmap sizes by type
247
+ for (const chunkId of nounSparseIndex.getAllChunkIds()) {
248
+ const chunk = await this.chunkManager.loadChunk('noun', chunkId);
249
+ if (chunk) {
250
+ for (const [type, bitmap] of chunk.entries) {
251
+ const currentCount = this.totalEntitiesByType.get(type) || 0;
252
+ this.totalEntitiesByType.set(type, currentCount + bitmap.size);
241
253
  }
242
254
  }
243
255
  }
256
+ prodLog.debug(`✅ Loaded type counts from sparse index: ${this.totalEntitiesByType.size} types`);
244
257
  }
245
258
  catch (error) {
246
259
  // Silently fail - counts will be populated as entities are added
247
260
  // This maintains zero-configuration principle
261
+ prodLog.debug('Could not load type counts from sparse index:', error);
248
262
  }
249
263
  }
250
264
  /**
@@ -1875,6 +1889,9 @@ export class MetadataIndexManager {
1875
1889
  }
1876
1890
  /**
1877
1891
  * Get all entity types and their counts - O(1) operation
1892
+ * v6.2.2: Fixed - totalEntitiesByType is correctly populated by updateTypeFieldAffinity
1893
+ * during add operations. lazyLoadCounts was reading wrong data but that doesn't
1894
+ * affect freshly-added entities within the same session.
1878
1895
  */
1879
1896
  getAllEntityCounts() {
1880
1897
  return new Map(this.totalEntitiesByType);
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Universal Concept System for VFS
3
+ *
4
+ * Manages concepts that transcend files and exist independently
5
+ * Ideas that can be linked to multiple manifestations across domains
6
+ * PRODUCTION-READY: Real implementation using Brainy
7
+ */
8
+ import { Brainy } from '../brainy.js';
9
+ import { EntityManager, ManagedEntity } from './EntityManager.js';
10
+ /**
11
+ * Universal concept that exists independently of files
12
+ */
13
+ export interface UniversalConcept extends ManagedEntity {
14
+ id: string;
15
+ name: string;
16
+ description?: string;
17
+ domain: string;
18
+ category: string;
19
+ keywords: string[];
20
+ links: ConceptLink[];
21
+ manifestations: ConceptManifestation[];
22
+ strength: number;
23
+ created: number;
24
+ lastUpdated: number;
25
+ version: number;
26
+ metadata: Record<string, any>;
27
+ conceptType?: string;
28
+ }
29
+ /**
30
+ * A link between concepts
31
+ */
32
+ export interface ConceptLink {
33
+ id: string;
34
+ targetConceptId: string;
35
+ relationship: 'extends' | 'implements' | 'uses' | 'opposite' | 'related' | 'contains' | 'part-of';
36
+ strength: number;
37
+ context?: string;
38
+ bidirectional: boolean;
39
+ }
40
+ /**
41
+ * A manifestation of a concept in a specific location
42
+ */
43
+ export interface ConceptManifestation extends ManagedEntity {
44
+ id: string;
45
+ conceptId: string;
46
+ filePath: string;
47
+ context: string;
48
+ form: 'definition' | 'usage' | 'example' | 'discussion' | 'implementation';
49
+ position?: {
50
+ line?: number;
51
+ column?: number;
52
+ offset?: number;
53
+ };
54
+ confidence: number;
55
+ timestamp: number;
56
+ extractedBy: 'manual' | 'auto' | 'ai';
57
+ }
58
+ /**
59
+ * Configuration for concept system
60
+ */
61
+ export interface ConceptSystemConfig {
62
+ autoLink?: boolean;
63
+ similarityThreshold?: number;
64
+ maxManifestations?: number;
65
+ strengthDecay?: number;
66
+ }
67
+ /**
68
+ * Concept graph structure for visualization
69
+ */
70
+ export interface ConceptGraph {
71
+ concepts: Array<{
72
+ id: string;
73
+ name: string;
74
+ domain: string;
75
+ strength: number;
76
+ manifestationCount: number;
77
+ }>;
78
+ links: Array<{
79
+ source: string;
80
+ target: string;
81
+ relationship: string;
82
+ strength: number;
83
+ }>;
84
+ }
85
+ /**
86
+ * Universal Concept System
87
+ *
88
+ * Manages concepts that exist independently of any specific file or context
89
+ * Examples:
90
+ * - "Authentication" concept appearing in docs, code, tests
91
+ * - "Customer Journey" concept in marketing, UX, analytics
92
+ * - "Dependency Injection" pattern across multiple codebases
93
+ * - "Sustainability" theme in various research papers
94
+ */
95
+ export declare class ConceptSystem extends EntityManager {
96
+ private config;
97
+ private conceptCache;
98
+ constructor(brain: Brainy, config?: ConceptSystemConfig);
99
+ /**
100
+ * Create a new universal concept
101
+ */
102
+ createConcept(concept: Omit<UniversalConcept, 'id' | 'created' | 'lastUpdated' | 'version' | 'links' | 'manifestations'>): Promise<string>;
103
+ /**
104
+ * Find concepts by various criteria
105
+ */
106
+ findConcepts(query: {
107
+ name?: string;
108
+ domain?: string;
109
+ category?: string;
110
+ keywords?: string[];
111
+ similar?: string;
112
+ manifestedIn?: string;
113
+ }): Promise<UniversalConcept[]>;
114
+ /**
115
+ * Link two concepts together
116
+ */
117
+ linkConcept(fromConceptId: string, toConceptId: string, relationship: ConceptLink['relationship'], options?: {
118
+ strength?: number;
119
+ context?: string;
120
+ bidirectional?: boolean;
121
+ }): Promise<string>;
122
+ /**
123
+ * Record a manifestation of a concept in a file
124
+ */
125
+ recordManifestation(conceptId: string, filePath: string, context: string, form: ConceptManifestation['form'], options?: {
126
+ position?: ConceptManifestation['position'];
127
+ confidence?: number;
128
+ extractedBy?: ConceptManifestation['extractedBy'];
129
+ }): Promise<string>;
130
+ /**
131
+ * Extract and link concepts from content
132
+ */
133
+ extractAndLinkConcepts(filePath: string, content: Buffer): Promise<string[]>;
134
+ /**
135
+ * Get concept graph for visualization
136
+ */
137
+ getConceptGraph(options?: {
138
+ domain?: string;
139
+ minStrength?: number;
140
+ maxConcepts?: number;
141
+ }): Promise<ConceptGraph>;
142
+ /**
143
+ * Find appearances of a concept
144
+ */
145
+ findAppearances(conceptId: string, options?: {
146
+ filePath?: string;
147
+ form?: ConceptManifestation['form'];
148
+ minConfidence?: number;
149
+ limit?: number;
150
+ }): Promise<ConceptManifestation[]>;
151
+ /**
152
+ * Auto-link concept to similar concepts
153
+ */
154
+ private autoLinkConcept;
155
+ /**
156
+ * Get concept by ID
157
+ */
158
+ private getConcept;
159
+ /**
160
+ * Update stored concept
161
+ */
162
+ private updateConcept;
163
+ /**
164
+ * Calculate similarity between two concepts
165
+ */
166
+ private calculateConceptSimilarity;
167
+ /**
168
+ * Generate embedding for concept
169
+ */
170
+ private generateConceptEmbedding;
171
+ /**
172
+ * Generate embedding for text
173
+ */
174
+ private generateTextEmbedding;
175
+ /**
176
+ * Get reverse relationship type
177
+ */
178
+ private getReverseRelationship;
179
+ /**
180
+ * Map concept relationship to VerbType
181
+ */
182
+ private getVerbType;
183
+ /**
184
+ * Detect concept domain from context
185
+ */
186
+ private detectDomain;
187
+ /**
188
+ * Detect concept category
189
+ */
190
+ private detectCategory;
191
+ /**
192
+ * Detect manifestation form from context
193
+ */
194
+ private detectManifestationForm;
195
+ /**
196
+ * Extract context around a position
197
+ */
198
+ private extractContext;
199
+ /**
200
+ * Clear concept cache
201
+ */
202
+ clearCache(conceptId?: string): void;
203
+ }