diff --git a/src/augmentationPipeline.ts b/src/augmentationPipeline.ts index 1d879122..cc44ab4c 100644 --- a/src/augmentationPipeline.ts +++ b/src/augmentationPipeline.ts @@ -1,48 +1,23 @@ /** - * Cortex - The Brain's Orchestration System + * Augmentation Pipeline (Compatibility Layer) * - * 🧠⚛️ The cerebral cortex that coordinates all augmentations + * @deprecated This file provides backward compatibility for code that imports + * from augmentationPipeline. All new code should use AugmentationRegistry directly. * - * This module provides the central coordination system for managing and executing - * augmentations across all categories. Like the brain's cortex, it orchestrates - * different capabilities (augmentations) in sequence or parallel. - * - * @deprecated AugmentationPipeline - Use Cortex instead + * This minimal implementation redirects to the new AugmentationRegistry system. */ -import { - BrainyAugmentations, - IAugmentation, - IWebSocketSupport, - AugmentationResponse, - AugmentationType -} from './types/augmentations.js' -import { isThreadingAvailable, isBrowser, isNode } from './utils/environment.js' -import { executeInThread } from './utils/workerUtils.js' +import { BrainyAugmentation } from './types/augmentations.js' /** - * Type definitions for the augmentation registry - */ -type AugmentationRegistry = { - sense: BrainyAugmentations.ISenseAugmentation[] - conduit: BrainyAugmentations.IConduitAugmentation[] - cognition: BrainyAugmentations.ICognitionAugmentation[] - memory: BrainyAugmentations.IMemoryAugmentation[] - perception: BrainyAugmentations.IPerceptionAugmentation[] - dialog: BrainyAugmentations.IDialogAugmentation[] - activation: BrainyAugmentations.IActivationAugmentation[] - webSocket: IWebSocketSupport[] -} - -/** - * Execution mode for the pipeline + * Execution mode for pipeline operations */ export enum ExecutionMode { SEQUENTIAL = 'sequential', PARALLEL = 'parallel', FIRST_SUCCESS = 'firstSuccess', FIRST_RESULT = 'firstResult', - THREADED = 'threaded' // Execute in separate threads when available + THREADED = 'threaded' } /** @@ -51,925 +26,129 @@ export enum ExecutionMode { export interface PipelineOptions { mode?: ExecutionMode timeout?: number - stopOnError?: boolean - forceThreading?: boolean // Force threading even if not in THREADED mode - disableThreading?: boolean // Disable threading even if in THREADED mode + retries?: number + throwOnError?: boolean } /** - * Default pipeline options - */ -const DEFAULT_PIPELINE_OPTIONS: PipelineOptions = { - mode: ExecutionMode.SEQUENTIAL, - timeout: 30000, - stopOnError: false, - forceThreading: false, - disableThreading: false -} - -/** - * Cortex class - The Brain's Orchestration Center - * - * Manages all augmentations like the cerebral cortex coordinates different brain regions. - * This is the central pipeline that orchestrates all augmentation execution. + * Minimal Cortex class for backward compatibility + * Redirects all operations to the new AugmentationRegistry system */ export class Cortex { - private registry: AugmentationRegistry = { - sense: [], - conduit: [], - cognition: [], - memory: [], - perception: [], - dialog: [], - activation: [], - webSocket: [] - } + private static instance?: Cortex - /** - * Register an augmentation with the cortex - * - * @param augmentation The augmentation to register - * @returns The cortex instance for chaining - */ - public register( - augmentation: T - ): Cortex { - let registered = false - - // Check for specific augmentation types - if ( - this.isAugmentationType( - augmentation, - 'processRawData', - 'listenToFeed' - ) - ) { - this.registry.sense.push(augmentation) - registered = true - } else if ( - this.isAugmentationType( - augmentation, - 'establishConnection', - 'readData', - 'writeData', - 'monitorStream' - ) - ) { - this.registry.conduit.push(augmentation) - registered = true - } else if ( - this.isAugmentationType( - augmentation, - 'reason', - 'infer', - 'executeLogic' - ) - ) { - this.registry.cognition.push(augmentation) - registered = true - } else if ( - this.isAugmentationType( - augmentation, - 'storeData', - 'retrieveData', - 'updateData', - 'deleteData', - 'listDataKeys' - ) - ) { - this.registry.memory.push(augmentation) - registered = true - } else if ( - this.isAugmentationType( - augmentation, - 'interpret', - 'organize', - 'generateVisualization' - ) - ) { - this.registry.perception.push(augmentation) - registered = true - } else if ( - this.isAugmentationType( - augmentation, - 'processUserInput', - 'generateResponse', - 'manageContext' - ) - ) { - this.registry.dialog.push(augmentation) - registered = true - } else if ( - this.isAugmentationType( - augmentation, - 'triggerAction', - 'generateOutput', - 'interactExternal' - ) - ) { - this.registry.activation.push(augmentation) - registered = true + constructor() { + if (Cortex.instance) { + return Cortex.instance } - - // Check if the augmentation supports WebSocket - if ( - this.isAugmentationType( - augmentation, - 'connectWebSocket', - 'sendWebSocketMessage', - 'onWebSocketMessage', - 'closeWebSocket' - ) - ) { - this.registry.webSocket.push(augmentation as IWebSocketSupport) - registered = true - } - - // If the augmentation wasn't registered as any known type, throw an error - if (!registered) { - throw new Error(`Unknown augmentation type: ${augmentation.name}`) - } - - return this + Cortex.instance = this } /** - * Unregister an augmentation from the pipeline - * - * @param augmentationName The name of the augmentation to unregister - * @returns The pipeline instance for chaining + * Get all available augmentation types (returns empty for compatibility) + * @deprecated Use brain.augmentations instead */ - public unregister(augmentationName: string): Cortex { - let found = false - - // Remove from all registries - for (const type in this.registry) { - const typedRegistry = this.registry[type as keyof AugmentationRegistry] - const index = typedRegistry.findIndex( - (aug) => aug.name === augmentationName - ) - - if (index !== -1) { - typedRegistry.splice(index, 1) - found = true - } - } - - return this + public getAvailableAugmentationTypes(): string[] { + console.warn('getAvailableAugmentationTypes is deprecated. Use brain.augmentations instead.') + return [] } /** - * Initialize all registered augmentations - * - * @returns A promise that resolves when all augmentations are initialized + * Get augmentations by type (returns empty for compatibility) + * @deprecated Use brain.augmentations instead */ - public async initialize(): Promise { - const allAugmentations = this.getAllAugmentations() - - await Promise.all( - allAugmentations.map((augmentation) => - augmentation.initialize().catch((error) => { - console.error( - `Failed to initialize augmentation ${augmentation.name}:`, - error - ) - }) - ) - ) + public getAugmentationsByType(type: string): BrainyAugmentation[] { + console.warn('getAugmentationsByType is deprecated. Use brain.augmentations instead.') + return [] } /** - * Shut down all registered augmentations - * - * @returns A promise that resolves when all augmentations are shut down - */ - public async shutDown(): Promise { - const allAugmentations = this.getAllAugmentations() - - await Promise.all( - allAugmentations.map((augmentation) => - augmentation.shutDown().catch((error) => { - console.error( - `Failed to shut down augmentation ${augmentation.name}:`, - error - ) - }) - ) - ) - } - - /** - * Execute a sense pipeline - * - * @param method The method to execute on each sense augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executeSensePipeline< - M extends keyof BrainyAugmentations.ISenseAugmentation & string, - R extends BrainyAugmentations.ISenseAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.ISenseAugmentation[M] extends (...args: any[]) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.ISenseAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.ISenseAugmentation, - M, - R - >(this.registry.sense, method, args, opts) - } - - /** - * Execute a conduit pipeline - * - * @param method The method to execute on each conduit augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executeConduitPipeline< - M extends keyof BrainyAugmentations.IConduitAugmentation & string, - R extends BrainyAugmentations.IConduitAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.IConduitAugmentation[M] extends ( - ...args: any[] - ) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.IConduitAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.IConduitAugmentation, - M, - R - >(this.registry.conduit, method, args, opts) - } - - /** - * Execute a cognition pipeline - * - * @param method The method to execute on each cognition augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executeCognitionPipeline< - M extends keyof BrainyAugmentations.ICognitionAugmentation & string, - R extends BrainyAugmentations.ICognitionAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.ICognitionAugmentation[M] extends ( - ...args: any[] - ) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.ICognitionAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.ICognitionAugmentation, - M, - R - >(this.registry.cognition, method, args, opts) - } - - /** - * Execute a memory pipeline - * - * @param method The method to execute on each memory augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executeMemoryPipeline< - M extends keyof BrainyAugmentations.IMemoryAugmentation & string, - R extends BrainyAugmentations.IMemoryAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.IMemoryAugmentation[M] extends ( - ...args: any[] - ) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.IMemoryAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.IMemoryAugmentation, - M, - R - >(this.registry.memory, method, args, opts) - } - - /** - * Execute a perception pipeline - * - * @param method The method to execute on each perception augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executePerceptionPipeline< - M extends keyof BrainyAugmentations.IPerceptionAugmentation & string, - R extends BrainyAugmentations.IPerceptionAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.IPerceptionAugmentation[M] extends ( - ...args: any[] - ) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.IPerceptionAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.IPerceptionAugmentation, - M, - R - >(this.registry.perception, method, args, opts) - } - - /** - * Execute a dialog pipeline - * - * @param method The method to execute on each dialog augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executeDialogPipeline< - M extends keyof BrainyAugmentations.IDialogAugmentation & string, - R extends BrainyAugmentations.IDialogAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.IDialogAugmentation[M] extends ( - ...args: any[] - ) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.IDialogAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.IDialogAugmentation, - M, - R - >(this.registry.dialog, method, args, opts) - } - - /** - * Execute an activation pipeline - * - * @param method The method to execute on each activation augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - public async executeActivationPipeline< - M extends keyof BrainyAugmentations.IActivationAugmentation & string, - R extends BrainyAugmentations.IActivationAugmentation[M] extends ( - ...args: any[] - ) => AugmentationResponse - ? U - : never - >( - method: M & - (BrainyAugmentations.IActivationAugmentation[M] extends ( - ...args: any[] - ) => any - ? M - : never), - args: Parameters< - Extract< - BrainyAugmentations.IActivationAugmentation[M], - (...args: any[]) => any - > - >, - options: PipelineOptions = {} - ): Promise[]> { - const opts = { ...DEFAULT_PIPELINE_OPTIONS, ...options } - return this.executeTypedPipeline< - BrainyAugmentations.IActivationAugmentation, - M, - R - >(this.registry.activation, method, args, opts) - } - - /** - * Get all registered augmentations - * - * @returns An array of all registered augmentations - */ - public getAllAugmentations(): IAugmentation[] { - // Create a Set to avoid duplicates (an augmentation might be in multiple registries) - const allAugmentations = new Set([ - ...this.registry.sense, - ...this.registry.conduit, - ...this.registry.cognition, - ...this.registry.memory, - ...this.registry.perception, - ...this.registry.dialog, - ...this.registry.activation, - ...this.registry.webSocket - ]) - - // Convert back to array - return Array.from(allAugmentations) - } - - /** - * Get all augmentations of a specific type - * - * @param type The type of augmentation to get - * @returns An array of all augmentations of the specified type - */ - public getAugmentationsByType(type: AugmentationType): IAugmentation[] { - switch (type) { - case AugmentationType.SENSE: - return [...this.registry.sense] - case AugmentationType.CONDUIT: - return [...this.registry.conduit] - case AugmentationType.COGNITION: - return [...this.registry.cognition] - case AugmentationType.MEMORY: - return [...this.registry.memory] - case AugmentationType.PERCEPTION: - return [...this.registry.perception] - case AugmentationType.DIALOG: - return [...this.registry.dialog] - case AugmentationType.ACTIVATION: - return [...this.registry.activation] - case AugmentationType.WEBSOCKET: - return [...this.registry.webSocket] - default: - return [] - } - } - - /** - * Get all available augmentation types - * - * @returns An array of all augmentation types that have at least one registered augmentation - */ - public getAvailableAugmentationTypes(): AugmentationType[] { - const availableTypes: AugmentationType[] = [] - - if (this.registry.sense.length > 0) - availableTypes.push(AugmentationType.SENSE) - if (this.registry.conduit.length > 0) - availableTypes.push(AugmentationType.CONDUIT) - if (this.registry.cognition.length > 0) - availableTypes.push(AugmentationType.COGNITION) - if (this.registry.memory.length > 0) - availableTypes.push(AugmentationType.MEMORY) - if (this.registry.perception.length > 0) - availableTypes.push(AugmentationType.PERCEPTION) - if (this.registry.dialog.length > 0) - availableTypes.push(AugmentationType.DIALOG) - if (this.registry.activation.length > 0) - availableTypes.push(AugmentationType.ACTIVATION) - if (this.registry.webSocket.length > 0) - availableTypes.push(AugmentationType.WEBSOCKET) - - return availableTypes - } - - /** - * Get all WebSocket-supporting augmentations - * - * @returns An array of all augmentations that support WebSocket connections - */ - public getWebSocketAugmentations(): IWebSocketSupport[] { - return [...this.registry.webSocket] - } - - /** - * Check if an augmentation is of a specific type - * - * @param augmentation The augmentation to check - * @param methods The methods that should be present on the augmentation - * @returns True if the augmentation is of the specified type - */ - private isAugmentationType( - augmentation: IAugmentation, - ...methods: (keyof T)[] - ): augmentation is T { - // First check that the augmentation has all the required base methods - const baseMethodsExist = ['initialize', 'shutDown', 'getStatus'].every( - (method) => typeof (augmentation as any)[method] === 'function' - ) - - if (!baseMethodsExist) { - return false - } - - // Then check that it has all the specific methods for this type - return methods.every( - (method) => typeof (augmentation as any)[method] === 'function' - ) - } - - /** - * Determines if threading should be used based on options and environment - * - * @param options The pipeline options - * @returns True if threading should be used, false otherwise - */ - private shouldUseThreading(options: PipelineOptions): boolean { - // If threading is explicitly disabled, don't use it - if (options.disableThreading) { - return false - } - - // If threading is explicitly forced, use it if available - if (options.forceThreading) { - return isThreadingAvailable() - } - - // If in THREADED mode, use threading if available - if (options.mode === ExecutionMode.THREADED) { - return isThreadingAvailable() - } - - // Otherwise, don't use threading - return false - } - - /** - * Execute a pipeline for a specific augmentation type - * - * @param augmentations The augmentations to execute - * @param method The method to execute on each augmentation - * @param args The arguments to pass to the method - * @param options The pipeline execution options - * @returns A promise that resolves with the results from all augmentations - */ - private async executeTypedPipeline< - T extends IAugmentation, - M extends keyof T & string, - R extends T[M] extends (...args: any[]) => AugmentationResponse - ? U - : never - >( - augmentations: T[], - method: M & (T[M] extends (...args: any[]) => any ? M : never), - args: Parameters any>>, - options: PipelineOptions - ): Promise< - Promise<{ - success: boolean - data: R - error?: string - }>[] - > { - // Filter out disabled augmentations - const enabledAugmentations = augmentations.filter( - (aug) => aug.enabled !== false - ) - - if (enabledAugmentations.length === 0) { - return [] - } - - // Create a function to execute the method on an augmentation - const executeMethod = async ( - augmentation: T - ): Promise<{ - success: boolean - data: R - error?: string - }> => { - try { - // Create a timeout promise if a timeout is specified - const timeoutPromise = options.timeout - ? new Promise<{ - success: boolean - data: R - error?: string - }>((_, reject) => { - setTimeout(() => { - reject( - new Error( - `Timeout executing ${String(method)} on ${augmentation.name}` - ) - ) - }, options.timeout) - }) - : null - - // Check if threading should be used - const useThreading = this.shouldUseThreading(options) - - // Execute the method on the augmentation, using threading if appropriate - let methodPromise: Promise> - - if (useThreading) { - // Execute in a separate thread - try { - // Create a function that can be serialized and executed in a worker - const workerFn = (...workerArgs: any[]) => { - // This function will be stringified and executed in the worker - // It needs to be self-contained - const augFn = augmentation[method as string] as Function - return augFn.apply(augmentation, workerArgs) - } - - methodPromise = executeInThread>( - workerFn.toString(), - args - ) - } catch (threadError) { - console.warn( - `Failed to execute in thread, falling back to main thread: ${threadError}` - ) - // Fall back to executing in the main thread - methodPromise = Promise.resolve( - (augmentation[method] as Function)( - ...args - ) as AugmentationResponse - ) - } - } else { - // Execute in the main thread - methodPromise = Promise.resolve( - (augmentation[method] as Function)( - ...args - ) as AugmentationResponse - ) - } - - // Race the method promise against the timeout promise if a timeout is specified - const result = timeoutPromise - ? await Promise.race([methodPromise, timeoutPromise]) - : await methodPromise - - return result - } catch (error) { - console.error( - `Error executing ${String(method)} on ${augmentation.name}:`, - error - ) - return { - success: false, - data: null as unknown as R, - error: error instanceof Error ? error.message : String(error) - } - } - } - - // Execute the pipeline based on the specified mode - switch (options.mode) { - case ExecutionMode.PARALLEL: - // Execute all augmentations in parallel - return enabledAugmentations.map(executeMethod) - - case ExecutionMode.THREADED: - // Execute all augmentations in parallel with threading enabled - // Force threading for this mode - const threadedOptions = { ...options, forceThreading: true } - - // Create a new executeMethod function that uses the threaded options - const executeMethodThreaded = async (augmentation: T) => { - // Save the original options - const originalOptions = options - - // Set the options to the threaded options - options = threadedOptions - - // Execute the method - const result = await executeMethod(augmentation) - - // Restore the original options - options = originalOptions - - return result - } - - return enabledAugmentations.map(executeMethodThreaded) - - case ExecutionMode.FIRST_SUCCESS: - // Execute augmentations sequentially until one succeeds - for (const augmentation of enabledAugmentations) { - const resultPromise = executeMethod(augmentation) - const result = await resultPromise - if (result.success) { - return [resultPromise] - } - } - return [] - - case ExecutionMode.FIRST_RESULT: - // Execute augmentations sequentially until one returns a result - for (const augmentation of enabledAugmentations) { - const resultPromise = executeMethod(augmentation) - const result = await resultPromise - if (result.success && result.data) { - return [resultPromise] - } - } - return [] - - case ExecutionMode.SEQUENTIAL: - default: - // Execute augmentations sequentially - const results: Promise<{ - success: boolean - data: R - error?: string - }>[] = [] - for (const augmentation of enabledAugmentations) { - const resultPromise = executeMethod(augmentation) - results.push(resultPromise) - - // Check if we need to stop on error - if (options.stopOnError) { - const result = await resultPromise - if (!result.success) { - break - } - } - } - return results - } - } - - /** - * Enable an augmentation by name - * - * @param name The name of the augmentation to enable - * @returns True if augmentation was found and enabled - */ - public enableAugmentation(name: string): boolean { - for (const type of Object.keys(this.registry) as (keyof AugmentationRegistry)[]) { - const augmentation = this.registry[type].find(aug => aug.name === name) - if (augmentation) { - augmentation.enabled = true - return true - } - } - return false - } - - /** - * Disable an augmentation by name - * - * @param name The name of the augmentation to disable - * @returns True if augmentation was found and disabled - */ - public disableAugmentation(name: string): boolean { - for (const type of Object.keys(this.registry) as (keyof AugmentationRegistry)[]) { - const augmentation = this.registry[type].find(aug => aug.name === name) - if (augmentation) { - augmentation.enabled = false - return true - } - } - return false - } - - /** - * Check if an augmentation is enabled - * - * @param name The name of the augmentation to check - * @returns True if augmentation is found and enabled, false otherwise + * Check if augmentation is enabled (returns false for compatibility) + * @deprecated Use brain.augmentations instead */ public isAugmentationEnabled(name: string): boolean { - for (const type of Object.keys(this.registry) as (keyof AugmentationRegistry)[]) { - const augmentation = this.registry[type].find(aug => aug.name === name) - if (augmentation) { - return augmentation.enabled - } - } + console.warn('isAugmentationEnabled is deprecated. Use brain.augmentations instead.') return false } /** - * Get all augmentations with their enabled status - * - * @returns Array of augmentations with name, type, and enabled status + * List augmentations with status (returns empty for compatibility) + * @deprecated Use brain.augmentations instead */ public listAugmentationsWithStatus(): Array<{ name: string - type: keyof AugmentationRegistry + type: string enabled: boolean description: string }> { - const result: Array<{ - name: string - type: keyof AugmentationRegistry - enabled: boolean - description: string - }> = [] - - for (const [type, augmentations] of Object.entries(this.registry) as Array<[keyof AugmentationRegistry, IAugmentation[]]>) { - for (const aug of augmentations) { - result.push({ - name: aug.name, - type: type, - enabled: aug.enabled, - description: aug.description - }) - } - } - - return result + console.warn('listAugmentationsWithStatus is deprecated. Use brain.augmentations instead.') + return [] } /** - * Enable all augmentations of a specific type - * - * @param type The type of augmentations to enable - * @returns Number of augmentations enabled + * Execute augmentations (compatibility method) + * @deprecated Use brain.augmentations.execute instead */ - public enableAugmentationType(type: keyof AugmentationRegistry): number { - let count = 0 - for (const aug of this.registry[type]) { - aug.enabled = true - count++ - } - return count + public async executeAugmentations( + operation: string, + data: any, + options?: PipelineOptions + ): Promise { + console.warn('executeAugmentations is deprecated. Use brain.augmentations.execute instead.') + return data as T } /** - * Disable all augmentations of a specific type - * - * @param type The type of augmentations to disable - * @returns Number of augmentations disabled + * Enable augmentation (compatibility method) + * @deprecated Use brain.augmentations instead */ - public disableAugmentationType(type: keyof AugmentationRegistry): number { - let count = 0 - for (const aug of this.registry[type]) { - aug.enabled = false - count++ - } - return count + public enableAugmentation(name: string): boolean { + console.warn('enableAugmentation is deprecated. Use brain.augmentations instead.') + return false + } + + /** + * Disable augmentation (compatibility method) + * @deprecated Use brain.augmentations instead + */ + public disableAugmentation(name: string): boolean { + console.warn('disableAugmentation is deprecated. Use brain.augmentations instead.') + return false + } + + /** + * Register augmentation (compatibility method) + * @deprecated Use brain.augmentations.register instead + */ + public register(augmentation: BrainyAugmentation): void { + console.warn('register is deprecated. Use brain.augmentations.register instead.') + } + + /** + * Unregister augmentation (compatibility method) + * @deprecated Use brain.augmentations instead + */ + public unregister(name: string): boolean { + console.warn('unregister is deprecated. Use brain.augmentations instead.') + return false + } + + /** + * Enable augmentation type (compatibility method) + * @deprecated Use brain.augmentations instead + */ + public enableAugmentationType(type: string): number { + console.warn('enableAugmentationType is deprecated. Use brain.augmentations instead.') + return 0 + } + + /** + * Disable augmentation type (compatibility method) + * @deprecated Use brain.augmentations instead + */ + public disableAugmentationType(type: string): number { + console.warn('disableAugmentationType is deprecated. Use brain.augmentations instead.') + return 0 } } @@ -979,3 +158,6 @@ export const cortex = new Cortex() // Backward compatibility exports export const AugmentationPipeline = Cortex export const augmentationPipeline = cortex + +// Export types for compatibility (avoid duplicate export) +// PipelineOptions already exported above \ No newline at end of file diff --git a/src/augmentationRegistry.ts b/src/augmentationRegistry.ts index b8199758..060bbf4a 100644 --- a/src/augmentationRegistry.ts +++ b/src/augmentationRegistry.ts @@ -1,122 +1,63 @@ /** - * Augmentation Registry + * Augmentation Registry (Compatibility Layer) * - * This module provides a registry for augmentations that are loaded at build time. - * It replaces the dynamic loading mechanism in pluginLoader.ts. + * @deprecated This module provides backward compatibility for old augmentation + * loading code. All new code should use the AugmentationRegistry class directly + * on BrainyData instances. */ -import { IPipeline } from './types/pipelineTypes.js' -import { AugmentationType, IAugmentation } from './types/augmentations.js' - -// Forward declaration of the pipeline instance to avoid circular dependency -// The actual pipeline will be provided when initializeAugmentationPipeline is called -let defaultPipeline: IPipeline | null = null +import { BrainyAugmentation } from './types/augmentations.js' /** - * Sets the default pipeline instance - * This function should be called from pipeline.ts after the pipeline is created + * Registry of all available augmentations (for compatibility) + * @deprecated Use brain.augmentations instead */ -export function setDefaultPipeline(pipeline: IPipeline): void { - defaultPipeline = pipeline -} +export const availableAugmentations: any[] = [] /** - * Registry of all available augmentations + * Compatibility wrapper for registerAugmentation + * @deprecated Use brain.augmentations.register instead */ -export const availableAugmentations: IAugmentation[] = [] - -/** - * Registers an augmentation with the registry - * - * @param augmentation The augmentation to register - * @returns The augmentation that was registered - */ -export function registerAugmentation(augmentation: T): T { - // Set enabled to true by default if not specified - if (augmentation.enabled === undefined) { - augmentation.enabled = true - } - - // Add to the registry +export function registerAugmentation(augmentation: T): T { + console.warn('registerAugmentation is deprecated. Use brain.augmentations.register instead.') + + // For compatibility, just add to the list (but it won't actually do anything) availableAugmentations.push(augmentation) return augmentation } /** - * Initializes the augmentation pipeline with all registered augmentations - * - * @param pipeline Optional custom pipeline to use instead of the default - * @returns The pipeline that was initialized - * @throws Error if no pipeline is provided and the default pipeline hasn't been set + * Sets the default pipeline instance (compatibility) + * @deprecated Use brain.augmentations instead */ -export function initializeAugmentationPipeline( - pipelineInstance?: IPipeline -): IPipeline { - // Use the provided pipeline or fall back to the default - const pipeline = pipelineInstance || defaultPipeline - - if (!pipeline) { - throw new Error('No pipeline provided and default pipeline not set. Call setDefaultPipeline first.') - } - - // Register all augmentations with the pipeline - for (const augmentation of availableAugmentations) { - if (augmentation.enabled) { - pipeline.register(augmentation) - } - } - - return pipeline +export function setDefaultPipeline(pipeline: any): void { + console.warn('setDefaultPipeline is deprecated. Use brain.augmentations instead.') } /** - * Enables or disables an augmentation by name - * - * @param name The name of the augmentation to enable/disable - * @param enabled Whether to enable or disable the augmentation - * @returns True if the augmentation was found and updated, false otherwise + * Initializes the augmentation pipeline (compatibility) + * @deprecated Use brain.augmentations instead + */ +export function initializeAugmentationPipeline(pipelineInstance?: any): any { + console.warn('initializeAugmentationPipeline is deprecated. Use brain.augmentations instead.') + return pipelineInstance || {} +} + +/** + * Enables or disables an augmentation by name (compatibility) + * @deprecated Use brain.augmentations instead */ export function setAugmentationEnabled(name: string, enabled: boolean): boolean { - const augmentation = availableAugmentations.find(aug => aug.name === name) - - if (augmentation) { - augmentation.enabled = enabled - return true - } - + console.warn('setAugmentationEnabled is deprecated. Use brain.augmentations instead.') return false } /** - * Gets all augmentations of a specific type - * - * @param type The type of augmentation to get - * @returns An array of all augmentations of the specified type + * Gets all augmentations of a specific type (compatibility) + * @deprecated Use brain.augmentations instead */ -export function getAugmentationsByType(type: AugmentationType): IAugmentation[] { - return availableAugmentations.filter(aug => { - // Check if the augmentation is of the specified type - // This is a simplified check and may need to be updated based on how types are determined - switch (type) { - case AugmentationType.SENSE: - return 'processRawData' in aug && 'listenToFeed' in aug - case AugmentationType.CONDUIT: - return 'establishConnection' in aug && 'readData' in aug && 'writeData' in aug - case AugmentationType.COGNITION: - return 'reason' in aug && 'infer' in aug && 'executeLogic' in aug - case AugmentationType.MEMORY: - return 'storeData' in aug && 'retrieveData' in aug && 'updateData' in aug - case AugmentationType.PERCEPTION: - return 'interpret' in aug && 'organize' in aug && 'generateVisualization' in aug - case AugmentationType.DIALOG: - return 'processUserInput' in aug && 'generateResponse' in aug && 'manageContext' in aug - case AugmentationType.ACTIVATION: - return 'triggerAction' in aug && 'generateOutput' in aug && 'interactExternal' in aug - case AugmentationType.WEBSOCKET: - return 'connectWebSocket' in aug && 'sendWebSocketMessage' in aug && 'onWebSocketMessage' in aug - default: - return false - } - }) +export function getAugmentationsByType(type: any): any[] { + console.warn('getAugmentationsByType is deprecated. Use brain.augmentations instead.') + return [] } diff --git a/src/augmentations/apiServerAugmentation.ts b/src/augmentations/apiServerAugmentation.ts index 5f0ee75b..e73f84c0 100644 --- a/src/augmentations/apiServerAugmentation.ts +++ b/src/augmentations/apiServerAugmentation.ts @@ -120,13 +120,13 @@ export class APIServerAugmentation extends BaseAugmentation { return } - const { WebSocketServer } = ws + const WebSocketServer = ws?.WebSocketServer || ws?.default?.WebSocketServer const app = express.default() // Middleware app.use(cors.default(this.config.cors)) - app.use(express.json({ limit: '50mb' })) + app.use((express.default || express).json({ limit: '50mb' })) app.use(this.authMiddleware.bind(this)) app.use(this.rateLimitMiddleware.bind(this)) diff --git a/src/augmentations/cacheAugmentation.ts b/src/augmentations/cacheAugmentation.ts index a4fdd6c9..c6a3e22d 100644 --- a/src/augmentations/cacheAugmentation.ts +++ b/src/augmentations/cacheAugmentation.ts @@ -17,7 +17,6 @@ export interface CacheConfig { ttl?: number enabled?: boolean invalidateOnWrite?: boolean - memoryLimit?: number } /** @@ -45,7 +44,6 @@ export class CacheAugmentation extends BaseAugmentation { ttl: 300000, // 5 minutes default enabled: true, invalidateOnWrite: true, - memoryLimit: 50 * 1024 * 1024, // 50MB default ...config } } @@ -60,7 +58,7 @@ export class CacheAugmentation extends BaseAugmentation { this.searchCache = new SearchCache({ maxSize: this.config.maxSize!, maxAge: this.config.ttl!, // SearchCache uses maxAge, not ttl - memoryLimit: this.config.memoryLimit + enabled: true }) this.log(`Cache augmentation initialized (maxSize: ${this.config.maxSize}, ttl: ${this.config.ttl}ms)`) @@ -180,7 +178,6 @@ export class CacheAugmentation extends BaseAugmentation { const stats = this.searchCache.getStats() return { - enabled: true, ...stats, memoryUsage: this.searchCache.getMemoryUsage() } @@ -206,7 +203,7 @@ export class CacheAugmentation extends BaseAugmentation { this.searchCache.updateConfig({ maxSize: this.config.maxSize!, maxAge: this.config.ttl!, // SearchCache uses maxAge - memoryLimit: this.config.memoryLimit + enabled: this.config.enabled }) this.log('Cache configuration updated') } diff --git a/src/augmentations/conduitAugmentations.ts b/src/augmentations/conduitAugmentations.ts index d656760e..5cf47df8 100644 --- a/src/augmentations/conduitAugmentations.ts +++ b/src/augmentations/conduitAugmentations.ts @@ -21,7 +21,7 @@ export interface WebSocketConnection { */ abstract class BaseConduitAugmentation extends BaseAugmentation { readonly timing = 'after' as const // Conduits run after operations to sync - readonly operations = ['addNoun', 'deleteNoun', 'addVerb'] as ('addNoun' | 'deleteNoun' | 'addVerb')[] + readonly operations = ['addNoun', 'delete', 'addVerb'] as ('addNoun' | 'delete' | 'addVerb')[] readonly priority = 20 // Medium-low priority protected connections = new Map() diff --git a/src/augmentations/indexAugmentation.ts b/src/augmentations/indexAugmentation.ts index 97519c24..2b42464b 100644 --- a/src/augmentations/indexAugmentation.ts +++ b/src/augmentations/indexAugmentation.ts @@ -37,7 +37,7 @@ export class IndexAugmentation extends BaseAugmentation { private metadataIndex: MetadataIndexManager | null = null private config: IndexConfig - private flushTimer: NodeJS.Timer | null = null + private flushTimer: NodeJS.Timeout | null = null constructor(config: IndexConfig = {}) { super() @@ -68,7 +68,7 @@ export class IndexAugmentation extends BaseAugmentation { this.metadataIndex = new MetadataIndexManager( storage as StorageAdapter, { - maxFieldValues: this.config.maxFieldValues + maxIndexSize: this.config.maxIndexSize || 10000 } ) @@ -86,7 +86,7 @@ export class IndexAugmentation extends BaseAugmentation { this.log(`Index rebuilt: ${newStats.totalEntries} entries, ${newStats.fieldsIndexed.length} fields`) } } catch (e) { - this.log('Could not check storage statistics', 'debug') + this.log('Could not check storage statistics', 'info') } } } @@ -166,7 +166,7 @@ export class IndexAugmentation extends BaseAugmentation { const { id, metadata } = params if (id && metadata) { await this.metadataIndex.addToIndex(id, metadata) - this.log(`Indexed metadata for ${id}`, 'debug') + this.log(`Indexed metadata for ${id}`, 'info') } } @@ -186,7 +186,7 @@ export class IndexAugmentation extends BaseAugmentation { // Add new metadata if (id && newMetadata) { await this.metadataIndex.addToIndex(id, newMetadata) - this.log(`Reindexed metadata for ${id}`, 'debug') + this.log(`Reindexed metadata for ${id}`, 'info') } } @@ -199,7 +199,7 @@ export class IndexAugmentation extends BaseAugmentation { const { id, metadata } = params if (id && metadata) { await this.metadataIndex.removeFromIndex(id, metadata) - this.log(`Removed ${id} from index`, 'debug') + this.log(`Removed ${id} from index`, 'info') } } @@ -295,7 +295,7 @@ export class IndexAugmentation extends BaseAugmentation { async flush(): Promise { if (this.metadataIndex) { await this.metadataIndex.flush() - this.log('Index flushed to storage', 'debug') + this.log('Index flushed to storage', 'info') } } diff --git a/src/augmentations/metricsAugmentation.ts b/src/augmentations/metricsAugmentation.ts index 43218efd..69aa1c61 100644 --- a/src/augmentations/metricsAugmentation.ts +++ b/src/augmentations/metricsAugmentation.ts @@ -39,7 +39,7 @@ export class MetricsAugmentation extends BaseAugmentation { private statisticsCollector: StatisticsCollector | null = null private config: MetricsConfig - private metricsTimer: NodeJS.Timer | null = null + private metricsTimer: NodeJS.Timeout | null = null constructor(config: MetricsConfig = {}) { super() @@ -74,7 +74,7 @@ export class MetricsAugmentation extends BaseAugmentation { this.log('Loaded existing metrics from storage') } } catch (e) { - this.log('Could not load existing metrics', 'debug') + this.log('Could not load existing metrics', 'info') } } @@ -172,7 +172,7 @@ export class MetricsAugmentation extends BaseAugmentation { this.statisticsCollector.trackVerbType(params.metadata.verb) } - this.log(`Add operation completed in ${duration}ms`, 'debug') + this.log(`Add operation completed in ${duration}ms`, 'info') } /** @@ -183,7 +183,7 @@ export class MetricsAugmentation extends BaseAugmentation { const { query } = params this.statisticsCollector.trackSearch(query || '', duration) - this.log(`Search completed in ${duration}ms`, 'debug') + this.log(`Search completed in ${duration}ms`, 'info') } /** @@ -193,7 +193,7 @@ export class MetricsAugmentation extends BaseAugmentation { if (!this.statisticsCollector) return this.statisticsCollector.trackUpdate() - this.log(`Delete operation completed in ${duration}ms`, 'debug') + this.log(`Delete operation completed in ${duration}ms`, 'info') } /** @@ -245,7 +245,7 @@ export class MetricsAugmentation extends BaseAugmentation { }) } } catch (e) { - this.log('Could not update storage metrics', 'debug') + this.log('Could not update storage metrics', 'info') } } @@ -259,9 +259,9 @@ export class MetricsAugmentation extends BaseAugmentation { const stats = this.statisticsCollector.getStatistics() // Storage adapters can optionally store these metrics // This is a no-op for adapters that don't support it - this.log('Metrics persisted to storage', 'debug') + this.log('Metrics persisted to storage', 'info') } catch (e) { - this.log('Could not persist metrics', 'debug') + this.log('Could not persist metrics', 'info') } } diff --git a/src/neural/embeddedPatterns.ts b/src/neural/embeddedPatterns.ts index 8ca5f303..123d844f 100644 --- a/src/neural/embeddedPatterns.ts +++ b/src/neural/embeddedPatterns.ts @@ -2,7 +2,7 @@ * 🧠 BRAINY EMBEDDED PATTERNS * * AUTO-GENERATED - DO NOT EDIT - * Generated: 2025-08-25T17:15:55.893Z + * Generated: 2025-08-25T18:15:58.736Z * Patterns: 220 * Coverage: 94-98% of all queries *