@soulcraft/brainy 3.43.1 → 3.43.2

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.
@@ -1,251 +0,0 @@
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
@@ -1,52 +0,0 @@
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
- }
@@ -1,10 +0,0 @@
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
@@ -1,203 +0,0 @@
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
- }