@soulcraft/brainy 3.44.0 → 3.45.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,40 @@
1
+ /**
2
+ * Knowledge Layer Augmentation for VFS
3
+ *
4
+ * Adds intelligent features to VFS without modifying core functionality:
5
+ * - Event recording for all operations
6
+ * - Semantic versioning based on content changes
7
+ * - Entity and concept extraction
8
+ * - Git bridge for import/export
9
+ *
10
+ * This is a TRUE augmentation - VFS works perfectly without it
11
+ */
12
+ import { Brainy } from '../brainy.js';
13
+ import { BaseAugmentation } from './brainyAugmentation.js';
14
+ export declare class KnowledgeAugmentation extends BaseAugmentation {
15
+ name: string;
16
+ timing: 'after';
17
+ metadata: 'none';
18
+ operations: any;
19
+ priority: number;
20
+ constructor(config?: any);
21
+ execute<T = any>(operation: string, params: any, next: () => Promise<T>): Promise<T>;
22
+ private eventRecorder?;
23
+ private semanticVersioning?;
24
+ private entitySystem?;
25
+ private conceptSystem?;
26
+ private gitBridge?;
27
+ private originalMethods;
28
+ initialize(context: any): Promise<void>;
29
+ augment(brain: Brainy): Promise<void>;
30
+ /**
31
+ * Wrap a VFS method to add Knowledge Layer functionality
32
+ */
33
+ private wrapMethod;
34
+ /**
35
+ * Add Knowledge Layer methods to VFS
36
+ */
37
+ private addKnowledgeMethods;
38
+ private isSemanticChange;
39
+ cleanup(brain: Brainy): Promise<void>;
40
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Knowledge Layer Augmentation for VFS
3
+ *
4
+ * Adds intelligent features to VFS without modifying core functionality:
5
+ * - Event recording for all operations
6
+ * - Semantic versioning based on content changes
7
+ * - Entity and concept extraction
8
+ * - Git bridge for import/export
9
+ *
10
+ * This is a TRUE augmentation - VFS works perfectly without it
11
+ */
12
+ import { BaseAugmentation } from './brainyAugmentation.js';
13
+ import { EventRecorder } from '../vfs/EventRecorder.js';
14
+ import { SemanticVersioning } from '../vfs/SemanticVersioning.js';
15
+ import { PersistentEntitySystem } from '../vfs/PersistentEntitySystem.js';
16
+ import { ConceptSystem } from '../vfs/ConceptSystem.js';
17
+ import { GitBridge } from '../vfs/GitBridge.js';
18
+ export class KnowledgeAugmentation extends BaseAugmentation {
19
+ constructor(config = {}) {
20
+ super(config);
21
+ this.name = 'knowledge';
22
+ this.timing = 'after'; // Process after VFS operations
23
+ this.metadata = 'none'; // No metadata access needed
24
+ this.operations = []; // VFS-specific augmentation, no operation interception
25
+ this.priority = 100; // Run last
26
+ this.originalMethods = new Map();
27
+ }
28
+ async execute(operation, params, next) {
29
+ // Pass through - this augmentation works at VFS level, not operation level
30
+ return await next();
31
+ }
32
+ async initialize(context) {
33
+ await this.augment(context.brain);
34
+ }
35
+ async augment(brain) {
36
+ // Only augment if VFS exists
37
+ const vfs = brain.vfs?.();
38
+ if (!vfs) {
39
+ console.warn('KnowledgeAugmentation: VFS not found, skipping');
40
+ return;
41
+ }
42
+ // Initialize Knowledge Layer components
43
+ this.eventRecorder = new EventRecorder(brain);
44
+ this.semanticVersioning = new SemanticVersioning(brain);
45
+ this.entitySystem = new PersistentEntitySystem(brain);
46
+ this.conceptSystem = new ConceptSystem(brain);
47
+ this.gitBridge = new GitBridge(vfs, brain);
48
+ // Wrap VFS methods to add intelligence WITHOUT slowing them down
49
+ this.wrapMethod(vfs, 'writeFile', async (original, path, data, options) => {
50
+ // Call original first (stays fast)
51
+ const result = await original.call(vfs, path, data, options);
52
+ // Knowledge processing in background (non-blocking)
53
+ setImmediate(async () => {
54
+ try {
55
+ // Record event
56
+ if (this.eventRecorder) {
57
+ await this.eventRecorder.recordEvent({
58
+ type: 'write',
59
+ path,
60
+ content: data,
61
+ size: data.length,
62
+ author: options?.author || 'system'
63
+ });
64
+ }
65
+ // Check for semantic versioning
66
+ if (this.semanticVersioning) {
67
+ const existingContent = await vfs.readFile(path).catch(() => null);
68
+ const shouldVersion = existingContent && this.isSemanticChange(existingContent, data);
69
+ if (shouldVersion) {
70
+ await this.semanticVersioning.createVersion(path, data, {
71
+ message: 'Automatic semantic version'
72
+ });
73
+ }
74
+ }
75
+ // Extract concepts
76
+ if (this.conceptSystem && options?.extractConcepts !== false) {
77
+ await this.conceptSystem.extractAndLinkConcepts(path, data);
78
+ }
79
+ // Extract entities
80
+ if (this.entitySystem && options?.extractEntities !== false) {
81
+ await this.entitySystem.extractEntities(data.toString('utf8'), data);
82
+ }
83
+ }
84
+ catch (error) {
85
+ // Knowledge Layer errors should not affect VFS operations
86
+ console.debug('KnowledgeLayer background processing error:', error);
87
+ }
88
+ });
89
+ return result;
90
+ });
91
+ this.wrapMethod(vfs, 'unlink', async (original, path) => {
92
+ const result = await original.call(vfs, path);
93
+ // Record deletion event
94
+ setImmediate(async () => {
95
+ if (this.eventRecorder) {
96
+ await this.eventRecorder.recordEvent({
97
+ type: 'delete',
98
+ path,
99
+ author: 'system'
100
+ });
101
+ }
102
+ });
103
+ return result;
104
+ });
105
+ this.wrapMethod(vfs, 'rename', async (original, oldPath, newPath) => {
106
+ const result = await original.call(vfs, oldPath, newPath);
107
+ // Record rename event
108
+ setImmediate(async () => {
109
+ if (this.eventRecorder) {
110
+ await this.eventRecorder.recordEvent({
111
+ type: 'rename',
112
+ path: oldPath,
113
+ metadata: { newPath },
114
+ author: 'system'
115
+ });
116
+ }
117
+ });
118
+ return result;
119
+ });
120
+ // Add Knowledge Layer methods to VFS
121
+ this.addKnowledgeMethods(vfs);
122
+ console.log('✨ Knowledge Layer augmentation enabled');
123
+ }
124
+ /**
125
+ * Wrap a VFS method to add Knowledge Layer functionality
126
+ */
127
+ wrapMethod(vfs, methodName, wrapper) {
128
+ const original = vfs[methodName];
129
+ if (!original)
130
+ return;
131
+ // Store original for cleanup
132
+ this.originalMethods.set(methodName, original);
133
+ // Replace with wrapped version
134
+ vfs[methodName] = async (...args) => {
135
+ return await wrapper(original, ...args);
136
+ };
137
+ }
138
+ /**
139
+ * Add Knowledge Layer methods to VFS
140
+ */
141
+ addKnowledgeMethods(vfs) {
142
+ // Event history
143
+ vfs.getHistory = async (path, options) => {
144
+ if (!this.eventRecorder)
145
+ throw new Error('Knowledge Layer not initialized');
146
+ return await this.eventRecorder.getHistory(path, options);
147
+ };
148
+ vfs.reconstructAtTime = async (path, timestamp) => {
149
+ if (!this.eventRecorder)
150
+ throw new Error('Knowledge Layer not initialized');
151
+ return await this.eventRecorder.reconstructFileAtTime(path, timestamp);
152
+ };
153
+ // Semantic versioning
154
+ vfs.getVersions = async (path) => {
155
+ if (!this.semanticVersioning)
156
+ throw new Error('Knowledge Layer not initialized');
157
+ return await this.semanticVersioning.getVersions(path);
158
+ };
159
+ vfs.restoreVersion = async (path, versionId) => {
160
+ if (!this.semanticVersioning)
161
+ throw new Error('Knowledge Layer not initialized');
162
+ const version = await this.semanticVersioning.getVersion(path, versionId);
163
+ if (version) {
164
+ await vfs.writeFile(path, version);
165
+ }
166
+ };
167
+ // Entities
168
+ vfs.findEntity = async (query) => {
169
+ if (!this.entitySystem)
170
+ throw new Error('Knowledge Layer not initialized');
171
+ return await this.entitySystem.findEntity(query);
172
+ };
173
+ vfs.getEntityAppearances = async (entityId) => {
174
+ if (!this.entitySystem)
175
+ throw new Error('Knowledge Layer not initialized');
176
+ return await this.entitySystem.getEvolution(entityId);
177
+ };
178
+ // Concepts
179
+ vfs.getConcepts = async (path) => {
180
+ if (!this.conceptSystem)
181
+ throw new Error('Knowledge Layer not initialized');
182
+ const concepts = await this.conceptSystem.findConcepts({ manifestedIn: path });
183
+ return concepts;
184
+ };
185
+ vfs.getConceptGraph = async (options) => {
186
+ if (!this.conceptSystem)
187
+ throw new Error('Knowledge Layer not initialized');
188
+ return await this.conceptSystem.getConceptGraph(options);
189
+ };
190
+ // Git bridge
191
+ vfs.exportToGit = async (vfsPath, gitPath) => {
192
+ if (!this.gitBridge)
193
+ throw new Error('Knowledge Layer not initialized');
194
+ return await this.gitBridge.exportToGit(vfsPath, gitPath);
195
+ };
196
+ vfs.importFromGit = async (gitPath, vfsPath) => {
197
+ if (!this.gitBridge)
198
+ throw new Error('Knowledge Layer not initialized');
199
+ return await this.gitBridge.importFromGit(gitPath, vfsPath);
200
+ };
201
+ // Temporal coupling
202
+ vfs.findTemporalCoupling = async (path, windowMs) => {
203
+ if (!this.eventRecorder)
204
+ throw new Error('Knowledge Layer not initialized');
205
+ return await this.eventRecorder.findTemporalCoupling(path, windowMs);
206
+ };
207
+ }
208
+ isSemanticChange(oldContent, newContent) {
209
+ // Simple heuristic - significant size change or different content
210
+ const oldStr = oldContent.toString('utf8');
211
+ const newStr = newContent.toString('utf8');
212
+ // Check for significant size change (>10%)
213
+ const sizeDiff = Math.abs(oldStr.length - newStr.length) / oldStr.length;
214
+ if (sizeDiff > 0.1)
215
+ return true;
216
+ // Check for structural changes (simplified)
217
+ const oldLines = oldStr.split('\n').filter(l => l.trim());
218
+ const newLines = newStr.split('\n').filter(l => l.trim());
219
+ // Different number of non-empty lines
220
+ return Math.abs(oldLines.length - newLines.length) > 5;
221
+ }
222
+ async cleanup(brain) {
223
+ const vfs = brain.vfs?.();
224
+ if (!vfs)
225
+ return;
226
+ // Restore original methods
227
+ for (const [methodName, original] of this.originalMethods) {
228
+ vfs[methodName] = original;
229
+ }
230
+ // Remove added methods
231
+ delete vfs.getHistory;
232
+ delete vfs.reconstructAtTime;
233
+ delete vfs.getVersions;
234
+ delete vfs.restoreVersion;
235
+ delete vfs.findEntity;
236
+ delete vfs.getEntityAppearances;
237
+ delete vfs.getConcepts;
238
+ delete vfs.getConceptGraph;
239
+ delete vfs.exportToGit;
240
+ delete vfs.importFromGit;
241
+ delete vfs.findTemporalCoupling;
242
+ // Clean up components
243
+ this.eventRecorder = undefined;
244
+ this.semanticVersioning = undefined;
245
+ this.entitySystem = undefined;
246
+ this.conceptSystem = undefined;
247
+ this.gitBridge = undefined;
248
+ console.log('Knowledge Layer augmentation removed');
249
+ }
250
+ }
251
+ //# sourceMappingURL=KnowledgeAugmentation.js.map
@@ -2,7 +2,7 @@
2
2
  * 🧠 BRAINY EMBEDDED TYPE EMBEDDINGS
3
3
  *
4
4
  * AUTO-GENERATED - DO NOT EDIT
5
- * Generated: 2025-10-10T01:27:22.642Z
5
+ * Generated: 2025-10-15T19:24:11.910Z
6
6
  * Noun Types: 31
7
7
  * Verb Types: 40
8
8
  *
@@ -2,7 +2,7 @@
2
2
  * 🧠 BRAINY EMBEDDED TYPE EMBEDDINGS
3
3
  *
4
4
  * AUTO-GENERATED - DO NOT EDIT
5
- * Generated: 2025-10-10T01:27:22.642Z
5
+ * Generated: 2025-10-15T19:24:11.910Z
6
6
  * Noun Types: 31
7
7
  * Verb Types: 40
8
8
  *
@@ -15,7 +15,7 @@ export const TYPE_METADATA = {
15
15
  verbTypes: 40,
16
16
  totalTypes: 71,
17
17
  embeddingDimensions: 384,
18
- generatedAt: "2025-10-10T01:27:22.642Z",
18
+ generatedAt: "2025-10-15T19:24:11.910Z",
19
19
  sizeBytes: {
20
20
  embeddings: 109056,
21
21
  base64: 145408
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Type-Aware Storage Adapter
3
+ *
4
+ * Implements type-first storage architecture for billion-scale optimization
5
+ *
6
+ * Key Features:
7
+ * - Type-first paths: entities/nouns/{type}/vectors/{shard}/{uuid}.json
8
+ * - Fixed-size type tracking: Uint32Array(31) for nouns, Uint32Array(40) for verbs
9
+ * - O(1) type filtering: Can list entities by type via directory structure
10
+ * - Zero technical debt: Clean implementation, no legacy paths
11
+ *
12
+ * Memory Impact @ 1B Scale:
13
+ * - Type tracking: 284 bytes (vs ~120KB with Maps) = -99.76%
14
+ * - Metadata index: 3GB (vs 5GB) = -40% (when combined with TypeFirstMetadataIndex)
15
+ * - Total system: 69GB (vs 557GB) = -88%
16
+ *
17
+ * @version 3.45.0
18
+ * @since Phase 1 - Type-First Implementation
19
+ */
20
+ import { BaseStorage } from '../baseStorage.js';
21
+ import { GraphVerb, HNSWNoun, HNSWVerb, StatisticsData } from '../../coreTypes.js';
22
+ import { NounType, VerbType } from '../../types/graphTypes.js';
23
+ /**
24
+ * Options for TypeAwareStorageAdapter
25
+ */
26
+ export interface TypeAwareStorageOptions {
27
+ /**
28
+ * Underlying storage adapter to delegate file operations to
29
+ * (e.g., FileSystemStorage, S3CompatibleStorage, MemoryStorage)
30
+ */
31
+ underlyingStorage: BaseStorage;
32
+ /**
33
+ * Optional: Enable verbose logging for debugging
34
+ */
35
+ verbose?: boolean;
36
+ }
37
+ /**
38
+ * Type-Aware Storage Adapter
39
+ *
40
+ * Wraps an underlying storage adapter and adds type-first routing
41
+ * Tracks types with fixed-size arrays for billion-scale efficiency
42
+ */
43
+ export declare class TypeAwareStorageAdapter extends BaseStorage {
44
+ private underlying;
45
+ private verbose;
46
+ private nounCountsByType;
47
+ private verbCountsByType;
48
+ private nounTypeCache;
49
+ private verbTypeCache;
50
+ constructor(options: TypeAwareStorageOptions);
51
+ /**
52
+ * Helper to access protected methods on underlying storage
53
+ * TypeScript doesn't allow calling protected methods across instances,
54
+ * so we cast to any to bypass this restriction
55
+ */
56
+ private get u();
57
+ /**
58
+ * Initialize storage adapter
59
+ */
60
+ init(): Promise<void>;
61
+ /**
62
+ * Load type statistics from storage
63
+ * Rebuilds type counts if needed
64
+ */
65
+ private loadTypeStatistics;
66
+ /**
67
+ * Save type statistics to storage
68
+ */
69
+ private saveTypeStatistics;
70
+ /**
71
+ * Get noun type from noun object or cache
72
+ */
73
+ private getNounType;
74
+ /**
75
+ * Get verb type from verb object or cache
76
+ */
77
+ private getVerbType;
78
+ /**
79
+ * Save noun (type-first path)
80
+ */
81
+ protected saveNoun_internal(noun: HNSWNoun): Promise<void>;
82
+ /**
83
+ * Get noun (type-first path)
84
+ */
85
+ protected getNoun_internal(id: string): Promise<HNSWNoun | null>;
86
+ /**
87
+ * Get nouns by noun type (O(1) with type-first paths!)
88
+ */
89
+ protected getNounsByNounType_internal(nounType: string): Promise<HNSWNoun[]>;
90
+ /**
91
+ * Delete noun (type-first path)
92
+ */
93
+ protected deleteNoun_internal(id: string): Promise<void>;
94
+ /**
95
+ * Save verb (type-first path)
96
+ */
97
+ protected saveVerb_internal(verb: HNSWVerb): Promise<void>;
98
+ /**
99
+ * Get verb (type-first path)
100
+ */
101
+ protected getVerb_internal(id: string): Promise<HNSWVerb | null>;
102
+ /**
103
+ * Get verbs by source
104
+ */
105
+ protected getVerbsBySource_internal(sourceId: string): Promise<GraphVerb[]>;
106
+ /**
107
+ * Get verbs by target
108
+ */
109
+ protected getVerbsByTarget_internal(targetId: string): Promise<GraphVerb[]>;
110
+ /**
111
+ * Get verbs by type (O(1) with type-first paths!)
112
+ */
113
+ protected getVerbsByType_internal(verbType: string): Promise<GraphVerb[]>;
114
+ /**
115
+ * Delete verb (type-first path)
116
+ */
117
+ protected deleteVerb_internal(id: string): Promise<void>;
118
+ /**
119
+ * Write object to path (delegate to underlying storage)
120
+ */
121
+ protected writeObjectToPath(path: string, data: any): Promise<void>;
122
+ /**
123
+ * Read object from path (delegate to underlying storage)
124
+ */
125
+ protected readObjectFromPath(path: string): Promise<any | null>;
126
+ /**
127
+ * Delete object from path (delegate to underlying storage)
128
+ */
129
+ protected deleteObjectFromPath(path: string): Promise<void>;
130
+ /**
131
+ * List objects under path (delegate to underlying storage)
132
+ */
133
+ protected listObjectsUnderPath(prefix: string): Promise<string[]>;
134
+ /**
135
+ * Save statistics data
136
+ */
137
+ protected saveStatisticsData(statistics: StatisticsData): Promise<void>;
138
+ /**
139
+ * Get statistics data
140
+ */
141
+ protected getStatisticsData(): Promise<StatisticsData | null>;
142
+ /**
143
+ * Clear all data
144
+ */
145
+ clear(): Promise<void>;
146
+ /**
147
+ * Get storage status
148
+ */
149
+ getStorageStatus(): Promise<{
150
+ type: string;
151
+ used: number;
152
+ quota: number | null;
153
+ details?: Record<string, any>;
154
+ }>;
155
+ /**
156
+ * Initialize counts from storage
157
+ */
158
+ protected initializeCounts(): Promise<void>;
159
+ /**
160
+ * Persist counts to storage
161
+ */
162
+ protected persistCounts(): Promise<void>;
163
+ /**
164
+ * Get noun vector (delegate to underlying storage)
165
+ */
166
+ getNounVector(id: string): Promise<number[] | null>;
167
+ /**
168
+ * Save HNSW data for a noun
169
+ */
170
+ saveHNSWData(nounId: string, hnswData: {
171
+ level: number;
172
+ connections: Record<string, string[]>;
173
+ }): Promise<void>;
174
+ /**
175
+ * Get HNSW data for a noun
176
+ */
177
+ getHNSWData(nounId: string): Promise<{
178
+ level: number;
179
+ connections: Record<string, string[]>;
180
+ } | null>;
181
+ /**
182
+ * Save HNSW system data (entry point, max level)
183
+ */
184
+ saveHNSWSystem(systemData: {
185
+ entryPointId: string | null;
186
+ maxLevel: number;
187
+ }): Promise<void>;
188
+ /**
189
+ * Get HNSW system data
190
+ */
191
+ getHNSWSystem(): Promise<{
192
+ entryPointId: string | null;
193
+ maxLevel: number;
194
+ } | null>;
195
+ /**
196
+ * Get type statistics
197
+ * Useful for analytics and optimization
198
+ */
199
+ getTypeStatistics(): {
200
+ nouns: Array<{
201
+ type: NounType;
202
+ count: number;
203
+ }>;
204
+ verbs: Array<{
205
+ type: VerbType;
206
+ count: number;
207
+ }>;
208
+ totalMemory: number;
209
+ };
210
+ }